about summary refs log tree commit diff stats
path: root/continuation5.mu
diff options
context:
space:
mode:
Diffstat (limited to 'continuation5.mu')
-rw-r--r--continuation5.mu39
1 files changed, 39 insertions, 0 deletions
diff --git a/continuation5.mu b/continuation5.mu
new file mode 100644
index 00000000..fb00a4f5
--- /dev/null
+++ b/continuation5.mu
@@ -0,0 +1,39 @@
+# Example program showing that a 'paused' continuation can be 'resumed' with
+# ingredients.
+#
+# Print out a list of numbers, first adding 0 to the first, 1 to the second, 2
+# to the third, and so on.
+
+def main [
+  local-scope
+  l:&:list:num <- copy 0
+  l <- push 3, l
+  l <- push 2, l
+  l <- push 1, l
+  k:continuation, x:num, done?:bool <- call-with-continuation-mark create-yielder, l
+  a:num <- copy 1
+  {
+    break-if done?
+    $print x 10/newline
+    k, x:num, done?:bool <- call k, a  # resume; x = a + next l value
+    a <- add a, 1
+    loop
+  }
+]
+
+def create-yielder l:&:list:num -> n:num, done?:bool [
+  local-scope
+  load-ingredients
+  a:num <- copy 0
+  {
+    done? <- equal l, 0
+    break-if done?
+    n <- first l
+    l <- rest l
+    n <- add n, a
+    a <- return-continuation-until-mark n, done?  # pause/resume
+    loop
+  }
+  return-continuation-until-mark -1, done?
+  assert 0/false, [called too many times, ran out of continuations to return]
+]