利用模式匹配和递归计算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))
阅读全文
0 0
- 利用模式匹配和递归计算list
- scala 模式匹配之Type、Array、List和Tuple
- scala 模式匹配之Type、Array、List和Tuple
- 利用递归计算三角数字
- Scala模式匹配,case 字符串,case 匹配类型,case 匹配数组,case 匹配List,case 匹配元组,case匹配case class和case object
- 利用递归计算N的阶乘
- 利用递归树计算递归算法的复杂度
- 递归过程和递归计算过程
- C 递归和倒序计算
- 循环计算和递归计算阶乘
- 计算电磁学数值模式匹配算法实现
- mysql中的模式匹配,利用正则表达式
- 递归匹配 和 e修饰符
- 正则表达式话题2--递归和匹配
- scala中的正则匹配和模式匹配
- 单模式匹配KMP求匹配位置和匹配数目
- 路径和模式匹配.avi
- 朴素模式匹配和KMP
- Ubuntu 10.10下的飞鸽传书-iptux
- 容器核心技术详解
- 大型分布式系统的优化解决方案
- 并发程序设计01——基本概念
- C#.NET调用jar包(java环境配置及ikvm安装)
- 利用模式匹配和递归计算list
- C++指针1.1
- 进阶篇:4.2)面向高速自动化装配设计;
- AndroidStudio配置NDK/JNI开发环境
- ELK(ElasticSearch, Logstash, Kibana)搭建实时日志分析平台
- JavaScript中的设计模式之代理模式
- 线程与进程的区别
- Java线程池
- 控制文本输入框最多输入10个字符长度(即五个汉字)