Skip to content

Instantly share code, notes, and snippets.

@ClarkeRemy
Last active May 3, 2024 20:11
Show Gist options
  • Save ClarkeRemy/7b2e7e059c8f45e31aba8ce40ff47bc8 to your computer and use it in GitHub Desktop.
Save ClarkeRemy/7b2e7e059c8f45e31aba8ce40ff47bc8 to your computer and use it in GitHub Desktop.
Continuation passing style flatten sml
datatype 'a Tree =
Leaf
| Branch of {value : 'a, left : 'a Tree, right : 'a Tree}
fun infix_flatten t = case t of
Leaf => []
| Branch {value, left, right} => let
val l = infix_flatten left
val r = infix_flatten right
in
l @ (value :: r)
end
val my_tree: int Tree =
Branch {
value = 2,
left = Branch { value = 1, left = Leaf, right = Leaf},
right = Branch {
value = 4,
left = Branch { value = 3, left = Leaf, right = Leaf},
right = Leaf}
}
fun infix_flatten2 tree = recur tree (fn x => x)
and recur Leaf k = k []
| recur (Branch {value, left, right}) k =
recur left (fn l_ret =>
recur right (fn r_ret =>
k (l_ret @ (value :: r_ret))))
;
infix_flatten my_tree
;
infix_flatten2 my_tree
;
fun fact n = if n <= 1
then 1
else n * fact (n - 1)
fun fact_tail_rec n = loop n 1
and loop n acc = if n <= 1
then acc
else loop (n-1) (acc * n)
(*
let (n,acc) = (n,1);
loop {
if n <= 1 { break acc }
else { (n, acc) = (n-1, acc * n) }
}
*)
fun fact_tail_rec n = loop n (fn x => x)
and loop n k = if n <= 1
then k 1
else loop (n-1) (fn ret => k(n*ret))
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment