Mercurial > lbo > hg > ylisp
changeset 172:d7fe74faaa7a
example: Play with "generator function"
author | Lewin Bormann <lbo@spheniscida.de> |
---|---|
date | Mon, 09 Sep 2019 19:52:37 +0200 |
parents | 92c4365ce0b2 |
children | 800a02381024 |
files | test.yl |
diffstat | 1 files changed, 18 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/test.yl Tue Sep 03 20:20:06 2019 +0200 +++ b/test.yl Mon Sep 09 19:52:37 2019 +0200 @@ -13,12 +13,29 @@ ") (defn pow (a b) - (let next (- b 1)) (if (== b 0) 1 ((* a (pow a (- b 1)))) ) ) +(defn sum-to (n) + (if (== n 0) 0 ((+ n (sum-to (- n 1)))))) + -- Here we output it (print (fac 13) newline) (print (pow 2 10) newline) +(print (sum-to 100) newline) + +-- This produces a "generator function", yielding numbers from 0 to n. +-- This only works once, however, as `counter` is statically allocated. +-- TODO: Implement built-in to dynamically create references. +(defn make-gen (n) + (let counter 0) + (let max n) -- we can't reference the argument in a closure :\ + (defn increment () (if (== counter max) ((undef)) ((let counter (+ counter 1)) counter))) + increment) + +(let my-gen (make-gen 10)) +(let my-gen2 (make-gen 10)) +(print (my-gen) (my-gen) (my-gen) (my-gen2)) +(print newline)