Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created February 9, 2014 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/8901218 to your computer and use it in GitHub Desktop.
Save xuwei-k/8901218 to your computer and use it in GitHub Desktop.
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