您的位置:首页 > 其它

Scala By Example: Case 类与模式匹配 习题

2011-03-03 12:44 483 查看
1: abstract class IntTree


2: case object EmptyTree extends IntTree


3: case class Node(elem: Int, left: IntTree, right: IntTree) extends IntTree


4:


5: def contains(t: IntTree, v: Int): Boolean = t match {


6:     case EmptyTree => false


7:     case Node(e, l, r) => e == v || contains(l, v) || contains(r, v)


8: }


9:


10: def insert(t: IntTree, v: Int): IntTree = t match {


11:     case EmptyTree => Node(v, EmptyTree, EmptyTree)


12:     case Node(e, l, r) =>


13:         if(e == v) t


14:         else if(e > v) Node(e, insert(l, v), r)


15:         else Node(e, l, insert(r, v))


16: }


目前为止最简单的习题了,不解释。好的编程语言就像说话一样自然!
Technorati 标签: Scala
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: