Tree Fold

package tree

object Fold {

  def fold[A, B](t: Tree[A])(f: A => B)(g: (B, B) => B): B = t match {
    case Leaf(a)      => f(a)
    case Branch(l, r) => g(fold(l)(f)(g), fold(r)(f)(g))
  }

  def main(args: Array[String]): Unit = {
    val tree = Branch(Leaf(1), Branch(Branch(Branch(Leaf(3), Branch(Leaf(5), Leaf(6))), Leaf(4)), Leaf(2)))
    println(fold(tree)(_ => 1)(_ + _ + 1))
  }

}
11
时间: 2024-11-10 15:41:22

Tree Fold的相关文章

Linux中CPU与内存性能监测

在系统维护的过程中,随时可能有需要查看 CPU 使用率内存使用情况的需要,尤其是涉及到JVM,程序调优的情况,并根据相应信息分析系统状况的需要. top命令 top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器.运行 top 命令后,CPU 使用状态会以全屏的方式显示,并且会处在对话的模式 -- 用基于 top 的命令,可以控制显示方式等等.退出 top 的命令为 q (在 top 运行中敲 q 键一次). 可以直接使用top命令

Tree MaximumByFold

package tree object MaximumByFold { def maximum(t: Tree[Int]): Int = Fold.fold(t)(a => a)(_ max _) def main(args: Array[String]): Unit = { val tree = Branch(Leaf(1), Branch(Branch(Branch(Leaf(3), Branch(Leaf(5), Leaf(6))), Leaf(4)), Leaf(2))) println

Tree SizeByFold

package tree object SizeByFold { def size[A](t: Tree[A]) = Fold.fold(t)(_ => 1)(_ + _ + 1) def main(args: Array[String]): Unit = { val tree = Branch(Leaf(1), Branch(Branch(Branch(Leaf(3), Branch(Leaf(5), Leaf(6))), Leaf(4)), Leaf(2))) println(size(tr

Tree MapByFold

package tree object MapByFold { def map[A, B](t: Tree[A])(f: A => B): Tree[B] = Fold.fold(t)(a => Leaf(f(a)): Tree[B])(Branch(_, _)) def main(args: Array[String]): Unit = { val tree = Branch(Leaf(1), Branch(Branch(Branch(Leaf(3), Branch(Leaf(5), Lea

Tree DepthByFold

package tree object DepthByFold { def depth[A](t: Tree[A]): Int = Fold.fold(t)(_ => 0)((a, b) => (a max b) + 1) def main(args: Array[String]): Unit = { val tree = Branch(Leaf(1), Branch(Branch(Branch(Leaf(3), Branch(Leaf(5), Leaf(6))), Leaf(4)), Lea

泛函编程(8)-数据结构-Tree

上节介绍了泛函数据结构List及相关的泛函编程函数设计使用,还附带了少许多态类型(Polymorphic Type)及变形(Type Variance)的介绍.有关Polymorphism的详细介绍会放在typeclass讨论中.为了更多了解泛函数据结构(Functional Data Structure),想在这个章节把另一个我们熟悉的数据结构-Tree做些简单介绍. Tree的状态不是枝(Branch)就是叶(Leaf),这个很容易理解.那么就按照上节设计List那样设计Tree类型: 1

easyui js取消选中 Tree 指定节点

取消所有选中 var rootNodes = treeObject.tree('getRoots'); for ( var i = 0; i < rootNodes.length; i++) { var node = treeObject.tree('find', rootNodes[i].id); treeObject.tree('uncheck', node.target); }

Maximum Depth of Binary Tree

这道题为简单题 题目: Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 思路: 我是用递归做的,当然也可以用深搜和广搜,递归的话就是比较左右子树的深度然后返回 代码: 1 # Definition for a binary tre

538. Convert BST to Greater Tree 二叉搜索树转换为更大树

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like thi