Anonymous recursion: Difference between revisions

m
m (oops)
imported>Arakov
(24 intermediate revisions by 15 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++}}
<syntaxhighlight lang="11l">F fib(n)
F f(Int n) -> Int
I n < 2
Line 40 ⟶ 43:
 
Better would be to use type Natural instead of Integer, which lets Ada do the magic of checking the valid range.
<syntaxhighlight lang=Ada"ada"> function Fib (X: in Integer) return Integer is
function Actual_Fib (N: in Integer) return Integer is
begin
Line 59 ⟶ 62:
=={{header|ALGOL 68}}==
{{Trans|Ada}}
<syntaxhighlight lang="algol68">PROC fibonacci = ( INT x )INT:
IF x < 0
THEN
Line 82 ⟶ 85:
though they are not quite first-class objects (you can't have an array of functions for example).
 
<syntaxhighlight lang=APL"apl">fib←{ ⍝ Outer function
⍵<0:⎕SIGNAL 11 ⍝ DOMAIN ERROR if argument < 0
{ ⍝ Inner (anonymous) function
Line 92 ⟶ 95:
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">on fibonacci(n) -- "Anonymous recursion" task.
-- 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 130 ⟶ 133:
Or, as the recursion of an anonymous declarative function, enabled by the Y combinator:
 
<syntaxhighlight lang="applescript">------------ ANONYMOUS RECURSION WITH THE Y-COMBINATOR --------
on run
Line 289 ⟶ 292:
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">fib: function [x][
; Using scoped function fibI inside fib
fibI: function [n][
Line 311 ⟶ 314:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Fib(n) {
nold1 := 1
nold2 := 0
Line 336 ⟶ 339:
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
ConsoleWrite(Fibonacci(10) & @CRLF) ; ## USAGE EXAMPLE
ConsoleWrite(Fibonacci(20) & @CRLF) ; ## USAGE EXAMPLE
Line 362 ⟶ 365:
=={{header|Axiom}}==
Using the Aldor compiler in Axiom/Fricas:
<syntaxhighlight lang="axiom">#include "axiom"
Z ==> Integer;
fib(x:Z):Z == {
Line 369 ⟶ 372:
f(x,1,1);
}</syntaxhighlight>The old Axiom compiler has scope issues with calling a local function recursively. One solution is to use the Reference (pointer) domain and initialise the local function with a dummy value:
<syntaxhighlight lang="axiom">)abbrev package TESTP TestPackage
Z ==> Integer
TestPackage : with
Line 380 ⟶ 383:
f()(x,1,1)</syntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">
 
DEF FN fib(x) = FIB(x)
Line 423 ⟶ 426:
</syntaxhighlight>
 
==={{header|BASIC256}}===
 
=={{header|BASIC256}}==
{{trans|AutoIt}}
<syntaxhighlight lang=BASIC256"basic256">print Fibonacci(20)
print Fibonacci(30)
print Fibonacci(-10)
Line 450 ⟶ 452:
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:
<syntaxhighlight lang="bbcbasic"> PRINT FNfib(10)
END
Line 464 ⟶ 480:
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.
<syntaxhighlight lang="bracmat">( (
=
. !arg:#:~<0
Line 491 ⟶ 523:
===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
<syntaxhighlight lang="bracmat">( /(
' ( x
. $x:#:~<0
Line 519 ⟶ 551:
 
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>
Line 533 ⟶ 565:
=={{header|C}}==
Using scoped function fib_i inside fib, with GCC (required version 3.2 or higher):
<syntaxhighlight lang=C"c">#include <stdio.h>
 
long fib(long x)
Line 573 ⟶ 605:
 
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(){
Line 592 ⟶ 624:
=={{header|C sharp|C#}}==
The inner recursive function (delegate/lambda) has to be named.
<syntaxhighlight lang="csharp">
static int Fib(int n)
{
Line 605 ⟶ 637:
=={{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.
<syntaxhighlight lang="cpp">double fib(double n)
{
if(n < 0)
Line 632 ⟶ 664:
}</syntaxhighlight>
{{works with|C++11}}
<syntaxhighlight lang="cpp">#include <functional>
using namespace std;
 
Line 651 ⟶ 683:
Using a local function object that calls itself using <code>this</code>:
 
<syntaxhighlight lang="cpp">double fib(double n)
{
if(n < 0)
Line 680 ⟶ 712:
=={{header|Clio}}==
Simple anonymous recursion to print from 9 to 0.
<syntaxhighlight lang="clio">10 -> (@eager) fn n:
if n:
n - 1 -> print -> recall</syntaxhighlight>
Line 686 ⟶ 718:
=={{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.
<syntaxhighlight lang="clojure">
(defn fib [n]
(when (neg? n)
Line 698 ⟶ 730:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript"># This is a rather obscure technique to have an anonymous
# function call itself.
fibonacci = (n) ->
Line 722 ⟶ 754:
This version uses the anaphoric <code>lambda</code> from [http://dunsmor.com/lisp/onlisp/onlisp_18.html Paul Graham's On Lisp].
 
<syntaxhighlight lang="lisp">(defmacro alambda (parms &body body)
`(labels ((self ,parms ,@body))
#'self))</syntaxhighlight>
Line 728 ⟶ 760:
The Fibonacci function can then be defined as
 
<syntaxhighlight lang="lisp">(defun fib (n)
(assert (>= n 0) nil "'~a' is a negative number" n)
(funcall
Line 741 ⟶ 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
 
<syntaxhighlight lang="lisp">(defun fib (number)
"Fibonacci sequence function."
(if (< number 0)
Line 753 ⟶ 785:
 
Here is <code>fib</code> rewritten to use RECURSIVE:
<syntaxhighlight lang="lisp">(defun fib (number)
"Fibonacci sequence function."
(if (< number 0)
Line 762 ⟶ 794:
(recurse (- n 1) b (+ a b))))))</syntaxhighlight>
Implementation of RECURSIVE:
<syntaxhighlight lang="lisp">(defmacro recursive ((&rest parm-init-pairs) &body body)
(let ((hidden-name (gensym "RECURSIVE-")))
`(macrolet ((recurse (&rest args) `(,',hidden-name ,@args)))
Line 777 ⟶ 809:
===Using the Y combinator===
 
<syntaxhighlight lang="lisp">(setf (symbol-function '!) (symbol-function 'funcall)
(symbol-function '!!) (symbol-function 'apply))
 
Line 843 ⟶ 875:
 
=={{header|D}}==
<syntaxhighlight lang="d">int fib(in uint arg) pure nothrow @safe @nogc {
assert(arg >= 0);
 
Line 862 ⟶ 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.
<syntaxhighlight lang="d">import std.stdio;
 
int fib(in int n) pure nothrow {
Line 885 ⟶ 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.
 
<syntaxhighlight lang="dylan">
define function fib (n)
when (n < 0)
Line 903 ⟶ 935:
=={{header|Déjà Vu}}==
===With Y combinator===
<syntaxhighlight lang="dejavu">Y f:
labda y:
labda:
Line 922 ⟶ 954:
!print fibo j</syntaxhighlight>
===With <code>recurse</code>===
<syntaxhighlight lang="dejavu">fibo-2 n:
n 0 1
labda times back-2 back-1:
Line 941 ⟶ 973:
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">
program AnonymousRecursion;
 
Line 1,001 ⟶ 1,033:
=={{header|EchoLisp}}==
A '''named let''' provides a local lambda via a label.
<syntaxhighlight lang="scheme">
(define (fib n)
(let _fib ((a 1) (b 1) (n n))
Line 1,011 ⟶ 1,043:
=={{header|Ela}}==
Using fix-point combinator:
<syntaxhighlight lang="ela">fib n | n < 0 = fail "Negative n"
| else = fix (\f n -> if n < 2 then n else f (n - 1) + f (n - 2)) n</syntaxhighlight>
Function 'fix' is defined in standard Prelude as follows:
<syntaxhighlight lang="ela">fix f = f (& fix f)</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 46.x:
<syntaxhighlight lang="elena">import extensions;
 
fib(n)
{
if (n < 0)
{ InvalidArgumentException.raise() };
^ (n) {
if (n {> 1)
{ if (n > 1)
^ this self(n {- 2) + (this self(n - 1))
}
^ this self(n - 2) + (this self(n - 1))
}else
{ else
^ {n
^ n }
}(n)
}(n)
}
 
public program()
{
for (int i := -1,; i <= 10,; i += 1)
{
console.print("fib(",i,")=");
try
{
console.printLine(fib(i))
}
catch(Exception e)
{
console.printLine:("invalid")
}
};
console.readChar()
}</syntaxhighlight>
{{out}}
Line 1,073 ⟶ 1,104:
=={{header|Elixir}}==
With Y-Combinator:
<syntaxhighlight lang=Elixir"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 1,091 ⟶ 1,122:
{{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"erlang">
-module( anonymous_recursion ).
-export( [fib/1, fib_internal/1] ).
Line 1,118 ⟶ 1,179:
 
The function 'fib2' is only visible inside the 'fib' function.
<syntaxhighlight lang="fsharp">let fib = function
| n when n < 0 -> None
| n -> let rec fib2 = function
Line 1,125 ⟶ 1,186:
in Some (fib2 n)</syntaxhighlight>
'''Using a fixed point combinator:'''
<syntaxhighlight lang="fsharp">let rec fix f x = f (fix f) x
 
let fib = function
Line 1,132 ⟶ 1,193:
{{out}}
Both functions have the same output.
<syntaxhighlight lang="fsharp">[-1..5] |> List.map fib |> printfn "%A"
[null; Some 1; Some 1; Some 2; Some 3; Some 5; Some 8]</syntaxhighlight>
 
Line 1,139 ⟶ 1,200:
 
To achieve anonymous recursion, this solution has a recursive quotation.
<syntaxhighlight lang="factor">USING: kernel math ;
IN: rosettacode.fibonacci.ar
 
Line 1,160 ⟶ 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.
<syntaxhighlight lang="falcon">function fib(x)
if x < 0
raise ParamError(description|"Negative argument invalid", extra|"Fibbonacci sequence is undefined for negative numbers")
Line 1,198 ⟶ 1,259:
 
=={{header|FBSL}}==
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
FUNCTION Fibonacci(n)
Line 1,230 ⟶ 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.
<syntaxhighlight lang="forth">:noname ( n -- n' )
dup 2 < ?exit
1- dup recurse swap 1- recurse + ; ( xt )
Line 1,238 ⟶ 1,299:
[ ( xt from the :NONAME above ) compile, ] ;</syntaxhighlight>
Portability is achieved with a once-off variable (or any temporary-use space with a constant address - i.e., not PAD):
<syntaxhighlight lang="forth">( xt from :noname in the previous example )
variable pocket pocket !
: fib ( +n -- n' )
Line 1,244 ⟶ 1,305:
[ pocket @ compile, ] ;</syntaxhighlight>
Currently, most Forths have started to support embedded definitions (shown here for iForth):
<syntaxhighlight lang="forth">: fib ( +n -- )
dup 0< abort" Negative numbers don't exist"
[: dup 2 < ?exit 1- dup MYSELF swap 1- MYSELF + ;] execute . ;</syntaxhighlight>
Line 1,250 ⟶ 1,311:
=={{header|Fortran}}==
Since a hidden named function instead of an anonymous one seems to be ok with implementors, here is the Fortran version:
<syntaxhighlight lang=Fortran"fortran">integer function fib(n)
integer, intent(in) :: n
if (n < 0 ) then
Line 1,273 ⟶ 1,334:
 
However, for compatibility with old QB code, gosub can be used if one specifies the 'fblite', 'qb' or 'deprecated dialects:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Lang "fblite"
Line 1,324 ⟶ 1,385:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Anonymous_recursion}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution.'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
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.
In '''[https://formulae.org/?example=Anonymous_recursion this]''' page you can see the program(s) related to this task and their results.
 
[[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.
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,388 ⟶ 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.
<syntaxhighlight lang="groovy">def fib = {
assert it > -1
{i -> i < 2 ? i : {j -> owner.call(j)}(i-1) + {k -> owner.call(k)}(i-2)}(it)
}</syntaxhighlight>
Test:
<syntaxhighlight lang="groovy">def fib0to20 = (0..20).collect(fib)
println fib0to20
 
Line 1,420 ⟶ 1,543:
 
We're defining a function 'real' which is only available from within the fib function.
<syntaxhighlight lang="haskell">fib :: Integer -> Maybe Integer
fib n
| n < 0 = Nothing
Line 1,431 ⟶ 1,554:
 
This uses the 'fix' function to find the fixed point of the anonymous function.
<syntaxhighlight lang="haskell">import Data.Function (fix)
 
fib :: Integer -> Maybe Integer
Line 1,439 ⟶ 1,562:
{{out}}
Both functions provide the same output when run in GHCI.
<syntaxhighlight 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]</syntaxhighlight>
 
Or, without imports (inlining an anonymous fix)
 
<syntaxhighlight lang="haskell">fib :: Integer -> Maybe Integer
fib n
| n < 0 = Nothing
Line 1,476 ⟶ 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.
<syntaxhighlight lang=Icon"icon">procedure main(A)
every write("fib(",a := numeric(!A),")=",fib(a))
end
Line 1,508 ⟶ 1,631:
 
For reference, here is the non-cached version:
<syntaxhighlight lang=Icon"icon">procedure fib(n)
local source, i
if type(n) == "integer" & n >= 0 then
Line 1,521 ⟶ 1,644:
=={{header|Io}}==
The most natural way to solve this task is to use a nested function whose scope is limited to the helper function.
<syntaxhighlight lang=Io"io">fib := method(x,
if(x < 0, Exception raise("Negative argument not allowed!"))
fib2 := method(n,
Line 1,528 ⟶ 1,651:
fib2(x floor)
)</syntaxhighlight>
 
=={{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
190 LET FIB=0
200 CASE 1
210 LET FIB=1
220 CASE ELSE
230 LET FIB=FIB(K-1)+FIB(K-2)
240 END SELECT
250 END DEF</syntaxhighlight>
 
=={{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:
<syntaxhighlight lang="j"> fibN=: (-&2 +&$: -&1)^:(1&<) M."0</syntaxhighlight>
Note that this is an identity function for arguments less than 1 (and 1 (and 5)).
 
'''Examples:'''
<syntaxhighlight lang="j"> fibN 12
144
fibN i.31
Line 1,565 ⟶ 1,670:
Note also http://www.jsoftware.com/pipermail/general/2003-August/015571.html which points out that the form
 
<syntaxhighlight lang="j">basis ` ($: @: g) @. test</syntaxhighlight> which is an anonymous form matches the "tail recursion" pattern is not automatically transformed to satisfy the classic "tail recursion optimization". That optimization would be implemented as transforming this particular example of recursion to the non-recursive <syntaxhighlight lang="j">basis @: (g^:test^:_)</syntaxhighlight>
 
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.
Line 1,578 ⟶ 1,683:
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.
 
<syntaxhighlight lang="java">public static long fib(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not be a negative number");
Line 1,592 ⟶ 1,697:
Note that the fib method below is practically the same as that of the version above, with less fibInner.
 
<syntaxhighlight lang="java5">import java.util.function.Function;
 
@FunctionalInterface
Line 1,619 ⟶ 1,724:
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">function fibo(n) {
if (n < 0) { throw "Argument cannot be negative"; }
 
return (function(n) {
return (n < 2) ? 1n : arguments.callee(n-1) + arguments.callee(n-2);
})(n);
}</syntaxhighlight>
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).
<syntaxhighlight lang="javascript">function fibo(n) {
if (n < 0) { throw "Argument cannot be negative"; }
 
return (function fib(n) {
return (n < 2) ? 1n : fib(n-1) + fib(n-2);
})(n);
}</syntaxhighlight>
Line 1,637 ⟶ 1,742:
=={{header|Joy}}==
This definition is taken from "Recursion Theory and Joy" by Manfred von Thun.
<syntaxhighlight lang=Joy"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:
<syntaxhighlight lang="jq">0 | recurse(. + 1)</syntaxhighlight>
 
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:
<syntaxhighlight lang="jq">def fib(n):
def aux: if . == 0 then 0
elif . == 1 then 1
Line 1,655 ⟶ 1,760:
=={{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.
<syntaxhighlight lang="julia">function fib(n)
if n < 0
throw(ArgumentError("negative arguments not allowed"))
Line 1,664 ⟶ 1,769:
 
=={{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>
<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:'''
<syntaxhighlight lang="k"> fib'!10
0 1 1 2 3 5 8 13 21 34
fib -1
Line 1,672 ⟶ 1,780:
 
=={{header|Klingphix}}==
<syntaxhighlight lang="text">include ..\Utilitys.tlhy
 
Line 1,696 ⟶ 1,804:
 
=={{header|Klong}}==
<syntaxhighlight lang=K"k">
fib::{:[x<0;"error: negative":|x<2;x;.f(x-1)+.f(x-2)]}
</syntaxhighlight>
Line 1,702 ⟶ 1,810:
=={{header|Kotlin}}==
{{trans|Dylan}}
<syntaxhighlight lang=scala"kotlin">fun fib(n: Int): Int {
require(n >= 0)
fun fib1fib(k: Int, a: Int, b: Int): Int =
if (k == 0) a else fib1fib(k - 1, b, a + b)
return fib1fib(n, 0, 1)
}
 
Line 1,720 ⟶ 1,828:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1) defining a quasi-recursive function combined with a simple Ω-combinator:
{def fibo {lambda {:n}
Line 1,752 ⟶ 1,860:
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":
<syntaxhighlight lang="lingo">on fib (n)
if n<0 then return _player.alert("negative arguments not allowed")
 
Line 1,769 ⟶ 1,896:
end</syntaxhighlight>
 
<syntaxhighlight lang="lingo">put fib(10)
-- 55</syntaxhighlight>
 
=={{header|LOLCODE}}==
{{trans|C}}
<syntaxhighlight lang=LOLCODE"lolcode">HAI 1.3
 
HOW IZ I fib YR x
Line 1,809 ⟶ 1,936:
=={{header|Lua}}==
Using a [[Y combinator]].
<syntaxhighlight lang="lua">local function Y(x) return (function (f) return f(f) end)(function(y) return x(function(z) return y(y)(z) end) end) end
 
return Y(function(fibs)
Line 1,817 ⟶ 1,944:
end)</syntaxhighlight>
using a metatable (also achieves memoization)
<syntaxhighlight lang="lua">return setmetatable({1,1},{__index = function(self, n)
self[n] = self[n-1] + self[n-2]
return self[n]
Line 1,825 ⟶ 1,952:
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"m2000 Interpreterinterpreter">
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,836 ⟶ 1,963:
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"m2000 Interpreterinterpreter">
Function fib(x) {
If x<0 then Error "argument outside of range"
Line 1,852 ⟶ 1,979:
Using lambda function
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
fib=lambda -> {
fib1=lambda (x)->If(x>1->lambda(x-1)+lambda(x-2), x)
Line 1,883 ⟶ 2,010:
 
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Class Something {
\\ this class is a global function
Line 1,912 ⟶ 2,039:
=={{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"maple">
Fib := proc( n :: nonnegint )
proc( k )
Line 1,928 ⟶ 2,055:
</syntaxhighlight>
For example:
<syntaxhighlight lang=Maple"maple">
> seq( Fib( i ), i = 0 .. 10 );
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
Line 1,940 ⟶ 2,067:
=={{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.
<syntaxhighlight lang=Mathematica"mathematica">check := #<0&
fib := If[check[#],Throw["Negative Argument"],If[#<=1,1,#0[#-2]+#0[#-1]]&[#]]&
fib /@ Range[0,10]
Line 1,946 ⟶ 2,073:
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}</syntaxhighlight>
Making sure that the check is only performed once.
<syntaxhighlight lang=Mathematica"mathematica">check := (Print[#];#<0)&
fib /@ Range[0,4]
0
Line 1,960 ⟶ 2,087:
* 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"matlab">
function v = fibonacci(n)
assert(n >= 0)
Line 1,979 ⟶ 2,106:
* inner function not expected to be called from anywhere else
* nesting maintains program flow in source code
<syntaxhighlight lang=Nemerle"nemerle">using System;
using System.Console;
 
Line 2,011 ⟶ 2,138:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim"># Using scoped function fibI inside fib
proc fib(x: int): int =
proc fibI(n: int): int =
Line 2,032 ⟶ 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.
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface AnonymousRecursion : NSObject { }
Line 2,067 ⟶ 2,194:
;With internal named recursive block:
{{works with|Mac OS X|10.6+}}
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int fib(int n) {
Line 2,095 ⟶ 2,222:
 
When ARC is disabled, the above should be:
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int fib(int n) {
Line 2,128 ⟶ 2,255:
 
We're defining a function 'real' which is only available from within the fib function.
<syntaxhighlight lang="ocaml">let fib n =
let rec real = function
0 -> 1
Line 2,142 ⟶ 2,269:
 
This uses the 'fix' function to find the fixed point of the anonymous function.
<syntaxhighlight lang="ocaml">let rec fix f x = f (fix f) x
 
let fib n =
Line 2,155 ⟶ 2,282:
=={{header|Ol}}==
This uses named let to create a local function (loop) that only exists inside of function fibonacci.
<syntaxhighlight lang="scheme">
(define (fibonacci n)
(if (> 0 n)
Line 2,172 ⟶ 2,299:
=={{header|OxygenBasic}}==
An inner function keeps the name-space clean:
<syntaxhighlight lang="oxygenbasic">
function fiboRatio() as double
function fibo( double i, j ) as double
Line 2,187 ⟶ 2,314:
=={{header|PARI/GP}}==
This version uses a Y combinator to get a self-reference.
<syntaxhighlight lang="parigp">Fib(n)={
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)
Line 2,194 ⟶ 2,321:
{{works with|PARI/GP|2.8.1+}}
This version gets a self-reference from <code>self()</code>.
<syntaxhighlight lang="parigp">Fib(n)={
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))
Line 2,200 ⟶ 2,327:
 
=={{header|Pascal}}==
<syntaxhighlight lang=Pascal"pascal">
program AnonymousRecursion;
 
Line 2,257 ⟶ 2,384:
{{trans|PicoLisp}}
<code>recur</code> isn't built into Perl, but it's easy to implement.
<syntaxhighlight lang="perl">sub recur :prototype(&@) {
my $f = shift;
local *recurse = $f;
Line 2,272 ⟶ 2,399:
}</syntaxhighlight>
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:
<syntaxhighlight lang="perl">sub fib {
my ($n) = @_;
die "negative arg $n" if $n < 0;
Line 2,286 ⟶ 2,413:
print(fib($_), " ") for (0 .. 10);</syntaxhighlight>
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.
<syntaxhighlight lang="perl">sub fibo {
my $n = shift;
$n < 0 and die 'Negative argument';
Line 2,294 ⟶ 2,421:
===Perl 5.16 and __SUB__===
Perl 5.16 introduced __SUB__ which refers to the current subroutine.
<syntaxhighlight lang=Perl"perl">use v5.16;
say sub {
my $n = shift;
Line 2,304 ⟶ 2,431:
===using classes===
With proof that the private fib_i() does not pollute the outer namespace.
<!--<syntaxhighlight lang=Phix"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>
Line 2,334 ⟶ 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"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>
Line 2,355 ⟶ 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+}}
<syntaxhighlight lang="php"><?php
function fib($n) {
if ($n < 0)
Line 2,374 ⟶ 2,501:
;With internal named recursive function:
{{works with|PHP|5.3+}}
<syntaxhighlight lang="php"><?php
function fib($n) {
if ($n < 0)
Line 2,391 ⟶ 2,518:
;With a function object that can call itself using <code>$this</code>:
{{works with|PHP|5.3+}}
<syntaxhighlight lang="php"><?php
class fib_helper {
function __invoke($n) {
Line 2,411 ⟶ 2,538:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de fibo (N)
(if (lt0 N)
(quit "Illegal argument" N) )
Line 2,419 ⟶ 2,546:
(+ (recurse (dec N)) (recurse (- N 2))) ) ) )</syntaxhighlight>
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
<syntaxhighlight lang=PicoLisp"picolisp">(de recur recurse
(run (cdr recurse)) )</syntaxhighlight>
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,426 ⟶ 2,553:
{{libheader|initlib}}
Postscript can make use of the higher order combinators to provide recursion.
<syntaxhighlight lang="postscript">% primitive recursion
/pfact {
{1} {*} primrec}.
Line 2,453 ⟶ 2,580:
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.
<syntaxhighlight lang="prolog">:- use_module(lambda).
 
fib(N, _F) :-
Line 2,478 ⟶ 2,605:
 
=={{header|Python}}==
<syntaxhighlight lang="python">>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> 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) ]
Line 2,484 ⟶ 2,611:
 
Same thing as the above, but modified so that the function is uncurried:
<syntaxhighlight lang="python">>>>from functools import partial
>>> 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)))
Line 2,491 ⟶ 2,618:
 
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
<syntaxhighlight lang="python">>>> from functools import partial
>>> 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)))
Line 2,498 ⟶ 2,625:
 
An interesting approach using introspection (from http://metapython.blogspot.com/2010/11/recursive-lambda-functions.html)
<syntaxhighlight lang="python">
>>> from inspect import currentframe
>>> from types import FunctionType
Line 2,512 ⟶ 2,639:
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.
 
<syntaxhighlight lang="python">
>>> 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
Line 2,520 ⟶ 2,647:
 
All in one line:
<syntaxhighlight lang="python">
>>> 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) ]
Line 2,530 ⟶ 2,657:
{{works with|QBasic}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">DECLARE FUNCTION Fibonacci! (num!)
 
PRINT Fibonacci(20)
Line 2,563 ⟶ 2,690:
However, it can be done, for instance like this:
 
<syntaxhighlight lang=Qi"qi">
(define fib
N -> (let A (/. A N
Line 2,617 ⟶ 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.
<syntaxhighlight lang=R"r">fib2 <- function(n) {
(n >= 0) || stop("bad argument")
( function(n) if (n <= 1) 1 else Recall(n-1)+Recall(n-2) )(n)
Line 2,626 ⟶ 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.
 
<syntaxhighlight lang="racket">
#lang racket
Line 2,648 ⟶ 2,775:
 
This calculates the slightly more complex Fibonacci funciton:
<syntaxhighlight lang="racket">
#lang racket
;; Natural -> Natural
Line 2,673 ⟶ 2,800:
Also with the help of first-class functions in Racket, anonymous recursion can be implemented using fixed-points operators:
 
<syntaxhighlight lang="racket">
#lang racket
;; We use Z combinator (applicative order fixed-point operator)
Line 2,704 ⟶ 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=perl6"raku" line>sub fib($n) {
die "Naughty fib" if $n < 0;
return {
Line 2,715 ⟶ 2,842:
say fib(10);</syntaxhighlight>
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=perl6"raku" line>constant @fib = 0, 1, *+* ... *;
say @fib[10];</syntaxhighlight>
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,723 ⟶ 2,850:
=={{header|REBOL}}==
 
<syntaxhighlight lang="rebol">
fib: func [n /f][ do f: func [m] [ either m < 2 [m][(f m - 1) + f m - 2]] n]
</syntaxhighlight>
Line 2,732 ⟶ 2,859:
to be OK with the implementers, here are the REXX versions.
===simplistic===
<syntaxhighlight lang="rexx">/*REXX program to show anonymous recursion (of a function or subroutine). */
numeric digits 1e6 /*in case the user goes ka-razy with X.*/
parse arg x . /*obtain the optional argument from CL.*/
Line 2,765 ⟶ 2,892:
Since the above REXX version is &nbsp; ''very'' &nbsp; slow for larger numbers, the following version was added that incorporates memoization. &nbsp;
<br>It's many orders of magnitude faster for larger values.
<syntaxhighlight lang="rexx">/*REXX program to show anonymous recursion of a function or subroutine with memoization.*/
numeric digits 1e6 /*in case the user goes ka-razy with X.*/
parse arg x . /*obtain the optional argument from CL.*/
Line 2,782 ⟶ 2,909:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Anonymous recursion
 
Line 2,839 ⟶ 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,845 ⟶ 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===
<syntaxhighlight lang="ruby">def fib(n)
raise RangeError, "fib of negative" if n < 0
(fib2 = proc { |m| m < 2 ? m : fib2[m - 1] + fib2[m - 2] })[n]
end</syntaxhighlight>
 
<syntaxhighlight lang="ruby">(-2..12).map { |i| fib i rescue :error }
=> [:error, :error, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]</syntaxhighlight>
 
Line 2,859 ⟶ 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.
<syntaxhighlight lang="ruby">def fib(n)
raise RangeError, "fib of negative" if n < 0
(fib2 = proc { |n| n < 2 ? n : fib2[n - 1] + fib2[n - 2] })[n]
end</syntaxhighlight>
<syntaxhighlight lang="ruby"># Ruby 1.9
(-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,872 ⟶ 3,033:
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===
<syntaxhighlight lang="ruby">def fib(n)
raise RangeError, "fib of negative" if n < 0
Hash.new { |fib2, m|
Line 2,884 ⟶ 3,045:
{{trans|PicoLisp}}
{{libheader|continuation}}
<syntaxhighlight lang="ruby">require 'continuation' unless defined? Continuation
 
module Kernel
Line 2,912 ⟶ 3,073:
{{trans|JavaScript}}
{{libheader|continuation}}
<syntaxhighlight lang="ruby">require 'continuation' unless defined? Continuation
 
module Kernel
Line 2,947 ⟶ 3,108:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn fib(n: i64) -> Option<i64> {
// A function declared inside another function does not pollute the outer namespace.
fn actual_fib(n: i64) -> i64 {
Line 2,993 ⟶ 3,154:
=={{header|Scala}}==
Using a Y-combinator:
<syntaxhighlight lang="scala">def Y[A, B](f: (A ⇒ B) ⇒ (A ⇒ B)): A ⇒ B = f(Y(f))(_)
def fib(n: Int): Option[Int] =
Line 3,016 ⟶ 3,177:
=={{header|Scheme}}==
This uses named let to create a function (aux) that only exists inside of fibonacci:
<syntaxhighlight lang="scheme">(define (fibonacci n)
(if (> 0 n)
"Error: argument must not be negative."
Line 3,030 ⟶ 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.
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: fib (in integer: x) is func
Line 3,074 ⟶ 3,235:
=={{header|Sidef}}==
__FUNC__ refers to the current function.
<syntaxhighlight lang="ruby">func fib(n) {
return NaN if (n < 0)
 
Line 3,085 ⟶ 3,246:
__BLOCK__ refers to the current block.
 
<syntaxhighlight lang="ruby">func fib(n) {
return NaN if (n < 0)
 
Line 3,103 ⟶ 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).
<syntaxhighlight lang="smalltalk">
myMethodComputingFib:arg
|_|
Line 3,114 ⟶ 3,275:
<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.
<syntaxhighlight lang="smalltalk">
myMethodComputingFib2:arg
^ [
Line 3,128 ⟶ 3,289:
=={{header|Sparkling}}==
As a function expression:
<syntaxhighlight lang=Sparkling"sparkling">function(n, f) {
return f(n, f);
}(10, function(n, f) {
Line 3,136 ⟶ 3,297:
 
When typed into the REPL:
<syntaxhighlight lang=Sparkling"sparkling">spn:1> function(n, f) { return f(n, f); }(10, function(n, f) { return n < 2 ? 1 : f(n - 1, f) + f(n - 2, f); })
= 89</syntaxhighlight>
 
=={{header|Standard ML}}==
ML does not have a built-in construct for anonymous recursion, but you can easily write your own fix-point combinator:
<syntaxhighlight lang="sml">fun fix f x = f (fix f) x
 
fun fib n =
Line 3,152 ⟶ 3,313:
 
Instead of using a fix-point, the more common approach is to locally define a recursive function and call it once:
<syntaxhighlight lang="sml">fun fib n =
let
fun fib 0 = 0
Line 3,168 ⟶ 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":
<syntaxhighlight lang="sml">fun fib 0 = 0
| fib 1 = 1
| fib n = fib (n-1) + fib (n-2)
Line 3,179 ⟶ 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"supercollider">
(
f = { |n|
Line 3,193 ⟶ 3,354:
;With internal named recursive closure:
{{works with|Swift|2.x}}
<syntaxhighlight lang="swift">let fib: Int -> Int = {
func f(n: Int) -> Int {
assert(n >= 0, "fib: no negative numbers")
Line 3,203 ⟶ 3,364:
print(fib(8))</syntaxhighlight>
{{works with|Swift|1.x}}
<syntaxhighlight lang="swift">let fib: Int -> Int = {
var f: (Int -> Int)!
f = { n in
Line 3,215 ⟶ 3,376:
 
;Using Y combinator:
<syntaxhighlight lang="swift">struct RecursiveFunc<F> {
let o : RecursiveFunc<F> -> F
}
Line 3,236 ⟶ 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.
<syntaxhighlight lang="tcl">proc fib n {
# sanity checks
if {[incr n 0] < 0} {error "argument may not be negative"}
Line 3,247 ⟶ 3,408:
}</syntaxhighlight>
Demonstrating:
<syntaxhighlight lang="tcl">puts [fib 12]</syntaxhighlight>
{{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:
<syntaxhighlight lang="tcl">proc fib n {
if {[incr n 0] < 0} {error "argument may not be negative"}
apply {x {expr {
Line 3,261 ⟶ 3,422:
}</syntaxhighlight>
However, we can create a <code>recurse</code> function that makes this much more straight-forward:
<syntaxhighlight lang="tcl"># Pick the lambda term out of the introspected caller's stack frame
proc tcl::mathfunc::recurse args {apply [lindex [info level -1] 1] {*}$args}
proc fib n {
Line 3,274 ⟶ 3,435:
{{trans|BASIC256}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">FUNCTION Fibonacci (num)
IF num < 0 THEN
PRINT "Invalid argument: ";
Line 3,305 ⟶ 3,466:
{{trans|Common_Lisp}}
 
<syntaxhighlight lang="txrlisp">(defmacro recursive ((. parm-init-pairs) . body)
(let ((hidden-name (gensym "RECURSIVE-")))
^(macrolet ((recurse (. args) ^(,',hidden-name ,*args)))
Line 3,333 ⟶ 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.
<syntaxhighlight lang="bash">fib() {
if test 0 -gt "$1"; then
echo "fib: fib of negative" 1>&2
Line 3,350 ⟶ 3,511:
fi
}</syntaxhighlight>
<syntaxhighlight lang="bash">$ for i in -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12; do
> fib $i
> done
Line 3,370 ⟶ 3,531:
 
=={{header|Ursala}}==
<syntaxhighlight lang=Ursala"ursala">#import nat
 
fib =
Line 3,391 ⟶ 3,552:
'''Solution with anonymous class'''
 
<syntaxhighlight lang=UTFool"utfool">
···
http://rosettacode.org/wiki/Anonymous_recursion
Line 3,412 ⟶ 3,573:
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Sub Main()
Debug.Print F(-10)
Line 3,432 ⟶ 3,593:
 
=={{header|Wart}}==
<syntaxhighlight lang="wart">def (fib n)
if (n >= 0)
(transform n :thru (afn (n)
Line 3,443 ⟶ 3,604:
 
=={{header|WDTE}}==
<syntaxhighlight lang=WDTE"wdte">let str => 'strings';
 
let fib n => switch n {
Line 3,456 ⟶ 3,617:
 
=={{header|Wren}}==
<syntaxhighlight lang=ecmascript"wren">class Fibonacci {
static compute(n) {
var fib
Line 3,484 ⟶ 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.
<syntaxhighlight lang="asm">
; Calculates and prints Fibonacci numbers (Fn)
; Prints numbers 1 - 47 (largest 32bit Fn that fits)
Line 3,580 ⟶ 3,741:
This makes those nested functions invisible to the outside, thus preventing namespace pollution.
 
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes;
 
func Fib(X);
Line 3,606 ⟶ 3,767:
=={{header|Yabasic}}==
{{trans|AutoIt}}
<syntaxhighlight lang=Yabasic"yabasic">print Fibonacci(-10)
print Fibonacci(10)
 
Line 3,623 ⟶ 3,784:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn fib(n){
if (n<0) throw(Exception.ValueError);
fcn(n){
Line 3,641 ⟶ 3,802:
=={{header|ZX Spectrum Basic}}==
{{trans|AutoHotkey}}
<syntaxhighlight lang="zxbasic">10 INPUT "Enter a number: ";n
20 LET t=0
30 GO SUB 60
Anonymous user