Tail Recursion with continuation -


how convert following ml code tail recursive function? have stared @ , tried figure out couple hours , can't see how to.

datatype tree = null | node of tree*tree | val of int; fun dup(null) = null  | dup(val(y)) = node(val(y),val(y))  | dup(node(y1,y2)) = node(dup(y1), dup(y2)); 

transforming continuation-passing style (relatively) straightforward here - recursion tricky case.

rewriting right-hand side makes easier see pattern.

| dup (node (y1, y2)) = let val left = dup y1                             val right = dup y2                         in                             node (left, right) 

we need grab both left , right , combine them afterwards.
difference in cps pass along function receives these values instead of receiving them directly, let continuation given handle result.

naming continuation "return", can this:

fun dup_cont null return = return null (* trivial *)     (* duplicate value , return *)   | dup_cont (val y) return = return (node (val y, val y))     (* recurse, grab result.        recurse again, grab result.        combine 2 results , return *)   | dup_cont (node (y1, y2)) return =          dup_cont y1 (fn left => dup_cont y2 (fn right => return (node (left, right)))) 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -