Anonymous user
Anonymous recursion: Difference between revisions
m
→{{header|Elena}}
imported>Arakov |
|||
(44 intermediate revisions by 24 users not shown) | |||
Line 18:
;Task:
If possible, demonstrate this by writing the recursive version of the fibonacci function (see [[Fibonacci sequence]]) which checks for a negative argument before doing the actual recursion.
;Related tasks:
:* [[Y combinator]]
<br><br>
=={{header|11l}}==
{{trans|C++}}
<
F f(Int n) -> Int
I n < 2
Line 30 ⟶ 33:
L(i) 0..20
print(fib(i), end' ‘ ’)</
{{out}}
<pre>
Line 40 ⟶ 43:
Better would be to use type Natural instead of Integer, which lets Ada do the magic of checking the valid range.
<
function Actual_Fib (N: in Integer) return Integer is
begin
Line 55 ⟶ 58:
return Actual_Fib (X);
end if;
end Fib;</
=={{header|ALGOL 68}}==
{{Trans|Ada}}
<
IF x < 0
THEN
Line 74 ⟶ 77:
actual fibonacci( x )
FI;
</syntaxhighlight>
=={{header|APL}}==
Line 82 ⟶ 85:
though they are not quite first-class objects (you can't have an array of functions for example).
<
⍵<0:⎕SIGNAL 11 ⍝ DOMAIN ERROR if argument < 0
{ ⍝ Inner (anonymous) function
Line 88 ⟶ 91:
(∇⍵-1)+∇⍵-2 ⍝ ∇ = anonymous recursive call
}⍵ ⍝ Call function in place
}</
=={{header|AppleScript}}==
<
-- For the sake of the task, a needlessly anonymous local script object containing a needlessly recursive handler.
-- The script could easily (and ideally should) be assigned to a local variable.
Line 125 ⟶ 128:
fibonacci(15) --> {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}
fibonacci(-15) --> {0, -1, -1, -2, -3, -5, -8, -13, -21, -34, -55, -89, -144, -233, -377, -610}</
Or, as the recursion of an anonymous declarative function, enabled by the Y combinator:
<
on run
Line 282 ⟶ 285:
set my text item delimiters to dlm
s
end unlines</
{{Out}}
<pre>missing value, missing value, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765</pre>
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">fib: function [x][
; Using scoped function fibI inside fib
fibI: function [n][
(n<2)? -> n -> add fibI n-2 fibI n-1
]
if x < 0 -> panic "Invalid argument"
return fibI x
]
loop 0..4 'x [
print fib x
]</syntaxhighlight>
{{out}}
<pre>0
1
1
2
3</pre>
=={{header|AutoHotkey}}==
<
nold1 := 1
nold2 := 0
Line 310 ⟶ 336:
}
Return t
}</
=={{header|AutoIt}}==
<
ConsoleWrite(Fibonacci(10) & @CRLF) ; ## USAGE EXAMPLE
ConsoleWrite(Fibonacci(20) & @CRLF) ; ## USAGE EXAMPLE
Line 329 ⟶ 355:
EndFunc
</syntaxhighlight>
{{out}}
<pre>
Line 339 ⟶ 365:
=={{header|Axiom}}==
Using the Aldor compiler in Axiom/Fricas:
<
Z ==> Integer;
fib(x:Z):Z == {
Line 345 ⟶ 371:
f(n:Z,v1:Z,v2:Z):Z == if n<2 then v2 else f(n-1,v2,v1+v2);
f(x,1,1);
}</
<
Z ==> Integer
TestPackage : with
Line 355 ⟶ 381:
f : Reference((Z,Z,Z) -> Z) := ref((n, v1, v2) +-> 0)
f() := (n, v1, v2) +-> if n<2 then v2 else f()(n-1,v2,v1+v2)
f()(x,1,1)</
=={{header|
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">
DEF FN fib(x) = FIB(x)
Line 398 ⟶ 424:
'--- using an alias
'fib(9)
</
==={{header|BASIC256}}===
{{trans|AutoIt}}
<syntaxhighlight lang="basic256">print Fibonacci(20)
print Fibonacci(30)
print Fibonacci(-10)
print Fibonacci(10)
end
function Fibonacci(num)
if num < 0 then
print "Invalid argument: ";
return num
end if
if num < 2 then
return num
else
return Fibonacci(num - 1) + Fibonacci(num - 2)
end If
end function</syntaxhighlight>
{{out}}
<pre>6765
832040
Invalid argument: -10
55</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 cls
110 sub fib(num)
120 if num < 0 then print "Invalid argument: "; : fib = num
130 if num < 2 then fib = num else fib = fib(num-1)+fib(num-2)
140 end sub
190 print fib(20)
200 print fib(30)
210 print fib(-10)
220 print fib(10)
230 end</syntaxhighlight>
{{out}}
<pre>Same as BASIC256 entry.</pre>
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
This works by finding a pointer to the 'anonymous' function and calling it indirectly:
<
END
DEF FNfib(n%) IF n%<0 THEN ERROR 100, "Must not be negative"
LOCAL P% : P% = !384 + LEN$!384 + 4 : REM Function pointer
(n%) IF n%<2 THEN = n% ELSE = FN(^P%)(n%-1) + FN(^P%)(n%-2)</
{{out}}
<pre>
55
</pre>
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Fibonacc.bas"
110 FOR I=0 TO 10
120 PRINT FIB(I);
130 NEXT
140 DEF FIB(K)
150 SELECT CASE K
160 CASE IS<0
170 PRINT "Negative parameter to Fibonacci.":STOP
180 CASE 0,1
190 LET FIB=K
200 CASE ELSE
210 LET FIB=FIB(K-1)+FIB(K-2)
220 END SELECT
230 END DEF </syntaxhighlight>
=={{header|Bracmat}}==
===lambda 'light'===
The first solution uses macro substitution. In an expression headed by an apostrophe operator with an empty lhs all subexpressions headed by a dollar operator with empty lhs are replaced by the values that the rhs are bound to, without otherwise evaluating the expression. Example: if <code>(x=7) & (y=4)</code> then <code>'($x+3+$y)</code> becomes <code>=7+3+4</code>. Notice that the solution below utilises no other names than <code>arg</code>, the keyword that always denotes a function's argument. The test for negative or non-numeric arguments is outside the recursive part. The function fails if given negative input.
<
=
. !arg:#:~<0
Line 436 ⟶ 518:
$ 30
)
</syntaxhighlight>
Answer:
<pre>832040</pre>
===pure lambda calculus===
(See http://en.wikipedia.org/wiki/Lambda_calculus). The following solution works almost the same way as the previous solution, but uses lambda calculus
<
' ( x
. $x:#:~<0
Line 461 ⟶ 543:
)
$ 30
)</
Answer:
<pre>832040</pre>
=={{header|BQN}}==
<code>𝕊</code> is a useful symbol in BQN which references the function it is currently in. This can be used to perform anonymous recursion without the need of naming the function block.
The following code calls an anonymous recursive Fibonacci function on each number of the range 0-9.
<syntaxhighlight lang="bqn">{
(𝕩<2)◶⟨+´𝕊¨,𝕏⟩𝕩-1‿2
}¨↕10</syntaxhighlight>
<syntaxhighlight lang="bqn">⟨ 0 1 1 2 3 5 8 13 21 34 ⟩</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=ewogICjwnZWpPDIp4pe24p+oK8K08J2VisKoLPCdlY/in6nwnZWpLTHigL8yCn3CqOKGlTEw Try It!]
Recursion can also be performed using an internal name defined by a header such as <code>Fact:</code> or <code>Fact 𝕩:</code>. This header is visible inside the block but not outside of it, so from the outside the function is anonymous. The named form allows the outer function to be called within nested blocks, while <code>𝕊</code> can only refer to the immediately containing one.
<syntaxhighlight lang="bqn">{Fact 𝕩:
(𝕩<2)◶⟨+´Fact¨,𝕏⟩𝕩-1‿2
}¨↕10</syntaxhighlight>
=={{header|C}}==
Using scoped function fib_i inside fib, with GCC (required version 3.2 or higher):
<
long fib(long x)
Line 495 ⟶ 593:
return 0;
}</
{{out}}
<pre>Bad argument: fib(-1)
Line 505 ⟶ 603:
calling fib_i from outside fib:
This is not the fib you are looking for</pre>
Recursive functions can be defined within [https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html statement expressions]:
<syntaxhighlight lang="c">
#include <stdio.h>
int main(){
int n = 3;
printf("%d",({
int fib(int n){
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
fib(n);
}));
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
The inner recursive function (delegate/lambda) has to be named.
<
static int Fib(int n)
{
Line 517 ⟶ 633:
return fib(n);
}
</syntaxhighlight>
=={{header|C++}}==
In C++ (as of the 2003 version of the standard, possibly earlier), we can declare class within a function scope. By giving that class a public static member function, we can create a function whose symbol name is only known to the function in which the class was derived.
<
{
if(n < 0)
Line 546 ⟶ 662:
return actual_fib::calc(n);
}
}</
{{works with|C++11}}
<
using namespace std;
Line 563 ⟶ 679:
return actual_fib(n);
}</
Using a local function object that calls itself using <code>this</code>:
<
{
if(n < 0)
Line 592 ⟶ 708:
return actual_fib(n);
}
}</
=={{header|Clio}}==
Simple anonymous recursion to print from 9 to 0.
<
if n:
n - 1 -> print -> recall</
=={{header|Clojure}}==
The JVM as of now has no Tail call optimization so the default way of looping in Clojure uses anonymous recursion so not to be confusing.
<
(defn fib [n]
(when (neg? n)
Line 610 ⟶ 726:
v2
(recur (dec n) v2 (+ v1 v2)))))
</syntaxhighlight>
Using an anonymous function
=={{header|CoffeeScript}}==
<
# function call itself.
fibonacci = (n) ->
Line 631 ⟶ 747:
recurse(n-2) + recurse(n-1)
recurse(n)
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 638 ⟶ 754:
This version uses the anaphoric <code>lambda</code> from [http://dunsmor.com/lisp/onlisp/onlisp_18.html Paul Graham's On Lisp].
<
`(labels ((self ,parms ,@body))
#'self))</
The Fibonacci function can then be defined as
<
(assert (>= n 0) nil "'~a' is a negative number" n)
(funcall
Line 651 ⟶ 767:
n
(+ (self (- n 1)) (self (- n 2)))))
n))</
===Using labels===
Line 657 ⟶ 773:
This puts a function in a local label. The function is not anonymous, but not only is it local, so that its name does not pollute the global namespace, but the name can be chosen to be identical to that of the surrounding function, so it is not a newly invented name
<
"Fibonacci sequence function."
(if (< number 0)
Line 665 ⟶ 781:
a
(fib (- n 1) b (+ a b)))))
(fib number 0 1))))</
Although name space polution isn't an issue, in recognition of the obvious convenience of anonymous recursive helpers, here is another solution: add the language feature for anonymously recursive blocks: the operator RECURSIVE, with a built-in local operator RECURSE to make recursive calls.
Here is <code>fib</code> rewritten to use RECURSIVE:
<
"Fibonacci sequence function."
(if (< number 0)
Line 676 ⟶ 792:
(if (= n 0)
a
(recurse (- n 1) b (+ a b))))))</
Implementation of RECURSIVE:
<
(let ((hidden-name (gensym "RECURSIVE-")))
`(macrolet ((recurse (&rest args) `(,',hidden-name ,@args)))
(labels ((,hidden-name (,@(mapcar #'first parm-init-pairs)) ,@body))
(,hidden-name ,@(mapcar #'second parm-init-pairs))))))</
RECURSIVE works by generating a local function with LABELS, but with a machine-generated unique name. Furthermore, it provides syntactic sugar so that the initial call to the recursive function takes place implicitly, and the initial values are specified using LET-like syntax. Of course, if RECURSIVE blocks are nested, each RECURSE refers to its own function. There is no way for an inner RECURSIVE to specify recursion to an other RECURSIVE. That is what names are for!
Line 693 ⟶ 809:
===Using the Y combinator===
<
(symbol-function '!!) (symbol-function 'apply))
Line 756 ⟶ 872:
(1 1)
(otherwise (+ (fib (- n 1))
(fib (- n 2))))))</
=={{header|D}}==
<
assert(arg >= 0);
Line 772 ⟶ 888:
39.fib.writeln;
}</
{{out}}
<pre>63245986</pre>
Line 778 ⟶ 894:
===With Anonymous Class===
In this version anonymous class is created, and by using opCall member function, the anonymous class object can take arguments and act like an anonymous function. The recursion is done by calling opCall inside itself.
<
int fib(in int n) pure nothrow {
Line 795 ⟶ 911:
void main() {
writeln(fib(39));
}</
The output is the same.
Line 801 ⟶ 917:
This puts a function in a local method binding. The function is not anonymous, but the name fib1 is local and never pollutes the outside namespace.
<
define function fib (n)
when (n < 0)
Line 815 ⟶ 931:
fib1(n, 0, 1)
end
</syntaxhighlight>
=={{header|Déjà Vu}}==
===With Y combinator===
<
labda y:
labda:
Line 836 ⟶ 952:
for j range 0 10:
!print fibo j</
===With <code>recurse</code>===
<
n 0 1
labda times back-2 back-1:
Line 852 ⟶ 968:
for j range 0 10:
!print fibo-2 j</
Note that this method starts from 0, while the previous starts from 1.
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
program AnonymousRecursion;
{$APPTYPE CONSOLE}
uses
SysUtils;
function Fib(X: Integer): integer;
function DoFib(N: Integer): Integer;
begin
if N < 2 then Result:=N
else Result:=DoFib(N-1) + DoFib(N-2);
end;
begin
if X < 0 then raise Exception.Create('Argument < 0')
else Result:=DoFib(X);
end;
var I: integer;
begin
for I:=-1 to 15 do
begin
try
WriteLn(I:3,' - ',Fib(I):3);
except WriteLn(I,' - Error'); end;
end;
WriteLn('Hit Any Key');
ReadLn;
end.
</syntaxhighlight>
{{out}}
<pre>
-1 - -1 - Error
0 - 0
1 - 1
2 - 1
3 - 2
4 - 3
5 - 5
6 - 8
7 - 13
8 - 21
9 - 34
10 - 55
11 - 89
12 - 144
13 - 233
14 - 377
15 - 610
Hit Any Key
</pre>
=={{header|EchoLisp}}==
A '''named let''' provides a local lambda via a label.
<
(define (fib n)
(let _fib ((a 1) (b 1) (n n))
Line 864 ⟶ 1,039:
(<= n 1) a
(_fib b (+ a b) (1- n)))))
</syntaxhighlight>
=={{header|Ela}}==
Using fix-point combinator:
<
| else = fix (\f n -> if n < 2 then n else f (n - 1) + f (n - 2)) n</
Function 'fix' is defined in standard Prelude as follows:
<
=={{header|Elena}}==
ELENA
<
fib(n)
{
if (n
{
^ this self(n
}
{
^
}
public program()
{
}</
{{out}}
<pre>
Line 930 ⟶ 1,104:
=={{header|Elixir}}==
With Y-Combinator:
<syntaxhighlight lang="elixir">
fib = fn f -> (
fn x -> if x == 0, do: 0, else: (if x == 1, do: 1, else: f.(x - 1) + f.(x - 2)) end
Line 944 ⟶ 1,118:
IO.inspect y.(&(fib.(&1))).(40)
</syntaxhighlight>
{{out}}
102334155
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun fibonacci = int by int n
if n < 0 do
logLine("Invalid argument: " + n) # logs on standard error
return -1 ^| it should be better to raise an error,
| but the task is about recursive functions
|^
end
fun actualFibonacci = int by int n
return when(n < 2, n, actualFibonacci(n - 1) + actualFibonacci(n - 2))
end
return actualFibonacci(n)
end
writeLine("F(0) = " + fibonacci(0))
writeLine("F(20) = " + fibonacci(20))
writeLine("F(-10) = " + fibonacci(-10))
writeLine("F(30) = " + fibonacci(30))
writeLine("F(10) = " + fibonacci(10))
</syntaxhighlight>
{{out}}
<pre>
F(0) = 0
F(20) = 6765
Invalid argument: -10
F(-10) = -1
F(30) = 832040
F(10) = 55
</pre>
=={{header|Erlang}}==
Two solutions. First fib that use the module to hide its helper. The helper also is called fib so there is no naming problem. Then fib_internal which has the helper function inside itself.
<syntaxhighlight lang="erlang">
-module( anonymous_recursion ).
-export( [fib/1, fib_internal/1] ).
Line 969 ⟶ 1,173:
fib( N, Next, Acc ) -> fib( N - 1, Acc+Next, Next ).
</syntaxhighlight>
=={{header|F Sharp|F#}}==
Line 975 ⟶ 1,179:
The function 'fib2' is only visible inside the 'fib' function.
<
| n when n < 0 -> None
| n -> let rec fib2 = function
| 0 | 1 -> 1
| n -> fib2 (n-1) + fib2 (n-2)
in Some (fib2 n)</
'''Using a fixed point combinator:'''
<
let fib = function
| n when n < 0 -> None
| n -> Some (fix (fun f -> (function | 0 | 1 -> 1 | n -> f (n-1) + f (n-2))) n)</
{{out}}
Both functions have the same output.
<
[null; Some 1; Some 1; Some 2; Some 3; Some 5; Some 8]</
=={{header|Factor}}==
Line 996 ⟶ 1,200:
To achieve anonymous recursion, this solution has a recursive quotation.
<
IN: rosettacode.fibonacci.ar
Line 1,007 ⟶ 1,211:
[ [ 2 - ] dip dup call ] 2bi +
] if
] dup call( n q -- m ) ;</
The name ''q'' in the stack effect has no significance; <code>call( x x -- x )</code> would still work.
Line 1,017 ⟶ 1,221:
=={{header|Falcon}}==
Falcon allows a function to refer to itself by use of the fself keyword which is always set to the currently executing function.
<
if x < 0
raise ParamError(description|"Negative argument invalid", extra|"Fibbonacci sequence is undefined for negative numbers")
Line 1,041 ⟶ 1,245:
catch in e
> e
end</
{{out}}
<pre>
Line 1,055 ⟶ 1,259:
=={{header|FBSL}}==
<
FUNCTION Fibonacci(n)
Line 1,076 ⟶ 1,280:
PRINT Fibonacci(13.666)
PAUSE</
'''Output:'''
Nuts!
Line 1,087 ⟶ 1,291:
Recursion is always anonymous in Forth, allowing it to be used in anonymous functions. However, definitions can't be defined during a definition (there are no 'local functions'), and the data stack can't be portably used to get data into a definition being defined.
{{works with|SwiftForth}} - and any Forth in which colon-sys consumes zero cells on the data stack.
<
dup 2 < ?exit
1- dup recurse swap 1- recurse + ; ( xt )
Line 1,093 ⟶ 1,297:
: fib ( +n -- n' )
dup 0< abort" Negative numbers don't exist."
[ ( xt from the :NONAME above ) compile, ] ;</
Portability is achieved with a once-off variable (or any temporary-use space with a constant address - i.e., not PAD):
<
variable pocket pocket !
: fib ( +n -- n' )
dup 0< abort" Negative numbers don't exist."
[ pocket @ compile, ] ;</
Currently, most Forths have started to support embedded definitions (shown here for iForth):
<
dup 0< abort" Negative numbers don't exist"
[: dup 2 < ?exit 1- dup MYSELF swap 1- MYSELF + ;] execute . ;</
=={{header|Fortran}}==
Since a hidden named function instead of an anonymous one seems to be ok with implementors, here is the Fortran version:
<
integer, intent(in) :: n
if (n < 0 ) then
Line 1,124 ⟶ 1,328:
end if
end function purefib
end function fib</
=={{header|FreeBASIC}}==
Line 1,130 ⟶ 1,334:
However, for compatibility with old QB code, gosub can be used if one specifies the 'fblite', 'qb' or 'deprecated dialects:
<
#Lang "fblite"
Line 1,171 ⟶ 1,375:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,181 ⟶ 1,385:
=={{header|Fōrmulæ}}==
'''Solution.'''
It consists in having a local function inside the main function, so it is neither visible nor available outside. The local function is defined after the validation, so if the input is invalid, neither the definition nor its invocation is performed.
[[File:Fōrmulæ - Anonymous recursion 01.png]]
'''Test cases'''
[[File:Fōrmulæ - Anonymous recursion 02.png]]
[[File:Fōrmulæ - Anonymous recursion 03.png]]
=={{header|Go}}==
===Y combinator===
Y combinator solution. Go has no special support for anonymous recursion.
<
import "fmt"
Line 1,233 ⟶ 1,446:
})
})
}</
{{out}}
<pre>
Line 1,245 ⟶ 1,458:
fib 40 = 102334155
fib undefined for negative numbers
</pre>
===Closure===
<syntaxhighlight lang="go">
package main
import (
"errors"
"fmt"
)
func fib(n int) (result int, err error) {
var fib func(int) int // Must be declared first so it can be called in the closure
fib = func(n int) int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
if n < 0 {
err = errors.New("negative n is forbidden")
return
}
result = fib(n)
return
}
func main() {
for i := -1; i <= 10; i++ {
if result, err := fib(i); err != nil {
fmt.Printf("fib(%d) returned error: %s\n", i, err)
} else {
fmt.Printf("fib(%d) = %d\n", i, result)
}
}
}
</syntaxhighlight>
{{out}}
<pre>
fib(-1) returned error: negative n is forbidden
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
fib(10) = 55
</pre>
=={{header|Groovy}}==
Groovy does not explicitly support anonymous recursion. This solution is a kludgy trick that takes advantage of the "owner" scoping variable (reserved word) for closures.
<
assert it > -1
{i -> i < 2 ? i : {j -> owner.call(j)}(i-1) + {k -> owner.call(k)}(i-2)}(it)
}</
Test:
<
println fib0to20
Line 1,262 ⟶ 1,528:
println "KABOOM!!"
println e.message
}</
{{out}}
<pre>[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
Line 1,277 ⟶ 1,543:
We're defining a function 'real' which is only available from within the fib function.
<
fib n
| n < 0 = Nothing
Line 1,283 ⟶ 1,549:
where real 0 = 1
real 1 = 1
real n = real (n-1) + real (n-2)</
'''Anonymous function:'''
This uses the 'fix' function to find the fixed point of the anonymous function.
<
fib :: Integer -> Maybe Integer
fib n
| n < 0 = Nothing
| otherwise = Just $ fix (\f -> (\n -> if n > 1 then f (n-1) + f (n-2) else 1)) n</
{{out}}
Both functions provide the same output when run in GHCI.
<
[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]</
Or, without imports (inlining an anonymous fix)
<
fib n
| n < 0 = Nothing
Line 1,323 ⟶ 1,589:
case m of
Just x -> [x]
_ -> []</
{{Out}}
<pre>[1,1,2,3,5,8,13,21,34,55,89]</pre>
Line 1,333 ⟶ 1,599:
This example does accomplish the goals of hiding the procedure inside ''fib'' so that the type and value checking is outside the recursion. It also does not require an identifier to reference the inner procedure; but, it requires a local variable to remember our return point. Also, each recursion will result in the current co-expression being refreshed, essentially copied, placing a heavy demand on co-expression resources.
<
every write("fib(",a := numeric(!A),")=",fib(a))
end
Line 1,356 ⟶ 1,622:
A := if type(A) == "list" then A[1]
return (@A, A) # prime and return
end</
Some of the code requires some explaining:
* The double curly brace syntax after ''makeProc'' serves two different purposes, the outer set is used in the call to create a co-expression. The inner one binds all the expressions together as a single unit.
Line 1,365 ⟶ 1,631:
For reference, here is the non-cached version:
<
local source, i
if type(n) == "integer" & n >= 0 then
Line 1,373 ⟶ 1,639:
((i-1)@makeProc(^¤t) + (i-2)@makeProc(^¤t)) @ source
}}
end</
The performance of this second version is 'truly impressive'. And I mean that in a really bad way. By way of example, using default memory settings on a current laptop, a simple recursive non-cached ''fib'' out distanced the non-cached ''fib'' above by a factor of 20,000. And a simple recursive cached version out distanced the cached version above by a factor of 2,000.
=={{header|Io}}==
The most natural way to solve this task is to use a nested function whose scope is limited to the helper function.
<
if(x < 0, Exception raise("Negative argument not allowed!"))
fib2 := method(n,
Line 1,384 ⟶ 1,650:
)
fib2(x floor)
)</
=={{header|J}}==
Copied directly from the [[Fibonacci_sequence#J|fibonacci sequence]] task, which in turn copied from one of several implementations in an [[j:Essays/Fibonacci_Sequence|essay]] on the J Wiki:
<
Note that this is an identity function for arguments less than 1 (and 1 (and 5)).
'''Examples:'''
<
144
fibN i.31
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040</
(This implementation is doubly recursive except that results are cached across function calls.)
Line 1,422 ⟶ 1,670:
Note also http://www.jsoftware.com/pipermail/general/2003-August/015571.html which points out that the form
<
Of course, that won't work here, because we are adding two recursively obtained results where tail recursion requires that the recursive result is the final result.
-------------
See also [[Y_combinator#J|Y combinator]] but note that that approach is less efficient (has higher costs).
Also, note that J's "implicit mapping" is primitive recursive (as is arithmetic in general), and thus in some contexts a "more efficient approach to recursion".
=={{header|Java}}==
Creates an anonymous inner class to do the dirty work. While it does keep the recursive function out of the namespace of the class, it does seem to violate the spirit of the task in that the function is still named.
<
if (n < 0)
throw new IllegalArgumentException("n can not be a negative number");
Line 1,438 ⟶ 1,692:
}
}.fibInner(n);
}</
Another way is to use the Java Y combinator implementation (the following uses the Java 8 version for better readability).
Note that the fib method below is practically the same as that of the version above, with less fibInner.
<
@FunctionalInterface
Line 1,467 ⟶ 1,721:
).apply(m);
}
}</
=={{header|JavaScript}}==
<
if (n < 0) { throw "Argument cannot be negative"; }
return (function(n) {
return (n < 2) ?
})(n);
}</
Note that <code>arguments.callee</code> will not be available in ES5 Strict mode. Instead, you are expected to "name" function (the name is only visible inside function however).
<
if (n < 0) { throw "Argument cannot be negative"; }
return (function fib(n) {
return (n < 2) ?
})(n);
}</
=={{header|Joy}}==
This definition is taken from "Recursion Theory and Joy" by Manfred von Thun.
<syntaxhighlight lang="joy">fib == [small] [] [pred dup pred] [+] binrec;</syntaxhighlight>
=={{header|jq}}==
The "recurse" filter supports a type of anonymous recursion, e.g. to generate a stream of integers starting at 0:
<
Also, as is the case for example with Julia, jq allows you to define an inner/nested function (in the follow example, <code>aux</code>) that is only defined within the scope of the surrounding function (here <code>fib</code>). It is thus invisible outside the function:
<
def aux: if . == 0 then 0
elif . == 1 then 1
Line 1,498 ⟶ 1,756:
if n < 0 then error("negative arguments not allowed")
else n | aux
end ;</
=={{header|Julia}}==
Julia allows you to define an inner/nested function (here, <code>aux</code>) that is only defined within the surrounding function <code>fib</code> scope.
<
if n < 0
throw(ArgumentError("negative arguments not allowed"))
Line 1,508 ⟶ 1,766:
aux(m) = m < 2 ? one(m) : aux(m-1) + aux(m-2)
aux(n)
end</
=={{header|K}}==
{{works with|Kona}}
<syntaxhighlight lang="k">fib: {:[x<0; "Error Negative Number"; {:[x<2;x;_f[x-2]+_f[x-1]]}x]}</syntaxhighlight>
{{works with|ngn/k}}:
<syntaxhighlight lang=K>fib: {:[x<0; "Error Negative Number"; {:[x<2;x;o[x-2]+o[x-1]]}x]}</syntaxhighlight>
'''Examples:'''
<
0 1 1 2 3 5 8 13 21 34
fib -1
"Error Negative Number"</
=={{header|Klingphix}}==
<syntaxhighlight lang="text">include ..\Utilitys.tlhy
Line 1,540 ⟶ 1,801:
25 fib ?
msec ?
"End " input</
=={{header|Klong}}==
<syntaxhighlight lang="k">
fib::{:[x<0;"error: negative":|x<2;x;.f(x-1)+.f(x-2)]}
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|Dylan}}
<
require(n >= 0)
fun
if (k == 0) a else
return
}
Line 1,559 ⟶ 1,820:
for (i in 0..20) print("${fib(i)} ")
println()
}</
{{out}}
Line 1,567 ⟶ 1,828:
=={{header|Lambdatalk}}==
<
1) defining a
{def fibo {lambda {:n}
{{{lambda {:f
{lambda {:f :n :a :b}
{if {< :n 0}
Line 1,576 ⟶ 1,837:
else {if {< :n 1}
then :a
else {:f :f {- :n 1} {+ :a :b} :a}}}}} :n 1 0}}}
-> fibo
2) testing:
Line 1,583 ⟶ 1,845:
{fibo 8} -> 34
{fibo 1000} -> 7.0330367711422765e+208
{S.map fibo {S.serie 1 20}}
-> 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946
We could also avoid any name and write an IIFE
{{lambda {:n}
{{{lambda {:f
{lambda {:f :n :a :b}
{if {< :n 0}
Line 1,595 ⟶ 1,857:
else {if {< :n 1}
then :a
else {:f :f {- :n 1} {+ :a :b} :a}}}}} :n 1 0}}
8}
-> 34
</syntaxhighlight>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
fp.fib = ($n) -> {
if($n < 0) {
throw fn.withErrorMessage($LANG_ERROR_INVALID_ARGUMENTS, n must be >= 0)
}
fp.innerFib = ($n) -> {
if($n < 2) {
return $n
}
return parser.op(fp.innerFib($n - 1) + fp.innerFib($n - 2))
}
return fp.innerFib($n)
}
</syntaxhighlight>
=={{header|Lingo}}==
Lingo does not support anonymous functions. But what comes close: you can create and instantiate an "anonymous class":
<
if n<0 then return _player.alert("negative arguments not allowed")
Line 1,614 ⟶ 1,894:
return aux.fib(n)
end</
<
-- 55</
=={{header|LOLCODE}}==
{{trans|C}}
<
HOW IZ I fib YR x
Line 1,652 ⟶ 1,932:
I IZ fib_i YR 3 MKAY
KTHXBYE</
=={{header|Lua}}==
Using a [[Y combinator]].
<
return Y(function(fibs)
Line 1,662 ⟶ 1,942:
return n < 2 and 1 or fibs(n - 1) + fibs(n - 2)
end
end)</
using a metatable (also achieves memoization)
<
self[n] = self[n-1] + self[n-2]
return self[n]
end})</
=={{header|M2000 Interpreter}}==
We can use a function in string. We can named it so the error say about "Fibonacci"
To exclude first check for negative we have to declare a function in anonymous function, which may have a name (a local name)
<syntaxhighlight lang="m2000 interpreter">
A$={{ Module "Fibonacci" : Read X :If X<0 then {Error {X<0}} Else Fib=Lambda (x)->if(x>1->fib(x-1)+fib(x-2), x) : =fib(x)}}
Try Ok {
Line 1,679 ⟶ 1,959:
If Error or Not Ok Then Print Error$
Print Function(A$, 12)=144 ' true
</syntaxhighlight>
For recursion we can use Lambda() or Lambda$() (for functions which return string) and not name of function so we can use it in a referenced function. Here in k() if we have the fib() we get an error, but with lambda(), interpreter use current function's name.
<syntaxhighlight lang="m2000 interpreter">
Function fib(x) {
If x<0 then Error "argument outside of range"
Line 1,695 ⟶ 1,975:
CheckIt &Fib()
Print fib(-2) ' error
</syntaxhighlight>
Using lambda function
<syntaxhighlight lang="m2000 interpreter">
fib=lambda -> {
fib1=lambda (x)->If(x>1->lambda(x-1)+lambda(x-2), x)
Line 1,723 ⟶ 2,003:
Inventory Alfa = "key1":=Z
Print Alfa("key1")(12)=144
</syntaxhighlight>
Using a Group (object in M2000) like a function
Line 1,730 ⟶ 2,010:
<syntaxhighlight lang="m2000 interpreter">
Class Something {
\\ this class is a global function
Line 1,755 ⟶ 2,035:
Print Alfa("Key2")(12)=144
Print Eval(Alfa("100"),12)=144, Eval(Alfa(100),12)=144
</syntaxhighlight>
=={{header|Maple}}==
In Maple, the keyword thisproc refers to the currently executing procedure (closure), which need not be named. The following defines a procedure Fib, which uses a recursive, anonymous (unnamed) procedure to implement the Fibonacci sequence. For better efficiency, we use Maple's facility for automatic memoisation ("option remember").
<syntaxhighlight lang="maple">
Fib := proc( n :: nonnegint )
proc( k )
Line 1,773 ⟶ 2,053:
end( n )
end proc:
</syntaxhighlight>
For example:
<syntaxhighlight lang="maple">
> seq( Fib( i ), i = 0 .. 10 );
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
Line 1,782 ⟶ 2,062:
Error, invalid input: Fib expects its 1st argument, n, to be of type
nonnegint, but received -1
</syntaxhighlight>
The check for a negative argument could be put either on the outer Fib procedure, or the anonymous inner procedure (or both). As it wasn't completely clear what was intended, I put it on Fib, which results in a slightly better error message in that it does not reveal how the procedure was actually implemented.
=={{header|Mathematica}} / {{header|Wolfram Language}}==
An anonymous reference to a function from within itself is named #0, arguments to that function are named #1,#2..#n, n being the position of the argument. The first argument may also be referenced as a # without a following number, the list of all arguments is referenced with ##. Anonymous functions are also known as [http://reference.wolfram.com/mathematica/tutorial/PureFunctions.html pure functions] in Mathematica.
<
fib := If[check[#],Throw["Negative Argument"],If[#<=1,1,#0[#-2]+#0[#-1]]&[#]]&
fib /@ Range[0,10]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}</
Making sure that the check is only performed once.
<
fib /@ Range[0,4]
0
Line 1,801 ⟶ 2,081:
4
{1, 1, 2, 3, 5}</
=={{header|MATLAB}}==
Not anonymous exactly, but using a nested function solves all the problems stated in the task description.
* does not exist outside of parent function
* does not need a new name, can reuse the parent name
* a nested function can be defined in the place where it is needed
<syntaxhighlight lang="matlab">
function v = fibonacci(n)
assert(n >= 0)
v = fibonacci(n,0,1);
% nested function
function a = fibonacci(n,a,b)
if n ~= 0
a = fibonacci(n-1,b,a+b);
end
end
end
</syntaxhighlight>
=={{header|Nemerle}}==
Line 1,808 ⟶ 2,106:
* inner function not expected to be called from anywhere else
* nesting maintains program flow in source code
<
using System.Console;
Line 1,837 ⟶ 2,135:
}
}
}</
=={{header|Nim}}==
<
proc fib(x: int): int =
proc fibI(n: int): int =
Line 1,851 ⟶ 2,149:
echo fib(i)
# fibI(10) # undeclared identifier 'fibI'</
Output:
<pre>0
Line 1,861 ⟶ 2,159:
=={{header|Objective-C}}==
This shows how a method (not regular function) can recursively call itself without explicitly putting its name in the code.
<
@interface AnonymousRecursion : NSObject { }
Line 1,892 ⟶ 2,190:
}
return 0;
}</
;With internal named recursive block:
{{works with|Mac OS X|10.6+}}
<
int fib(int n) {
Line 1,921 ⟶ 2,219:
}
return 0;
}</
When ARC is disabled, the above should be:
<
int fib(int n) {
Line 1,948 ⟶ 2,246:
}
return 0;
}</
=={{header|OCaml}}==
Line 1,957 ⟶ 2,255:
We're defining a function 'real' which is only available from within the fib function.
<
let rec real = function
0 -> 1
Line 1,966 ⟶ 2,264:
None
else
Some (real n)</
'''Anonymous function:'''
This uses the 'fix' function to find the fixed point of the anonymous function.
<
let fib n =
Line 1,977 ⟶ 2,275:
None
else
Some (fix (fun f -> fun n -> if n <= 1 then 1 else f (n-1) + f (n-2)) n)</
{{out}}
<pre># fib 8;;
Line 1,984 ⟶ 2,282:
=={{header|Ol}}==
This uses named let to create a local function (loop) that only exists inside of function fibonacci.
<
(define (fibonacci n)
(if (> 0 n)
Line 1,995 ⟶ 2,293:
(print
(map fibonacci '(1 2 3 4 5 6 7 8 9 10)))
</syntaxhighlight>
{{out}}
<pre>'(1 1 2 3 5 8 13 21 34 55)</pre>
Line 2,001 ⟶ 2,299:
=={{header|OxygenBasic}}==
An inner function keeps the name-space clean:
<
function fiboRatio() as double
function fibo( double i, j ) as double
Line 2,012 ⟶ 2,310:
print fiboRatio
</syntaxhighlight>
=={{header|PARI/GP}}==
This version uses a Y combinator to get a self-reference.
<
my(F=(k,f)->if(k<2,k,f(k-1,f)+f(k-2,f)));
if(n<0,(-1)^(n+1),1)*F(abs(n),F)
};</
{{works with|PARI/GP|2.8.1+}}
This version gets a self-reference from <code>self()</code>.
<
my(F=k->my(f=self());if(k<2,k,f(k-1)+f(k-2)));
if(n<0,(-1)^(n+1),1)*F(abs(n))
};</
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
program AnonymousRecursion;
function Fib(X: Integer): integer;
function DoFib(N: Integer): Integer;
begin
if N < 2 then DoFib:=N
else DoFib:=DoFib(N-1) + DoFib(N-2);
end;
begin
if X < 0 then Fib:=X
else Fib:=DoFib(X);
end;
var I,V: integer;
begin
for I:=-1 to 15 do
begin
V:=Fib(I);
Write(I:3,' - ',V:3);
if V<0 then Write(' - Error');
WriteLn;
end;
WriteLn('Hit Any Key');
ReadLn;
end.
</syntaxhighlight>
{{out}}
<pre>
-1 - -1 - Error
0 - 0
1 - 1
2 - 1
3 - 2
4 - 3
5 - 5
6 - 8
7 - 13
8 - 21
9 - 34
10 - 55
11 - 89
12 - 144
13 - 233
14 - 377
15 - 610
Hit Any Key
</pre>
=={{header|Perl}}==
{{trans|PicoLisp}}
<code>recur</code> isn't built into Perl, but it's easy to implement.
<
my $f = shift;
local *recurse = $f;
Line 2,044 ⟶ 2,397:
$m < 3 ? 1 : recurse($m - 1) + recurse($m - 2);
} $n;
}</
Although for this task, it would be fine to use a lexical variable (closure) to hold an anonymous sub reference, we can also just push it onto the args stack and use it from there:
<
my ($n) = @_;
die "negative arg $n" if $n < 0;
Line 2,058 ⟶ 2,411:
}
print(fib($_), " ") for (0 .. 10);</
One can also use <code>caller</code> to get the name of the current subroutine as a string, then call the sub with that string. But this won't work if the current subroutine is anonymous: <code>caller</code> will just return <code>'__ANON__'</code> for the name of the subroutine. Thus, the below program must check the sign of the argument every call, failing the task. Note that under stricture, the line <code>no strict 'refs';</code> is needed to permit using a string as a subroutine.
<
my $n = shift;
$n < 0 and die 'Negative argument';
no strict 'refs';
$n < 3 ? 1 : (caller(0))[3]->($n - 1) + (caller(0))[3]->($n - 2);
}</
===Perl 5.16 and __SUB__===
Perl 5.16 introduced __SUB__ which refers to the current subroutine.
<
say sub {
my $n = shift;
$n < 2 ? $n : __SUB__->($n-2) + __SUB__->($n-1)
}->($_) for 0..10</
=={{header|Phix}}==
{{libheader|Phix/Class}}
===using classes===
With proof that the private fib_i() does not pollute the outer namespace.
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class yet)</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">Fib</span>
<span style="color: #008080;">private</span> <span style="color: #008080;">function</span> <span style="color: #000000;">fib_i</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">2</span><span style="color: #0000FF;">?</span><span style="color: #000000;">n</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">this</span><span style="color: #0000FF;">.</span><span style="color: #000000;">fib_i</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">this</span><span style="color: #0000FF;">.</span><span style="color: #000000;">fib_i</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">public</span> <span style="color: #008080;">function</span> <span style="color: #000000;">fib</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">throw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"constraint error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">this</span><span style="color: #0000FF;">.</span><span style="color: #000000;">fib_i</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
<span style="color: #000000;">Fib</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">fib_i</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"this is not the fib_i(%d) you are looking for\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">f</span><span style="color: #0000FF;">.</span><span style="color: #000000;">fib</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--?f.fib_i(10) -- illegal</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">fib_i</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,105 ⟶ 2,461:
Obviously the inner function does not have to and in fact is not allowed to have a name itself, but it needs to be stored in something with a name before it can be called,
and in being anonymous, in order to effect recursion it must be passed to itself, repeatedly and not really anonymous at all anymore.
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no lambda yet)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">erm</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">fib</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">throw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"constraint error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">erm</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #008080;">function</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">2</span><span style="color: #0000FF;">?</span><span style="color: #000000;">n</span><span style="color: #0000FF;">:</span><span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">fib</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,123 ⟶ 2,482:
In this solution, the function is always called using <code>call_user_func()</code> rather than using function call syntax directly. Inside the function, we get the function itself (without having to refer to the function by name) by relying on the fact that this function must have been passed as the first argument to <code>call_user_func()</code> one call up on the call stack. We can then use <code>debug_backtrace()</code> to get this out.
{{works with|PHP|5.3+}}
<
function fib($n) {
if ($n < 0)
Line 2,138 ⟶ 2,497:
}
echo fib(8), "\n";
?></
;With internal named recursive function:
{{works with|PHP|5.3+}}
<
function fib($n) {
if ($n < 0)
Line 2,155 ⟶ 2,514:
}
echo fib(8), "\n";
?></
;With a function object that can call itself using <code>$this</code>:
{{works with|PHP|5.3+}}
<
class fib_helper {
function __invoke($n) {
Line 2,176 ⟶ 2,535:
}
echo fib(8), "\n";
?></
=={{header|PicoLisp}}==
<
(if (lt0 N)
(quit "Illegal argument" N) )
Line 2,185 ⟶ 2,544:
(if (> 2 N)
1
(+ (recurse (dec N)) (recurse (- N 2))) ) ) )</
Explanation: The above uses the '[http://software-lab.de/doc/refR.html#recur recur]' / '[http://software-lab.de/doc/refR.html#recurse recurse]' function pair, which is defined as a standard language extensions as
<
(run (cdr recurse)) )</
Note how 'recur' dynamically defines the function 'recurse' at runtime, by binding the rest of the expression (i.e. the body of the 'recur' statement) to the symbol 'recurse'.
Line 2,194 ⟶ 2,553:
{{libheader|initlib}}
Postscript can make use of the higher order combinators to provide recursion.
<
/pfact {
{1} {*} primrec}.
Line 2,216 ⟶ 2,575:
% binary recursion
/fib {
{2 lt} {} {pred dup pred} {+} binrec}.</
=={{header|Prolog}}==
Works with SWI-Prolog and module <b>lambda</b>, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
The code is inspired from this page : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/ISO-Hiord#Hiord (p 106). It uses the Y combinator.
<
fib(N, _F) :-
Line 2,243 ⟶ 2,602:
Pred = PF +\Nb2^F2^call(PF,Nb2,F2,PF),
call(Pred,N,F).</
=={{header|Python}}==
<
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]</
Same thing as the above, but modified so that the function is uncurried:
<
>>> Y = lambda f: (lambda x: x(x))(lambda y: partial(f, lambda *args: y(y)(*args)))
>>> fib = lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]</
A different approach: the function always receives itself as the first argument, and when recursing, makes sure to pass the called function as the first argument also
<
>>> Y = lambda f: partial(f, f)
>>> fib = lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(f, n-1) + f(f, n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]</
An interesting approach using introspection (from http://metapython.blogspot.com/2010/11/recursive-lambda-functions.html)
<
>>> from inspect import currentframe
>>> from types import FunctionType
Line 2,276 ⟶ 2,635:
>>> print "factorial(5) =",
>>> print (lambda n:1 if n<=1 else n*myself(n-1)) ( 5 )
</syntaxhighlight>
Another way of implementing the "Y" function is given in this post: https://stackoverflow.com/questions/481692/can-a-lambda-function-call-itself-recursively-in-python. The main problem to solve is that the function "fib" can't call itself. Therefore, the function "Y" is used to help "fib" call itself.
<
>>> Y = lambda f: lambda n: f(f,n)
>>> fib = lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(f,n-1) + f(f,n-2))) #same as the first three implementations
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
</syntaxhighlight>
All in one line:
<
>>> fib_func = (lambda f: lambda n: f(f,n))(lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(f,n-1) + f(f,n-2))))
>>> [ fib_func(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
</syntaxhighlight>
=={{header|QBasic}}==
{{works with|QBasic}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">DECLARE FUNCTION Fibonacci! (num!)
PRINT Fibonacci(20)
PRINT Fibonacci(30)
PRINT Fibonacci(-10)
PRINT Fibonacci(10)
END
FUNCTION Fibonacci (num)
IF num < 0 THEN
PRINT "Invalid argument: ";
Fibonacci = num
END IF
IF num < 2 THEN
Fibonacci = num
ELSE
Fibonacci = Fibonacci(num - 1) + Fibonacci(num - 2)
END IF
END FUNCTION</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de BASIC256.
</pre>
=={{header|Qi}}==
Line 2,301 ⟶ 2,690:
However, it can be done, for instance like this:
<syntaxhighlight lang="qi">
(define fib
N -> (let A (/. A N
Line 2,309 ⟶ 2,698:
(A A (- N 1)))))
(A A N)))
</syntaxhighlight>
=={{header|Quackery}}==
Line 2,355 ⟶ 2,744:
=={{header|R}}==
R provides Recall() as a wrapper which finds the calling function, with limitations; Recall will not work if passed to another function as an argument.
<
(n >= 0) || stop("bad argument")
( function(n) if (n <= 1) 1 else Recall(n-1)+Recall(n-2) )(n)
}</
=={{header|Racket}}==
Line 2,364 ⟶ 2,753:
In Racket, local helper function definitions inside of a function are only visible locally and do not pollute the module or global scope.
<
#lang racket
Line 2,383 ⟶ 2,772:
(check-equal? (fact 0) 1)
(check-equal? (fact 5) 120))
</syntaxhighlight>
This calculates the slightly more complex Fibonacci funciton:
<
#lang racket
;; Natural -> Natural
Line 2,407 ⟶ 2,796:
'(0 1 1 2 3 5 8 13 21 34 55 89 144 233
377 610 987 1597 2584 4181 6765)))
</syntaxhighlight>
Also with the help of first-class functions in Racket, anonymous recursion can be implemented using fixed-points operators:
<
#lang racket
;; We use Z combinator (applicative order fixed-point operator)
Line 2,426 ⟶ 2,815:
(+ (fibo (- n 1))
(fibo (- n 2))))))))
</syntaxhighlight>
<pre>
Line 2,442 ⟶ 2,831:
In addition to the methods in the [[Perl]] entry above, and the Y-combinator described in [[Y_combinator]], you may also refer to an anonymous block or function from the inside:
<syntaxhighlight lang="raku"
die "Naughty fib" if $n < 0;
return {
Line 2,451 ⟶ 2,840:
}
say fib(10);</
However, using any of these methods is insane, when Raku provides a sort of inside-out combinator that lets you define lazy infinite constants, where the demand for a particular value is divorced from dependencies on more primitive values. This operator, known as the sequence operator, does in a sense provide anonymous recursion to a closure that refers to more primitive values.
<syntaxhighlight lang="raku"
say @fib[10];</
Here the closure, <tt>*+*</tt>, is just a quick way to write a lambda, <tt>-> $a, $b { $a + $b }</tt>. The sequence operator implicitly maps the two arguments to the -2nd and -1st elements of the sequence. So the sequence operator certainly applies an anonymous lambda, but whether it's recursion or not depends on whether you view a sequence as iteration or as simply a convenient way of memoizing a recursion. Either view is justifiable.
Line 2,461 ⟶ 2,850:
=={{header|REBOL}}==
<
fib: func [n /f][ do f: func [m] [ either m < 2 [m][(f m - 1) + f m - 2]] n]
</syntaxhighlight>
=={{header|REXX}}==
Line 2,470 ⟶ 2,859:
to be OK with the implementers, here are the REXX versions.
===simplistic===
<
numeric digits 1e6 /*in case the user goes ka-razy with X.*/
parse arg x . /*obtain the optional argument from CL.*/
Line 2,482 ⟶ 2,871:
fib: procedure; parse arg z; if z>=0 then return .(z)
say "***error*** argument can't be negative."; exit
.: procedure; parse arg #; if #<2 then return #; return .(#-1) + .(#-2)</
{{out|output|text= when using the input of: <tt> 12 </tt>}}
<pre>
Line 2,503 ⟶ 2,892:
Since the above REXX version is ''very'' slow for larger numbers, the following version was added that incorporates memoization.
<br>It's many orders of magnitude faster for larger values.
<
numeric digits 1e6 /*in case the user goes ka-razy with X.*/
parse arg x . /*obtain the optional argument from CL.*/
Line 2,516 ⟶ 2,905:
fib: procedure expose @.; arg z; if z>=0 then return .(z)
say "***error*** argument can't be negative."; exit
.: procedure expose @.; arg #; if @.#\==. then return @.#; @.#=.(#-1)+.(#-2); return @.#</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br>
=={{header|Ring}}==
<
# Project : Anonymous recursion
Line 2,558 ⟶ 2,947:
end
return t
</syntaxhighlight>
Output:
<pre>
Line 2,577 ⟶ 2,966:
144
</pre>
=={{header|RPL}}==
===Hidden variable===
The recursive part of the function is stored in a local variable, which is made accessible to all the recursive instances by starting its name with the <code>←</code> character.
{{works with|HP|48G}}
≪ ≪ '''IF''' DUP 1 > '''THEN'''
DUP 1 - ←fib EVAL
SWAP 2 - ←fib EVAL +
'''END''' ≫ → ←fib
≪ '''IF''' DUP 0 <
'''THEN''' DROP "Negative value" DOERR
'''ELSE''' ←fib EVAL '''END'''
≫ ≫ '<span style="color:blue">FIBAR</span>' STO
-2 <span style="color:blue">FIBAR</span>
10 <span style="color:blue">FIBAR</span>
{{out}}
<pre>
1: 55
</pre>
===Truly anonymous===
Both the recursive block and the argument are pushed onto the stack, without any naming. This meets the requirements of the task perfectly and works on any RPL machine, but it is far from idiomatic and uses a lot of stack space.
{{works with|HP|28}}
≪ '''IF''' DUP 0 <
'''THEN''' DROP "Negative value"
'''ELSE'''
≪ '''IF''' DUP 1 > '''THEN'''
DUP2 1 - OVER EVAL
ROT ROT 2 - OVER EVAL +
'''ELSE''' SWAP DROP '''END'''
≫
SWAP OVER EVAL
'''END'''
≫ '<span style="color:blue">FIBAR</span>' STO
=={{header|Ruby}}==
Line 2,583 ⟶ 3,006:
We can recurse a block of code, but we must provide the block with a reference to itself. The easiest solution is to use a local variable.
===Ruby with local variable===
<
raise RangeError, "fib of negative" if n < 0
(fib2 = proc { |m| m < 2 ? m : fib2[m - 1] + fib2[m - 2] })[n]
end</
<
=> [:error, :error, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]</
Here 'fib2' is a local variable of the fib() method. Only the fib() method, or a block inside the fib() method, can call this 'fib2'. The rest of this program cannot call this 'fib2', but it can use the name 'fib2' for other things.
Line 2,597 ⟶ 3,020:
'''Caution!''' The recursive block has a difference from Ruby 1.8 to Ruby 1.9. Here is the same method, except changing the block parameter from 'm' to 'n', so that block 'n' and method 'n' have the same name.
<
raise RangeError, "fib of negative" if n < 0
(fib2 = proc { |n| n < 2 ? n : fib2[n - 1] + fib2[n - 2] })[n]
end</
<
(-2..12).map { |i| fib i rescue :error }
=> [:error, :error, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
Line 2,607 ⟶ 3,030:
# Ruby 1.8
(-2..12).map { |i| fib i rescue :error }
=> [:error, :error, 0, 1, 0, -3, -8, -15, -24, -35, -48, -63, -80, -99, -120]</
Ruby 1.9 still shows the correct answer, but Ruby 1.8 shows the wrong answer. With Ruby 1.9, 'n' is still a local variable of the block. With Ruby 1.8, 'n' of the block closes on 'n' of the fib() method. All calls to the block share the 'n' of one call to the method. So <tt>fib2[n - 1]</tt> changes the value of 'n', and <tt>fib2[n - 2]</tt> uses the wrong value of 'n', thus the wrong answer.
===Ruby with Hash===
<
raise RangeError, "fib of negative" if n < 0
Hash.new { |fib2, m|
fib2[m] = (m < 2 ? m : fib2[m - 1] + fib2[m - 2]) }[n]
end</
This uses a Hash to memoize the recursion. After <tt>fib2[m - 1]</tt> returns, <tt>fib2[m - 2]</tt> uses the value in the Hash, without redoing the calculations.
Line 2,622 ⟶ 3,045:
{{trans|PicoLisp}}
{{libheader|continuation}}
<
module Kernel
Line 2,641 ⟶ 3,064:
raise RangeError, "fib of negative" if n < 0
recur(n) { |m| m < 2 ? m : (recurse m - 1) + (recurse m - 2) }
end</
Our recursive block now lives in the 'block' variable of the Kernel#recur method.
Line 2,650 ⟶ 3,073:
{{trans|JavaScript}}
{{libheader|continuation}}
<
module Kernel
Line 2,681 ⟶ 3,104:
end
}[n]
end</
Our recursive block now lives in the 'block' variable of the Kernel#function method. Another block 'f' wraps our original block and sets up the 'arguments' array. Kernel#function returns this wrapper block. Kernel#arguments plays a trick to get the array of arguments from 'f'; this array has an extra singleton method #callee which returns 'f'.
=={{header|Rust}}==
<
// A function declared inside another function does not pollute the outer namespace.
fn actual_fib(n: i64) -> i64 {
Line 2,727 ⟶ 3,150:
fn test_invalid_argument() {
assert_eq!(fib(-1), None);
}</
=={{header|Scala}}==
Using a Y-combinator:
<
def fib(n: Int): Option[Int] =
Line 2,739 ⟶ 3,162:
else f(i - 1) + f(i - 2))(n))
-2 to 5 map (n ⇒ (n, fib(n))) foreach println</
{{out}}
<pre>
Line 2,754 ⟶ 3,177:
=={{header|Scheme}}==
This uses named let to create a function (aux) that only exists inside of fibonacci:
<
(if (> 0 n)
"Error: argument must not be negative."
Line 2,762 ⟶ 3,185:
(aux (+ a b) a (- count 1))))))
(map fibonacci '(1 2 3 4 5 6 7 8 9 10))</
{{out}}
<pre>'(1 1 2 3 5 8 13 21 34 55)</pre>
Line 2,768 ⟶ 3,191:
=={{header|Seed7}}==
Uses a local function to do the dirty work. The local function has a name, but it is not in the global namespace.
<
const func integer: fib (in integer: x) is func
Line 2,799 ⟶ 3,222:
writeln(fib(i));
end for;
end func;</
{{out}}
Line 2,812 ⟶ 3,235:
=={{header|Sidef}}==
__FUNC__ refers to the current function.
<
return NaN if (n < 0)
Line 2,819 ⟶ 3,242:
: (__FUNC__(n-1) + __FUNC__(n-2))
}(n)
}</
__BLOCK__ refers to the current block.
<
return NaN if (n < 0)
Line 2,830 ⟶ 3,253:
: (__BLOCK__(n-1) + __BLOCK__(n-2))
}(n)
}</
=={{header|Smalltalk}}==
Line 2,841 ⟶ 3,264:
a) Use a funny local name (in this case: "_").
Here the closure is defined as "_", and then evaluated (by sending it a <tt>value:</tt> message).
<
myMethodComputingFib:arg
|_|
Line 2,848 ⟶ 3,271:
ifTrue:[n]
ifFalse:[(_ value:(n - 1))+(_ value:(n - 2))]]
) value:arg.</
b) Define it in a local scope to not infect the outer scopes.
<br>Here, a separate closure is defined (and evaluated with <tt>value</tt>), in which fib is defined and evaluated with the argument.
This is semantically equivalent to the named let solution of Scheme.
<
myMethodComputingFib2:arg
^ [
Line 2,860 ⟶ 3,283:
ifTrue:[1]
ifFalse:[(fib value:(n - 1))+(fun value:(n - 2))]] value:arg.
] value.</
To completely make it anonymous, we could use reflection to get at the current executed block (via thisContext),
but that is too ugly and obfuscating to be shown here.
Line 2,866 ⟶ 3,289:
=={{header|Sparkling}}==
As a function expression:
<
return f(n, f);
}(10, function(n, f) {
return n < 2 ? 1 : f(n - 1, f) + f(n - 2, f);
})
</syntaxhighlight>
When typed into the REPL:
<
= 89</
=={{header|Standard ML}}==
ML does not have a built-in construct for anonymous recursion, but you can easily write your own fix-point combinator:
<
fun fib n =
Line 2,887 ⟶ 3,310:
(fn 0 => 0
| 1 => 1
| n => fib (n-1) + fib (n-2))) n</
Instead of using a fix-point, the more common approach is to locally define a recursive function and call it once:
<
let
fun fib 0 = 0
Line 2,900 ⟶ 3,323:
else
fib n
end</
In this example the local function has the same name as the outer function. This is fine: the local definition shadows
Line 2,906 ⟶ 3,329:
Another variation is possible. Instead, we could define the recursive "fib" at top-level, then shadow it with a non-recursive wrapper. To force the wrapper to be non-recursive, we use the "val" syntax instead of "fun":
<
| fib 1 = 1
| fib n = fib (n-1) + fib (n-2)
val fib = fn n => if n < 0 then raise Fail "Negative"
else fib n</
=={{header|SuperCollider}}==
Line 2,917 ⟶ 3,340:
SuperCollider has a keyword "thisFunction", which refers to the current function context. The example below uses this for anonymous recursion. One may think that "thisFunction" would refer to the second branch of the if statement, but because if statements are inlined, the function is the outer one.
<syntaxhighlight lang="supercollider">
(
f = { |n|
Line 2,926 ⟶ 3,349:
(0..20).collect(f)
)
</syntaxhighlight>
=={{header|Swift}}==
;With internal named recursive closure:
{{works with|Swift|2.x}}
<
func f(n: Int) -> Int {
assert(n >= 0, "fib: no negative numbers")
Line 2,939 ⟶ 3,362:
}()
print(fib(8))</
{{works with|Swift|1.x}}
<
var f: (Int -> Int)!
f = { n in
Line 2,950 ⟶ 3,373:
}()
println(fib(8))</
;Using Y combinator:
<
let o : RecursiveFunc<F> -> F
}
Line 2,967 ⟶ 3,390:
}
println(fib(8))</
=={{header|Tailspin}}==
Line 2,974 ⟶ 3,397:
=={{header|Tcl}}==
This solution uses Tcl 8.5's lambda terms, extracting the current term from the call stack using introspection (storing it in a local variable only for convenience, with that ''not'' in any way being the name of the lambda term; just what it is stored in, and only as a convenience that keeps the code shorter). The lambda terms are applied with the <code>apply</code> command.
<
# sanity checks
if {[incr n 0] < 0} {error "argument may not be negative"}
Line 2,983 ⟶ 3,406:
expr {[apply $f [incr x -1]] + [apply $f [incr x -1]]}
}} $n
}</
Demonstrating:
<syntaxhighlight lang
{{out}}}
<pre>144</pre>
The code above can be written without even using a local variable to hold the lambda term, though this is generally less idiomatic because the code ends up longer and clumsier:
<
if {[incr n 0] < 0} {error "argument may not be negative"}
apply {x {expr {
Line 2,997 ⟶ 3,420:
+ [apply [lindex [info level 0] 1] [incr x -1]]
}}} $n
}</
However, we can create a <code>recurse</code> function that makes this much more straight-forward:
<
proc tcl::mathfunc::recurse args {apply [lindex [info level -1] 1] {*}$args}
proc fib n {
Line 3,006 ⟶ 3,429:
$x < 2 ? $x : recurse([incr x -1]) + recurse([incr x -1])
}}} $n
}</
=={{header|True BASIC}}==
{{trans|BASIC256}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">FUNCTION Fibonacci (num)
IF num < 0 THEN
PRINT "Invalid argument: ";
LET Fibonacci = num
END IF
IF num < 2 THEN
LET Fibonacci = num
ELSE
LET Fibonacci = Fibonacci(num - 1) + Fibonacci(num - 2)
END IF
END FUNCTION
PRINT Fibonacci(20)
PRINT Fibonacci(30)
PRINT Fibonacci(-10)
PRINT Fibonacci(10)
END</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de BASIC256.
</pre>
=={{header|TXR}}==
For the Y combinator approach in TXR, see the Y combinator task.
Line 3,016 ⟶ 3,466:
{{trans|Common_Lisp}}
<
(let ((hidden-name (gensym "RECURSIVE-")))
^(macrolet ((recurse (. args) ^(,',hidden-name ,*args)))
Line 3,031 ⟶ 3,481:
(put-line `fib(10) = @(fib 10)`)
(put-line `fib(-1) = @(fib -1)`))</
{{out}}
Line 3,044 ⟶ 3,494:
=={{header|UNIX Shell}}==
The shell does not have anonymous functions. Every function must have a name. However, one can create a subshell such that some function, which has a name in the subshell, is effectively anonymous to the parent shell.
<
if test 0 -gt "$1"; then
echo "fib: fib of negative" 1>&2
Line 3,060 ⟶ 3,510:
)
fi
}</
<
> fib $i
> done
Line 3,078 ⟶ 3,528:
55
89
144</
=={{header|Ursala}}==
<
fib =
Line 3,093 ⟶ 3,543:
predecessor^~( # with the respective predecessors of
~&, # the given argument
predecessor)))) # and the predecessor thereof</
Anonymous recursion is often achieved using the recursive conditional operator, <code>( _ )^?( _ , _ )</code>, which takes a predicate on the left and a pair of functions on the right, typically one for the base and one for the inductive case in a recursive definition. The form <code>^?<</code> can be used if the relevant predicate is given by membership of the argument in a constant set, in which case only the set needs to be specified rather than the whole predicate.
Line 3,102 ⟶ 3,552:
'''Solution with anonymous class'''
<syntaxhighlight lang="utfool">
···
http://rosettacode.org/wiki/Anonymous_recursion
Line 3,120 ⟶ 3,570:
⏎ n ≤ 1 ? n ! (apply n - 1) + (apply n - 2)
°.apply Integer.valueOf args[0]
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Sub Main()
Debug.Print F(-10)
Line 3,137 ⟶ 3,587:
F = F(N - 1) + F(N - 2)
End If
End Function</
{{out}}
<pre>Error. Negative argument
Line 3,143 ⟶ 3,593:
=={{header|Wart}}==
<
if (n >= 0)
(transform n :thru (afn (n)
Line 3,149 ⟶ 3,599:
n
(+ (self n-1)
(self n-2)))))</
<code>afn</code> creates an anonymous function that can be recursed by calling <code>self</code>.
=={{header|WDTE}}==
<
let fib n => switch n {
Line 3,162 ⟶ 3,612:
default => + (s (- n 1)) (s (- n 2));
});
};</
In WDTE, a lambda, defined in a block delineated by <code>(@)</code>, gets passed itself as its first argument, allowing for recursion.
=={{header|Wren}}==
<
static compute(n) {
var fib
Line 3,180 ⟶ 3,630:
}
System.print(Fibonacci.compute(36))</
{{out}}
Line 3,195 ⟶ 3,645:
The address of the instructions after the function get put on the stack and then execution continues into the actual function.
When the recursion is complete, instead of returning to the location of the call it goes to the end of the loop.
<
; Calculates and prints Fibonacci numbers (Fn)
; Prints numbers 1 - 47 (largest 32bit Fn that fits)
Line 3,284 ⟶ 3,734:
pop ebp
ret
</syntaxhighlight>
=={{header|XPL0}}==
Line 3,291 ⟶ 3,741:
This makes those nested functions invisible to the outside, thus preventing namespace pollution.
<
func Fib(X);
Line 3,307 ⟶ 3,757:
[IntOut(0, Fib(8)); CrLf(0);
IntOut(0, Fib(-2)); CrLf(0);
]</
{{out}}
Line 3,317 ⟶ 3,767:
=={{header|Yabasic}}==
{{trans|AutoIt}}
<
print Fibonacci(10)
Line 3,331 ⟶ 3,781:
EndIf
end sub</
=={{header|zkl}}==
<
if (n<0) throw(Exception.ValueError);
fcn(n){
Line 3,343 ⟶ 3,793:
fib(8) .println();
fib(-8).println();
</syntaxhighlight>
{{out}}
<pre>
Line 3,352 ⟶ 3,802:
=={{header|ZX Spectrum Basic}}==
{{trans|AutoHotkey}}
<
20 LET t=0
30 GO SUB 60
Line 3,364 ⟶ 3,814:
110 IF n>2 THEN LET n=n-1: LET nold2=nold1: LET nold1=t: GO SUB 100
120 RETURN
</syntaxhighlight>
{{omit from|ACL2}}
|