fork download
  1. object Main extends App {
  2. abstract class Tree {
  3. val datum: Int
  4. val left: Tree
  5. val right: Tree
  6.  
  7. def isEmpty: Boolean
  8.  
  9. def insert(newDatum: Int): Tree = {
  10. if(datum < newDatum)
  11. Node(datum, left, right insert newDatum)
  12. else if(datum > newDatum)
  13. Node(datum, left insert newDatum, right)
  14. }
  15.  
  16. def fold[A](init: A)(fn: (A,Int) => A): A = this.isEmpty match {
  17. case false => (right fold fn((left fold init)(fn), datum))(fn)
  18. case _ => init
  19. }
  20.  
  21. def merge(t: Tree) = (this fold t)(_ insert _)
  22. override def toString = (this fold "")(_ + _ + ", ")
  23. }
  24.  
  25. object Empty extends Tree {
  26. lazy val right = throw new Exception()
  27. lazy val left = throw new Exception()
  28. lazy val datum = throw new Exception()
  29.  
  30. def isEmpty = true
  31.  
  32. override def insert(newDatum: Int) = Node(newDatum, Empty, Empty)
  33. }
  34.  
  35. case class Node(datum: Int, left: Tree, right: Tree) extends Tree {
  36. def isEmpty = false
  37. }
  38.  
  39. object Tree {
  40. def apply(data: Int*) = (data foldLeft (Empty: Tree))(_ insert _)
  41. }
  42.  
  43. println(Tree(5,2,3))
  44.  
  45. println(Tree(5,2,3) merge Tree(6,2,4))
  46. }
Success #stdin #stdout 0.3s 247552KB
stdin
1
2
10
42
11
stdout
2, 3, 5, 
2, 3, 4, 5, 6,