Skip to content

Instantly share code, notes, and snippets.

@jido
Created October 4, 2010 15:10
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 jido/609842 to your computer and use it in GitHub Desktop.
Save jido/609842 to your computer and use it in GitHub Desktop.
# Dodo code, imperative style
# ---
String s = ""
loop for (int n = 1; n < 100; ++.n)
{
test
{
n % 4 = 0:
continue.
n = 13:
.s = s + n
break.
default:
.s = s + n + ", ".
}
}
return s
# Dodo code, CPS transformation
# ---
"" -> s
# Note: s is captured by the loop and mutated by it, hence the String.
fun (int n, String s -> break(String)
{
$forloop(++n, _) -> continue # curried recursive call
n < 100 ->
n % 4 = 0 ->
continue(s)
|
n = 13 ->
s + n -> s
break(s);
|
s + n + ", " -> s
continue(s);
;
;
|
break(s)
}) -> forloop
forloop(1, s) -> s
return(s)
# Clojure code
# ---
"""
(trampoline
(let [s ""]
; Note: s is captured by the loop and mutated by it, hence the String.
(letfn [(forloop [n, s, break]
(letfn [(continue [s] #(forloop (inc n) s break))]
(if (< n 100)
(if (zero? (rem n 4))
#(continue s)
(if (= n 13)
#(break (str s n))
#(continue (str s n ", "))))
#(break s))))]
(forloop 1 s)))
"""
# Output
# ---
"1, 2, 3, 5, 6, 7, 9, 10, 11, 13"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment