add generator example
This commit is contained in:
@@ -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)
|
||||||
|
)
|
||||||
|
)
|
||||||
+22
-5
@@ -1,24 +1,41 @@
|
|||||||
(
|
(
|
||||||
; This is an example implementation of itoa using a buffer of characters
|
; This is an example implementation of itoa using a buffer of characters
|
||||||
(ld r0 -123456789)
|
(ld r0 -123456789)
|
||||||
|
|
||||||
(mkbf r1)
|
(mkbf r1)
|
||||||
(call itoa r1 r0)
|
(call itoa r1 r0)
|
||||||
|
|
||||||
; print it
|
; print it
|
||||||
(:pn) (bfrpop @cout @r1 (em? (ld @cout '\n') (halt))) (j :pn)
|
(:pn) (bfrpop @cout @r1 (em? (ld @cout '\n') (halt))) (j :pn)
|
||||||
(halt)
|
(halt)
|
||||||
|
|
||||||
(proc itoa buf num
|
(proc itoa buf num
|
||||||
(ld r1 num)
|
(ld r1 num)
|
||||||
(tst r1 (<0? (mul r1 -1)))
|
(tst r1 (<0? (mul r1 -1)))
|
||||||
(:next)
|
(:next)
|
||||||
(mod r0 r1 10)
|
(mod r0 r1 10)
|
||||||
(add r0 '0')
|
(add r0 '0')
|
||||||
(bfrpush @buf r0)
|
(bfrpush @buf r0)
|
||||||
(div r1 10 (z?
|
(div r1 10 (z?
|
||||||
(tst num (<0? (bfrpush @buf '-')))
|
(tst num (<0? (bfrpush @buf '-')))
|
||||||
(ret)))
|
(ret)))
|
||||||
(j :next)
|
(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)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user