delay vs. generate - yield
On Date: 01 Mar 2009 14:37:58 +0100 Martin Rubey wrote:
[Due to] the absence of Generators in SPAD, [here is] a
mini-tutorial for delay$Stream
, which is a partial replacement.
delay
takes a function f:() -> Stream
, and evaluates it
lazily. Warning: it won't work in the interpreter.
Simplest example I can think of:
fricas
(1) -> <spad>
fricas
)abb package TEST Test
Test(): with
f: Integer -> Stream Integer
== add
f n == delay cons(n, f(n+1))</spad>
fricas
Compiling FriCAS source code from file
/var/lib/zope2.10/instance/axiom-wiki/var/LatexWiki/4237768559018105081-25px001.spad
using old system compiler.
TEST abbreviates package Test
------------------------------------------------------------------------
initializing NRLIB TEST for Test
compiling into NRLIB TEST
compiling exported f : Integer -> Stream Integer
Time: 0 SEC.
(time taken in buildFunctor: 0)
;;; *** |Test| REDEFINED
;;; *** |Test| REDEFINED
Time: 0 SEC.
Cumulative Statistics for Constructor Test
Time: 0 seconds
finalizing NRLIB TEST
Processing Test for Browser database:
--->-->Test(constructor): Not documented!!!!
--->-->Test((f ((Stream (Integer)) (Integer)))): Not documented!!!!
--->-->Test(): Missing Description
; compiling file "/var/aw/var/LatexWiki/TEST.NRLIB/TEST.lsp" (written 02 DEC 2024 12:32:47 PM):
; wrote /var/aw/var/LatexWiki/TEST.NRLIB/TEST.fasl
; compilation finished in 0:00:00.008
------------------------------------------------------------------------
Test is now explicitly exposed in frame initial
Test will be automatically loaded when needed from
/var/aw/var/LatexWiki/TEST.NRLIB/TEST
then'f 1' will return '[1,...]?'.
fricas
f 1
Type: Stream(Integer)
Of course the actual output depends on your setting of
)set stream calculate
, which is usually 10. "lazy"
always happens when "delay" is encountered. I.e., when
the number of already computed elements is not large
enough, computation continues until the number of
computed elements is large enough and then until
a "delay" is encountered again.
Thus, the aldor style:
f() == generate {
block1;
yield a;
block2;
yield b;
}
}
could become:
f() == f1()
f1() == delay
block1
cons(a, f2())
f2() == delay
block2
[b]::Stream R