Created
February 9, 2014 16:05
-
-
Save xuwei-k/8901218 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package scalaz | |
import Free.Trampoline | |
object Main extends App{ | |
def fff = CTree(1,Map(2 -> CTree(3, Map()))).map(identity) | |
println(fff) | |
} | |
final case class CTree[@specialized(Double) V](root: V, | |
children: Map[Int, CTree[V]] = Map.empty[Int, CTree[V]]){ | |
def map[A](f: V => A): CTree[A] = walk(this, f).run | |
protected def walk[A](tree: CTree[V], f: V => A): Trampoline[CTree[A]] = tree match { | |
case CTree(value, childs) if childs.isEmpty => Trampoline.done(CTree(f(value))) | |
case CTree(value, childs) => step(childs.toList, f) map (CTree(f(value), _)) | |
} | |
protected def step[A](trees: List[(Int, CTree[V])], | |
f: V => A, | |
acc: List[(Int, CTree[A])] = Nil): Trampoline[Map[Int, CTree[A]]] = trees match { | |
case (id, head) :: tail => for { | |
that <- Trampoline.suspend(walk(head, f)) | |
remainder <- Trampoline.suspend(step(tail, f, (id, that) :: acc)) | |
} yield remainder | |
case Nil => Trampoline.done(acc.toMap) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment