Anonymous recursion: Difference between revisions
Content added Content deleted
(→{{header|Perl 6}}: mention how the sequence operator "checks for negative") |
No edit summary |
||
Line 436: | Line 436: | ||
<lang haskell>ghci> map fib [-4..10] |
<lang haskell>ghci> map fib [-4..10] |
||
[Nothing,Nothing,Nothing,Nothing,Just 1,Just 1,Just 2,Just 3,Just 5,Just 8,Just 13,Just 21,Just 34,Just 55,Just 89]</lang> |
[Nothing,Nothing,Nothing,Nothing,Just 1,Just 1,Just 2,Just 3,Just 5,Just 8,Just 13,Just 21,Just 34,Just 55,Just 89]</lang> |
||
=={{header|Icon}} and {{header|Unicon}}== |
|||
The following solution works in both languages. The a cache is used |
|||
to improve performance. |
|||
<lang unicon>procedure main(A) |
|||
every write("fib(",a := numeric(!A),")=",fib(a)) |
|||
end |
|||
procedure fib(n) |
|||
local source, i |
|||
static cache |
|||
initial { |
|||
cache := table() |
|||
cache[0] := 0 |
|||
cache[1] := 1 |
|||
} |
|||
if type(n) == "integer" & n >= 0 then |
|||
return n @ makeProc {{ |
|||
i := @(source := &source) |
|||
if /cache[i] then cache[i] := ((i-1)@makeProc(^¤t) + |
|||
(i-2)@makeProc(^¤t)) |
|||
cache[i] @ source |
|||
}} |
|||
end |
|||
procedure makeProc(A) |
|||
A := if type(A) == "list" then A[1] |
|||
return (@A, A) # prime and return |
|||
end</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |