利用模式匹配和递归计算list

来源:互联网 发布:java图形用户界面设计 编辑:程序博客网 时间:2024/06/03 22:57
val l = List(List(9,8),8,List(12)) def leafSum(l: List[Any]): Int = l.map(_ match {   case l: List[Any] => leafSum(l)   case x: Int => x   case _ => 0 }).sum println(leafSum(l))
/****************************************/
//使用新方法实现
sealed abstract class BinaryTreecase class Leaf(value: Int) extends BinaryTreecase class Node(left:BinaryTree,right: BinaryTree) extends BinaryTreeval n = Node(Node(Leaf(3),Leaf(8)),Leaf(5))def leafSum(bt:BinaryTree):Int = bt match {  case Node(left,right) => leafSum(left) + leafSum(right)  case Leaf(value) => value}print( leafSum(n) == 16)
/*******************************/
//扩展使每个节点可以有任意多的后代
sealed abstract class BinaryTreecase class Leaf(value: Int) extends BinaryTreecase class Node(bt:BinaryTree*) extends BinaryTreeval n = Node(Node(Leaf(3),Leaf(5)),Leaf(2),Node(Leaf(5)))def leafSum(bt:BinaryTree):Int = bt match {  case Node(bts @ _*) => bts.map(leafSum).sum  case Leaf(value) => value}print( leafSum(n))

/********************************************/
//每个非叶子节点存放操作符
sealed abstract class BinaryTreecase class Leaf(value: Int) extends BinaryTreecase class Node(operator: Char,bt:BinaryTree*) extends BinaryTreeval n = Node('+', Node('*', Leaf(3), Leaf(8)), Leaf(2), Node('-', Leaf(5)))def eval(bt:BinaryTree):Int = bt match {  case Node('+',bts @ _*) => bts.map(eval).sum  case Node('-',bts @ _*) => bts.map(eval).foldLeft(0)(_ - _)  case Node('*',bts @ _*) => bts.map(eval).product  case Leaf(value) => value  case _ => 0}print( eval(n))


原创粉丝点击