Guest User

Untitled

a guest
Jul 17th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. object BinTree {
  2. def apply[T](x: T, y: T*): BinTree[T] = {
  3. @tailrec def construct(args: Seq[BinTree[T]]): BinTree[T] =
  4. args.sliding(2, 2).map {
  5. case Seq(l, r) => Branch(l, r)
  6. case Seq(o) => o
  7. }.toSeq match {
  8. case Seq(m) => m
  9. case xs => construct(xs)
  10. }
  11. construct((x +: y).map(Leaf(_)))
  12. }
  13.  
  14. implicit val foldable: Foldable[BinTree] = new Foldable[BinTree] {
  15. override def foldLeft[A, B](fa: BinTree[A], b: B)(f: (B, A) => B): B = {
  16. def impl(toVisit: List[BinTree[A]], acc: B): B =
  17. if (toVisit.isEmpty) acc
  18. else toVisit.head match {
  19. case Leaf(v) => impl(toVisit.tail, f(acc, v))
  20. case Branch(l, r) => impl(l :: r :: toVisit.tail, acc)
  21. }
  22. impl(fa :: Nil, b)
  23. }
  24.  
  25. override def foldRight[A, B](fa: BinTree[A], lb: Eval[B])(f: (A, Eval[B]) => Eval[B]): Eval[B] = {
  26. fa match {
  27. case Leaf(v) => f(v, lb)
  28. case Branch(l, r) => Eval.defer(foldRight(r, lb)(f) flatMap { e => foldRight(l, Eval.now(e))(f) } )
  29. }
  30. }
  31. }
  32. }
Add Comment
Please, Sign In to add comment