scala - could not optimize @tailrec annotated method loop: it contains a recursive call not in tail position -
i have following recursive function want use tail recursion on it. compiler complains implementation error:error:(79, 7) not optimize @tailrec annotated method loop: contains recursive call not in tail position n match { ^
is because of loop assumes it's not in tail position?
def dsl[n,e](qnodes:qnodelike[n,e]*) = { val markers = scala.collection.mutable.map.empty[string, n] @tailrec def loop(n:qnodelike[n,e]):unit = { n match { case qnode(head, kids:seq[halfedgelike[e,n]]) => { for(kid <- kids){ kid match { case emptyhalfedge() => case halfedge(e, n) => loop(n) } } } case qnodemarker(head, marker, kids:seq[halfedgelike[e,n]]) => { markers.update(marker,head) for(kid <- kids){ kid match { case emptyhalfedge() => case halfedge(e, n) => loop(n) } } } } } loop(qnodes.head) }
yes, that's right. make tail recursive, should use explicit accumulator passed recursion.
however, unless have very deep , narrow trees, unlikely need tail recursive optimization, run time grow large before end stack overflow.
here's rough idea of how make tail optimized:
@tailrec def loop(n:list[qnodelike[n,e]]):unit = { n match { case qnode(head, kids:seq[halfedgelike[e,n]]) :: rem => { kids match { case nil => case emptyhalfedge() :: rem2 => loop(rem2 ::: rem) case halfedge(e, n) :: rem2 => loop(n :: rem2 ::: rem) } } case qnodemarker(head, marker, kids:seq[halfedgelike[e,n]]) :: rem => { markers.update(marker,head) kids match { case nil => case emptyhalfedge() :: rem2 => loop(rem2 ::: rem) case halfedge(e, n) :: rem2 => loop(n :: rem2 ::: rem) } } case nil => } }
Comments
Post a Comment