From af52270a29cacd56a3a915239e906927ed85774d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Sat, 31 Oct 2020 18:17:50 +0100 Subject: [PATCH] add generator example --- examples/coroutines2.csn | 44 ++++++++++++++++++++++++++++++++++++++++ examples/itoa.csn | 27 +++++++++++++++++++----- 2 files changed, 66 insertions(+), 5 deletions(-) create mode 100644 examples/coroutines2.csn diff --git a/examples/coroutines2.csn b/examples/coroutines2.csn new file mode 100644 index 0000000..c1d32f6 --- /dev/null +++ b/examples/coroutines2.csn @@ -0,0 +1,44 @@ +( + ; using a coroutine as a generator + + (spawn r15 fibo) + + (ld r0 20) + (:next) + + (ld r1 @r15) ; Read a yielded value + (call printnum r1) + (lds @cout ", ") + + (dec r0) + (j.nz :next) + (ld @cout '\n') + (halt) + + (proc fibo + (ld r0 0) + (ld r1 1) + (:x) + (yield r1) + (add r2 r0 r1) + (ld r0 r1) + (ld r1 r2) + (j :x) + ) + + (proc printnum num + (mkbf r15) + (ld r1 num) + (tst r1 (<0? (mul r1 -1))) + (:next) + (mod r0 r1 10) + (add r0 '0') + (bfrpush @r15 r0) + (div r1 10 (z? + (tst num (<0? (bfrpush @r15 '-'))) + (lds @cout @r15) + (del @r15) + (ret))) + (j :next) + ) +) diff --git a/examples/itoa.csn b/examples/itoa.csn index b5f63ef..66c58ba 100644 --- a/examples/itoa.csn +++ b/examples/itoa.csn @@ -1,24 +1,41 @@ ( ; This is an example implementation of itoa using a buffer of characters (ld r0 -123456789) - + (mkbf r1) (call itoa r1 r0) - + ; print it (:pn) (bfrpop @cout @r1 (em? (ld @cout '\n') (halt))) (j :pn) (halt) - - (proc itoa buf num + + (proc itoa buf num (ld r1 num) (tst r1 (<0? (mul r1 -1))) (:next) (mod r0 r1 10) (add r0 '0') (bfrpush @buf r0) - (div r1 10 (z? + (div r1 10 (z? (tst num (<0? (bfrpush @buf '-'))) (ret))) (j :next) ) + + ; other version that prints it + (proc printnum num + (mkbf r15) + (ld r1 num) + (tst r1 (<0? (mul r1 -1))) + (:next) + (mod r0 r1 10) + (add r0 '0') + (bfrpush @r15 r0) + (div r1 10 (z? + (tst num (<0? (bfrpush @r15 '-'))) + (lds @cout @r15) + (del @r15) + (ret))) + (j :next) + ) )