42 lines
1.1 KiB
Plaintext
42 lines
1.1 KiB
Plaintext
% Generate Fibonacci numbers
|
|
fib = iter () yields (int)
|
|
a: int := 0
|
|
b: int := 1
|
|
|
|
while true do
|
|
yield (a)
|
|
a, b := b, a+b
|
|
end
|
|
end fib
|
|
|
|
% Grab the n'th value from an iterator
|
|
nth = proc [T: type] (g: itertype () yields (T), n: int) returns (T)
|
|
for v: T in g() do
|
|
if n<=0 then return (v) end
|
|
n := n-1
|
|
end
|
|
end nth
|
|
|
|
% Print a few values
|
|
start_up = proc ()
|
|
po: stream := stream$primary_output()
|
|
|
|
% print values coming out of the fibonacci iterator
|
|
% (which are generated one after the other without delay)
|
|
count: int := 0
|
|
for f: int in fib() do
|
|
stream$putl(po, "F(" || int$unparse(count) || ") = " || int$unparse(f))
|
|
count := count + 1
|
|
if count = 15 then break end
|
|
end
|
|
|
|
% print a few random fibonacci numbers
|
|
% (to do this it has to restart at the beginning for each
|
|
% number, making it O(N))
|
|
fibs: sequence[int] := sequence[int]$[20,30,50]
|
|
for n: int in sequence[int]$elements(fibs) do
|
|
stream$putl(po, "F(" || int$unparse(n) || ") = "
|
|
|| int$unparse(nth[int](fib, n)))
|
|
end
|
|
end start_up
|