Mutual recursion: Difference between revisions

Add ABC
(Added Quackery.)
(Add ABC)
 
(40 intermediate revisions by 24 users not shown)
Line 37:
in a recursive routine, as the code below does.
 
<langsyntaxhighlight lang="8080asm"> org 100h
jmp test
;;; Implementation of F(A).
Line 104:
jmp 5 ; Tail call optimization
fpfx: db 'F: $'
mpfx: db 13,10,'M: $'</langsyntaxhighlight>
 
{{out}}
Line 114:
This works for ABAP Version 7.40 and can be implemented in procedural ABAP as well, but with classes it is much more readable. As this allows a method with a returning value to be an input for a subsequent method call.
 
<syntaxhighlight lang="abap">
<lang ABAP>
report z_mutual_recursion.
 
Line 162:
for i = 1 while i < 20
next results = |{ results }, { hoffstadter_sequences=>m( i ) }| ) }|, /.
</syntaxhighlight>
</lang>
 
{{output}}
Line 170:
m(0 - 19): 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO RETURN f n:
IF n=0: RETURN 1
RETURN n - m f (n-1)
 
HOW TO RETURN m n:
IF n=0: RETURN 0
RETURN n - f m (n-1)
 
WRITE "F:"
FOR n IN {0..15}: WRITE f n
WRITE /
 
WRITE "M:"
FOR n IN {0..15}: WRITE m n
WRITE /</syntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9</pre>
 
=={{header|ACL2}}==
<langsyntaxhighlight lang="lisp">(mutual-recursion
(defun f (n)
(declare (xargs :mode :program))
Line 183 ⟶ 203:
(if (zp n)
0
(- n (f (m (1- n)))))))</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_Io; use Ada.Text_Io;
procedure Mutual_Recursion is
function M(N : Integer) return Integer;
Line 213 ⟶ 233:
Put_Line(Integer'Image(M(I)));
end loop;
end Mutual_recursion;</langsyntaxhighlight>
 
{{Works with|Ada 2012}}
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
procedure Mutual_Recursion is
function M(N: Natural) return Natural;
Line 235 ⟶ 255:
end loop;
end Mutual_recursion;</langsyntaxhighlight>
 
=={{header|Aime}}==
{{trans|C}}
 
<langsyntaxhighlight lang="aime">integer F(integer n);
integer M(integer n);
 
Line 281 ⟶ 301:
o_byte('\n');
return 0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 289 ⟶ 309:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">PROC (INT)INT m; # ONLY required for ELLA ALGOL 68RS - an official subset OF full ALGOL 68 #
 
PROC f = (INT n)INT:
Line 309 ⟶ 329:
OD;
new line(stand out)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 317 ⟶ 337:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% define mutually recursive funtions F and M that compute the elements %
% of the Hofstadter Female and Male sequences %
Line 334 ⟶ 354:
for i := 0 until 20 do writeon( M( i ) );
 
end.</langsyntaxhighlight>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">f ← {⍵=0:1 ⋄ ⍵-m∇⍵-1}
m ← {⍵=0:0 ⋄ ⍵-f∇⍵-1}
⍉'nFM'⍪↑(⊢,f,m)¨0,⍳20</syntaxhighlight>
{{out}}
<pre>n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
F 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13
M 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12</pre>
 
=={{header|AppleScript}}==
 
<langsyntaxhighlight AppleScriptlang="applescript">-- f :: Int -> Int
on f(x)
if x = 0 then
Line 403 ⟶ 433:
end repeat
return lst
end range</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12},
{0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12}}</langsyntaxhighlight>
 
=={{header|ArturoARM Assembly}}==
Unlike on the x86 family of processors, the ARM instruction set does not include specialized
<code>call</code> and <code>ret</code> instructions. However, the program counter is a visible
register (<code>r15</code>, also called <code>pc</code>), so it can be loaded and saved
as any other. Nor is there a specialized stack pointer, though the load and store instructions offer
pre- and postincrement as well as pre- and postdecrement on the register used as a pointer, making
any register usable as a stack pointer.
 
By convention, <code>r13</code> is used as the system stack pointer and is therefore also
<lang arturo>f: @(n)-> if n=0 {1} { n-[m|f n-1] }
called <code>sp</code>, and <code>r14</code> is used to store the return address for
m: @(n)-> if n=0 {0} { n-[f|m n-1] }
a function, and is therefore also called the *link register* or <code>lr</code>.
The assembler recognizes <code>push {x}</code> and <code>pop {x}</code> instructions, though these
are really pseudoinstructions, that generate the exact same machine code as
<code>ldmia r13!,{x}</code> and <code>stmdb r13!,{x}</code>,
these being, respectively, load with postincrement and store with predecrement on r13.
 
The link register is slightly special in that there is a family of branch-and-link instructions
loop 0..10 {
(<code>bl</code>). These are the same as <code>mov r14,pc ; mov/ldr pc,<destination></code>, but in
print "f("+&+")= " + [f &]
one machine instruction instead of two. This is the general way of calling subroutines,
print "m("+&+")= " + [m &] + "\n"
meaning no stack access is necessary unless the subroutine wants to call others in turn, in which case
}
the link register must be saved by hand (as the code below shows several ways of doing).
</lang>
 
<syntaxhighlight lang="text">.text
.global _start
@@@ Implementation of F(n), n in R0. n is considered unsigned.
F: tst r0,r0 @ n = 0?
moveq r0,#1 @ In that case, the result is 1
bxeq lr @ And we can return to the caller
push {r0,lr} @ Save link register and argument to stack
sub r0,r0,#1 @ r0 -= 1 = n-1
bl F @ r0 = F(r0) = F(n-1)
bl M @ r0 = M(r0) = M(F(n-1))
pop {r1,lr} @ Restore link register and argument in r1
sub r0,r1,r0 @ Result is n-F(M(n-1))
bx lr @ Return to caller.
 
@@@ Implementation of M(n), n in R0. n is considered unsigned.
M: tst r0,r0 @ n = 0?
bxeq lr @ In that case the result is also 0; return.
push {r0,lr} @ Save link register and argument to stack
sub r0,r0,#1 @ r0 -= 1 = n-1
bl M @ r0 = M(r0) = M(n-1)
bl F @ r0 = M(r0) = F(M(n-1))
pop {r1,lr} @ Restore link register and argument in r1
sub r0,r1,r0 @ Result is n-M(F(n-1))
bx lr @ Return to caller
 
@@@ Print F(0..15) and M(0..15)
_start: ldr r1,=fmsg @ Print values for F
ldr r4,=F
bl prfn
ldr r1,=mmsg @ Print values for M
ldr r4,=M
bl prfn
mov r7,#1 @ Exit process
swi #0
@@@ Helper function for output: print [r1], then [r4](0..15)
@@@ This assumes [r4] preserves r3 and r4; M and F do.
prfn: push {lr} @ Keep link register
bl pstr @ Print the string
mov r3,#0 @ Start at 0
1: mov r0,r3 @ Call the function in r4 with current number
blx r4
add r0,r0,#'0 @ Make ASCII digit
ldr r1,=dgt @ Store in digit string
strb r0,[r1]
ldr r1,=dstr @ Print result
bl pstr
add r3,r3,#1 @ Next number
cmp r3,#15 @ Keep going up to and including 15
bls 1b
ldr r1,=nl @ Print newline afterwards
bl pstr
pop {pc} @ Return to address on stack
@@@ Print length-prefixed string r1 to stdout
pstr: push {lr} @ Keep link register
mov r0,#1 @ stdout = 1
ldrb r2,[r1],#1 @ r2 = length prefix
mov r7,#4 @ 4 = write syscall
swi #0
pop {pc} @ Return to address on stack
.data
fmsg: .ascii "\3F: "
mmsg: .ascii "\3M: "
dstr: .ascii "\2"
dgt: .ascii "* "
nl: .ascii "\1\n"</syntaxhighlight>
 
{{out}}
 
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
<pre>f(0)= 1
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9</pre>
m(0)= 0
 
=={{header|Arturo}}==
f(1)= 1
<syntaxhighlight lang="rebol">f: $[n][ if? n=0 -> 1 else -> n-m f n-1 ]
m(1)= 0
m: $[n][ if? n=0 -> 0 else -> n-f m n-1 ]
loop 0..20 'i [
print ["f(" i ")=" f i]
print ["m(" i ")=" m i]
print ""
]</syntaxhighlight>
 
{{out}}
f(2)= 2
m(2)= 1
 
<pre>f(3 0 )= 21
m(3 0 )= 20
 
f(4 1 )= 31
m(4 1 )= 20
 
f(5 2 )= 32
m(5 2 )= 31
 
f(6 3 )= 42
m(6 3 )= 42
 
f(7 4 )= 53
m(7 4 )= 42
 
f(8 5 )= 53
m(8 5 )= 53
 
f(9 6 )= 64
m(9 6 )= 64
 
f(10 7 )= 65
m(10 7 )= 64
 
f( 8 )= 5
</pre>
m( 8 )= 5
 
f( 9 )= 6
m( 9 )= 6
 
f( 10 )= 6
m( 10 )= 6
 
f( 11 )= 7
m( 11 )= 7
 
f( 12 )= 8
m( 12 )= 7
 
f( 13 )= 8
m( 13 )= 8
 
f( 14 )= 9
m( 14 )= 9
 
f( 15 )= 9
m( 15 )= 9
 
f( 16 )= 10
m( 16 )= 10
 
f( 17 )= 11
m( 17 )= 11
 
f( 18 )= 11
m( 18 )= 11
 
f( 19 )= 12
m( 19 )= 12
 
f( 20 )= 13
m( 20 )= 12</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop 20
i := A_Index-1, t .= "`n" i "`t " M(i) "`t " F(i)
MsgBox x`tmale`tfemale`n%t%
Line 468 ⟶ 619:
M(n) {
Return n ? n - F(M(n-1)) : 0
}</langsyntaxhighlight>
 
{{trans|C}}
Line 474 ⟶ 625:
This one is an alternative to the above.
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">main()
Return
 
Line 504 ⟶ 655:
MsgBox % "male:`n" . male
MsgBox % "female:`n" . female
}</langsyntaxhighlight>
 
=={{header|AWK}}==
In AWK it is enough that both functions are defined somewhere. It matters not whether the BEGIN block is before or after the function definitions.
 
<langsyntaxhighlight lang="awk">cat mutual_recursion.awk:
#!/usr/local/bin/gawk -f
 
Line 528 ⟶ 679:
}
print ""
}</langsyntaxhighlight>
 
{{out}}
Line 538 ⟶ 689:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">' Mutually recursive
FUNCTION F(int n) TYPE int
RETURN IIF(n = 0, 1, n - M(F(n -1)))
Line 558 ⟶ 709:
PRINT M(i) FORMAT "%2d "
NEXT
PRINT</langsyntaxhighlight>
 
{{out}}
Line 567 ⟶ 718:
=={{header|BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic">DECLARE FUNCTION f! (n!)
DECLARE FUNCTION m! (n!)
 
Line 584 ⟶ 735:
m = f(m(n - 1))
END IF
END FUNCTION</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> @% = 3 : REM Column width
PRINT "F sequence:"
FOR i% = 0 TO 20
Line 602 ⟶ 753:
DEF FNf(n%) IF n% = 0 THEN = 1 ELSE = n% - FNm(FNf(n% - 1))
DEF FNm(n%) IF n% = 0 THEN = 0 ELSE = n% - FNf(FNm(n% - 1))</langsyntaxhighlight>
{{out}}
<pre>
Line 612 ⟶ 763:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Hofstad.bas"
110 PRINT "F sequence:"
120 FOR I=0 TO 20
Line 634 ⟶ 785:
300 LET M=N-F(M(N-1))
310 END IF
320 END DEF</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256"># Rosetta Code problem: http://rosettacode.org/wiki/Mutual_recursion
# by Jjuanhdez, 06/2022
 
n = 24
print "n : ";
for i = 0 to n : print ljust(i, 3); : next i
print chr(10); ("-" * 78)
print "F : ";
for i = 0 to n : print ljust(F(i), 3); : next i
print chr(10); "M : ";
for i = 0 to n : print ljust(M(i), 3); : next i
end
 
function F(n)
if n = 0 then return 0 else return n - M(F(n-1))
end function
 
function M(n)
if n = 0 then return 0 else return n - F(M(n-1))
end function</syntaxhighlight>
 
=={{header|Bc}}==
 
<langsyntaxhighlight lang="bc">cat mutual_recursion.bc:
define f(n) {
if ( n == 0 ) return(1);
Line 647 ⟶ 820:
if ( n == 0 ) return(0);
return(n - f(m(n-1)));
}</langsyntaxhighlight>
 
{{works with|GNU bc}}
Line 653 ⟶ 826:
POSIX bc doesn't have the <tt>print</tt> statement.
 
<langsyntaxhighlight lang="bc">/* GNU bc */
for(i=0; i < 19; i++) {
print f(i); print " ";
Line 662 ⟶ 835:
}
print "\n";
quit</langsyntaxhighlight>
 
{{out}}
Line 674 ⟶ 847:
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12
</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
// Mutually recursive functions
let f(n) = n=0 -> 1, n - m(f(n-1))
and m(n) = n=0 -> 0, n - f(m(n-1))
 
// Print f(0..15) and m(0..15)
let start() be
$( writes("F:")
for i=0 to 15 do
$( writes(" ")
writen(f(i))
$)
writes("*NM:")
for i=0 to 15 do
$( writes(" ")
writen(m(i))
$)
writes("*N")
$)</syntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">F ← {0:1; 𝕩-M F𝕩-1}
M ← {0:0; 𝕩-F M𝕩-1}
⍉"FM"∾>(F∾M)¨↕15</syntaxhighlight>
{{out}}
<pre>┌─
╵ 'F' 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9
'M' 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9
┘</pre>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> (F=.!arg:0&1|!arg+-1*M$(F$(!arg+-1)));
(M=.!arg:0&0|!arg+-1*F$(M$(!arg+-1)));
 
Line 683 ⟶ 891:
 
-1:?n&whl'(!n+1:~>20:?n&put$(M$!n " "))&put$\n
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">female = null #yes, this is necessary
 
male = { n |
Line 701 ⟶ 909:
 
p 0.to(20).map! { n | female n }
p 0.to(20).map! { n | male n }</langsyntaxhighlight>
 
=={{header|Bruijn}}==
Normally it's not possible to call functions before they are defined. We can still induce mutual recursion using its [[Variadic_fixed-point_combinator|variadic fixed-point combinator]].
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/Number .
:import std/List .
 
f' [[[=?0 (+1) (0 - (1 (2 --0)))]]]
 
m' [[[=?0 (+0) (0 - (2 (1 --0)))]]]
 
f ^(y* (f' : {}m'))
 
m _(y* (f' : {}m'))
 
:test ((f (+0)) =? (+1)) ([[1]])
:test ((m (+0)) =? (+0)) ([[1]])
:test ((f (+4)) =? (+3)) ([[1]])
:test ((m (+4)) =? (+2)) ([[1]])
:test ((f (+15)) =? (+9)) ([[1]])
:test ((m (+15)) =? (+9)) ([[1]])
</syntaxhighlight>
 
=={{header|C}}==
Line 707 ⟶ 938:
To let C see functions that will be used, it is enough to declare them. Normally this is done in a header file; in this example we do it directly in the code. If we do not declare them explicitly, they get an implicit declaration (if implicit declaration matches the use, everything's fine; but it is better however to write an explicit declaration)
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 736 ⟶ 967:
printf("\n");
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">namespace RosettaCode {
class Hofstadter {
static public int F(int n) {
Line 759 ⟶ 990:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
C++ has prior declaration rules similar to those stated above for [[Mutual Recursion#C|C]], if we would use two functions. Instead here we define M and F as static (class) methods of a class, and specify the bodies inline in the declaration of the class. Inlined methods in the class can still call other methods or access fields in the class, no matter what order they are declared in, without any additional pre-declaration. This is possible because all the possible methods and fields are declared somewhere in the class declaration, which is known the first time the class declaration is parsed.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <vector>
#include <iterator>
Line 798 ⟶ 1,029:
cout << endl;
return 0;
}</langsyntaxhighlight>
 
The following version shows better what's going on and why we ''seemingly'' didn't need pre-declaration (like C) when "encapsulating" the functions as static (class) methods.
Line 804 ⟶ 1,035:
This version is equivalent to the above but does not inline the definition of the methods into the definition of the class. Here the method declarations in the class definition serves as the "pre-declaration" for the methods, as in C.
 
<langsyntaxhighlight lang="cpp">class Hofstadter
{
public:
Line 821 ⟶ 1,052:
if ( n == 0 ) return 0;
return n - F(M(n-1));
}</langsyntaxhighlight>
 
=={{header|Ceylon}}==
 
<langsyntaxhighlight lang="ceylon">Integer f(Integer n)
=> if (n > 0)
then n - m(f(n-1))
Line 838 ⟶ 1,069:
printAll((0:20).map(f));
printAll((0:20).map(m));
}</langsyntaxhighlight>
 
{{out}}
Line 848 ⟶ 1,079:
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">(declare F) ; forward reference
 
(defn M [n]
Line 858 ⟶ 1,089:
(if (zero? n)
1
(- n (M (F (dec n))))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">
% To declare things you can either write an .spc file or you can use
% the clu file itself as a specfile. For a small program a common
% idiom is to spec and compile the same source file:
%
% pclu -spec mutrec.clu -clu mutrec.clu
%
start_up = proc ()
print_first_16("F", F)
print_first_16("M", M)
end start_up
 
% Print the first few values for F and M
print_first_16 = proc (name: string, fn: proctype (int) returns (int))
po: stream := stream$primary_output()
stream$puts(po, name || ":")
for i: int in int$from_to(0, 15) do
stream$puts(po, " " || int$unparse(fn(i)))
end
stream$putl(po, "")
end print_first_16
 
F = proc (n: int) returns (int)
if n = 0 then
return (1)
else
return (n - M(F(n-1)))
end
end F
 
M = proc (n: int) returns (int)
if n = 0 then
return (0)
else
return (n - F(M(n-1)))
end
end M
</syntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9</pre>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
F = (n) ->
if n is 0 then 1 else n - M F n - 1
Line 870 ⟶ 1,144:
console.log [0...20].map F
console.log [0...20].map M
</syntaxhighlight>
</lang>
 
{{out}}
<syntaxhighlight lang="text">
> coffee mutual_recurse.coffee
[ 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12 ]
[ 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12 ]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun m (n)
(if (zerop n)
0
Line 889 ⟶ 1,163:
(if (zerop n)
1
(- n (m (f (- n 1))))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
int male(in int n) pure nothrow {
Line 905 ⟶ 1,179:
20.iota.map!female.writeln;
20.iota.map!male.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12]
Line 911 ⟶ 1,185:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">int M(int n) => n==0?1:n-F(M(n-1));
int F(int n) => n==0?0:n-M(F(n-1));
 
Line 922 ⟶ 1,196:
print("M: $m");
print("F: $f");
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Hofstadter;
 
Line 954 ⟶ 1,228:
 
end.
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">F n:
if n:
- n M F -- n
Line 970 ⟶ 1,244:
 
for i range 0 10:
!.( M i F i )</langsyntaxhighlight>
{{out}}
<pre>0 1
Line 983 ⟶ 1,257:
6 6
6 6 </pre>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">/* We need to predeclare M if we want F to be able to see it.
* This is done using 'extern', same as if it had been in a
* different compilation unit. */
extern M(byte n) byte;
 
/* Mutually recursive functions */
proc F(byte n) byte:
if n=0 then 1 else n - M(F(n-1)) fi
corp
 
proc M(byte n) byte:
if n=0 then 0 else n - F(M(n-1)) fi
corp
 
/* Show the first 16 values of each */
proc nonrec main() void:
byte i;
write("F:");
for i from 0 upto 15 do write(F(i):2) od;
writeln();
write("M:");
for i from 0 upto 15 do write(M(i):2) od;
writeln()
corp</syntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9</pre>
 
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">func f(n) {
n == 0 ? 1 : n - m(f(n-1))
}
and m(n) {
n == 0 ? 0 : n - f(m(n-1))
}
print( (0..20).Map(i => f(i)).ToArray() )
print( (0..20).Map(i => m(i)).ToArray() )</syntaxhighlight>
 
=={{header|E}}==
Line 990 ⟶ 1,307:
Recursive def:
 
<langsyntaxhighlight lang="e">def [F, M] := [
fn n { if (n <=> 0) { 1 } else { n - M(F(n - 1)) } },
fn n { if (n <=> 0) { 0 } else { n - F(M(n - 1)) } },
]</langsyntaxhighlight>
 
Forward declaration:
 
<langsyntaxhighlight lang="e">def M
def F(n) { return if (n <=> 0) { 1 } else { n - M(F(n - 1)) } }
bind M(n) { return if (n <=> 0) { 0 } else { n - F(M(n - 1)) } }</langsyntaxhighlight>
 
<code>def M</code> binds <var>M</var> to a promise, and stashes the ''resolver'' for that promise where <code>bind</code> can get to it. When <code>def F...</code> is executed, the function F closes over the promise which is the value of M. <code>bind M...</code> uses the resolver to resolve <var>M</var> to the provided definition. The recursive def operates similarly, except that it constructs promises for every variable on the left side (<code>[F, M]</code>), executes the right side (<code>[fn ..., fn ...]</code>) and collects the values, then resolves each promise to its corresponding value.
 
But you don't have to worry about that to use it.
 
=={{header|EasyLang}}==
<syntaxhighlight>
funcdecl M n .
func F n .
if n = 0
return 1
.
return n - M F (n - 1)
.
func M n .
if n = 0
return 0
.
return n - F M (n - 1)
.
for i = 0 to 15
write F i & " "
.
print ""
for i = 0 to 15
write M i & " "
.
</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,054 ⟶ 1,395:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,063 ⟶ 1,404:
=={{header|Elena}}==
{{trans|Smalltalk}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'collections;
Line 1,075 ⟶ 1,416:
var rb := new ArrayList();
for(int i := 0,; i <= 19,; i += 1)
{
ra.append(F(i));
Line 1,083 ⟶ 1,424:
console.printLine(ra.asEnumerable());
console.printLine(rb.asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,091 ⟶ 1,432:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule MutualRecursion do
def f(0), do: 1
def f(n), do: n - m(f(n - 1))
Line 1,099 ⟶ 1,440:
 
IO.inspect Enum.map(0..19, fn n -> MutualRecursion.f(n) end)
IO.inspect Enum.map(0..19, fn n -> MutualRecursion.m(n) end)</langsyntaxhighlight>
 
{{out}}
Line 1,108 ⟶ 1,449:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(mutrec).
-export([mutrec/0, f/1, m/1]).
 
Line 1,120 ⟶ 1,461:
io:format("~n", []),
lists:map(fun(X) -> io:format("~w ", [m(X)]) end, lists:seq(0,19)),
io:format("~n", []).</langsyntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">integer idM, idF
 
function F(integer n)
Line 1,143 ⟶ 1,484:
end function
 
idM = routine_id("M")</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
 
<langsyntaxhighlight lang="fsharp">let rec f n =
match n with
| 0 -> 1
Line 1,154 ⟶ 1,495:
match n with
| 0 -> 0
| _ -> n - (f (m (n-1)))</langsyntaxhighlight>
 
Like OCaml, the <code>let '''rec''' ''f'' .. '''and''' ''m'' ...</code> construct indicates that the functions call themselves (<code>'''rec'''</code>) and each other (<code>'''and'''</code>).
Line 1,160 ⟶ 1,501:
=={{header|Factor}}==
In Factor, if you need a word before it's defined, you have to <code>DEFER:</code> it.
<syntaxhighlight lang="text">DEFER: F
: M ( n -- n' ) dup 0 = [ dup 1 - M F - ] unless ;
: F ( n -- n' ) dup 0 = [ drop 1 ] [ dup 1 - F M - ] if ;</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[$[$1-f;!m;!-1-]?1+]f:
[$[$1-m;!f;!- ]? ]m:
[0[$20\>][\$@$@!." "1+]#%%]t:
f; t;!"
"m; t;!</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,197 ⟶ 1,538:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.01 C--PRINT F(0..15) AND M(0..15)
01.10 T "F(0..15)"
01.20 F X=0,15;S N=X;D 4;T %1,N
01.30 T !"M(0..15)"
01.40 F X=0,15;S N=X;D 5;T %1,N
01.50 T !
01.60 Q
 
04.01 C--N = F(N)
04.10 I (N(D)),4.11,4.2
04.11 S N(D)=1;R
04.20 S D=D+1;S N(D)=N(D-1)-1;D 4;D 5
04.30 S D=D-1;S N(D)=N(D)-N(D+1)
 
05.01 C--N = M(N)
05.10 I (N(D)),5.11,5.2
05.11 R
05.20 S D=D+1;S N(D)=N(D-1)-1;D 5;D 4
05.30 S D=D-1;S N(D)=N(D)-N(D+1)</syntaxhighlight>
 
{{out}}
 
<pre>F(0..15)= 1= 1= 2= 2= 3= 3= 4= 5= 5= 6= 6= 7= 8= 8= 9= 9
M(0..15)= 0= 0= 1= 2= 2= 3= 4= 4= 5= 6= 6= 7= 7= 8= 9= 9</pre>
 
 
=={{header|Forth}}==
Forward references required for mutual recursion may be set up using DEFER.
<langsyntaxhighlight lang="forth">defer m
 
: f ( n -- n )
Line 1,215 ⟶ 1,583:
 
' m defer@ 20 test \ 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12
' f 20 test \ 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,222 ⟶ 1,590:
 
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">module MutualRec
implicit none
contains
Line 1,245 ⟶ 1,613:
end function f
 
end module</langsyntaxhighlight>
 
I've added the attribute <tt>pure</tt> so that we can use them in a <tt>forall</tt> statement.
 
<langsyntaxhighlight lang="fortran">program testmutrec
use MutualRec
implicit none
Line 1,265 ⟶ 1,633:
write(*,'(20I3)') ra
end program testmutrec</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Need forward declaration of M as it's used
Line 1,300 ⟶ 1,668:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,312 ⟶ 1,680:
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Mutual_recursion this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). 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 transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Mutual recursion 01.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
[[File:Fōrmulæ - Mutual recursion 02.png]]
 
[[File:Fōrmulæ - Mutual recursion 03.png]]
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
def fn F( n as long ) as long
def fn M( n as long ) as long
 
local fn F( n as long ) as long
long result
if n == 0 then exit fn = 1
result = n - fn M( fn F( n-1 ) )
end fn = result
 
local fn M( n as long ) as long
long result
if n == 0 then exit fn = 0
result = n - fn F( fn M( n-1 ) )
end fn = result
 
long i, counter
 
counter = 0
for i = 0 to 19
printf @"%3ld\b", fn F( i )
counter++
if counter mod 5 == 0 then print : counter = 0
next
 
print : print
 
counter = 0
for i = 0 to 19
printf @"%3ld\b", fn M( i )
counter++
if counter mod 5 == 0 then print : counter = 0
next
 
NSLog( @"%@", fn WindowPrintViewString( 1 ) )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
1 1 2 2 3
3 4 5 5 6
6 7 8 8 9
9 10 11 11 12
 
 
0 0 1 2 2
3 4 4 5 6
6 7 7 8 9
9 10 11 11 12
</pre>
 
=={{header|Go}}==
It just works. No special pre-declaration is necessary.
<langsyntaxhighlight lang="go">package main
import "fmt"
 
Line 1,342 ⟶ 1,769:
}
fmt.Println()
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def f, m // recursive closures must be declared before they are defined
f = { n -> n == 0 ? 1 : n - m(f(n-1)) }
m = { n -> n == 0 ? 0 : n - f(m(n-1)) }</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">println 'f(0..20): ' + (0..20).collect { f(it) }
println 'm(0..20): ' + (0..20).collect { m(it) }</langsyntaxhighlight>
 
{{out}}
Line 1,360 ⟶ 1,787:
=={{header|Haskell}}==
Haskell's definitions constructs (at the top level, or inside a <code>let</code> or <code>where</code> construct) are always mutually-recursive:
<langsyntaxhighlight lang="haskell">f 0 = 1
f n | n > 0 = n - m (f $ n-1)
 
Line 1,368 ⟶ 1,795:
main = do
print $ map f [0..19]
print $ map m [0..19]</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
every write(F(!arglist)) # F of all arguments
end
Line 1,383 ⟶ 1,810:
if integer(n) >= 0 then
return (0 = n) | n - F(M(n-1))
end</langsyntaxhighlight>
 
=={{header|Idris}}==
<langsyntaxhighlight lang="idris">mutual {
F : Nat -> Nat
F Z = (S Z)
Line 1,394 ⟶ 1,821:
M Z = Z
M (S n) = (S n) `minus` F(M(n))
}</langsyntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight Iolang="io">f := method(n, if( n == 0, 1, n - m(f(n-1))))
m := method(n, if( n == 0, 0, n - f(m(n-1))))
 
Range
0 to(19) map(n,f(n)) println
0 to(19) map(n,m(n)) println</langsyntaxhighlight>
{{out}}
<pre>list(1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12)
Line 1,408 ⟶ 1,835:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">F =: 1:`(- M @ $: @ <:) @.* M."0
M =: 0:`(- F @ $: @ <:) @.* M."0</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> F i. 20
1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12</langsyntaxhighlight>
 
That said, note that numbers are defined recursively, so other some other approaches using numbers which give equivalent results should be acceptable.
 
=={{header|Java}}==
Replace translation (that doesn't compile) with a Java native implementation.
<langsyntaxhighlight lang="java">
import java.util.HashMap;
import java.util.Map;
Line 1,462 ⟶ 1,889:
 
}
</syntaxhighlight>
</lang>
{{out}}
First 20 values of the Female sequence:
Line 1,508 ⟶ 1,935:
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">function f(num) {
return (num === 0) ? 1 : num - m(f(num - 1));
}
Line 1,526 ⟶ 1,953:
//return a new array of the results and join with commas to print
console.log(a.map(function (n) { return f(n); }).join(', '));
console.log(a.map(function (n) { return m(n); }).join(', '));</langsyntaxhighlight>
{{out}}
<pre>1,1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12
Line 1,532 ⟶ 1,959:
 
ES6 implementation
<langsyntaxhighlight JavaScriptlang="javascript">var f = num => (num === 0) ? 1 : num - m(f(num - 1));
var m = num => (num === 0) ? 0 : num - f(m(num - 1));
 
Line 1,545 ⟶ 1,972:
//return a new array of the results and join with commas to print
console.log(a.map(n => f(n)).join(', '));
console.log(a.map(n => m(n)).join(', '));</langsyntaxhighlight>
 
More ES6 implementation
 
<langsyntaxhighlight JavaScriptlang="javascript">var range = (m, n) => Array(... Array(n - m + 1)).map((x, i) => m + i)</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,556 ⟶ 1,983:
 
He we define F and M as arity-0 filters:
<syntaxhighlight lang="jq">
<lang jq>
def M:
def F: if . == 0 then 1 else . - ((. - 1) | F | M) end;
Line 1,562 ⟶ 1,989:
 
def F:
if . == 0 then 1 else . - ((. - 1) | F | M) end;</langsyntaxhighlight>Example:<syntaxhighlight lang ="jq">
[range(0;20) | F],
[range(0;20) | M]</langsyntaxhighlight><syntaxhighlight lang ="sh">$ jq -n -c -f Mutual_recursion.jq
 
[1,1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12]
[0,0,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12]</langsyntaxhighlight>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Mutual recursion, is jsish */
function f(num):number { return (num === 0) ? 1 : num - m(f(num - 1)); }
function m(num):number { return (num === 0) ? 0 : num - f(m(num - 1)); }
Line 1,589 ⟶ 2,016:
0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12, 12
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,600 ⟶ 2,027:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">F(n) = n < 1 ? one(n) : n - M(F(n - 1))
M(n) = n < 1 ? zero(n) : n - F(M(n - 1))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,609 ⟶ 2,036:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun f(n: Int): Int =
Line 1,628 ⟶ 2,055:
for (i in 0..n) print("%3d".format(i))
println()
println("-".repeat(78(n + 2) * 3))
print("F :")
for (i in 0..24n) print("%3d".format(f(i)))
println()
print("M :")
for (i in 0..24n) print("%3d".format(m(i)))
println()
}</langsyntaxhighlight>
 
{{out}}
Line 1,647 ⟶ 2,074:
=={{header|Lambdatalk}}==
 
<langsyntaxhighlight lang="scheme">
{def F {lambda {:n} {if {= :n 0} then 1 else {- :n {M {F {- :n 1}}}} }}}
{def M {lambda {:n} {if {= :n 0} then 0 else {- :n {F {M {- :n 1}}}} }}}
Line 1,655 ⟶ 2,082:
{map M {serie 0 19}}
-> 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12
</syntaxhighlight>
</lang>
 
The naïve version is very slow, {F 80} requires 3800 ms on a recent laptop, so let's memoize:
 
<langsyntaxhighlight lang="scheme">
{def cache
{def cache.F {#.new}}
Line 1,695 ⟶ 2,122:
33 34 34 35 35 36 37 37 38 38 39 40 40 41 42 42 43 43 44 45 45 46 46 47
48 48 49 50 50 51 51 52 53 53 54 55 55 56 56 57 58 58 59 59 60 61 61 62
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print "F sequence."
for i = 0 to 20
Line 1,726 ⟶ 2,153:
end if
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>F sequence.
Line 1,734 ⟶ 2,161:
 
=={{header|LibreOffice Basic}}==
<langsyntaxhighlight LibreOfficelang="libreoffice Basicbasic">'// LibreOffice Basic Implementation of Hofstadter Female-Male sequences
 
'// Utility functions
Line 1,828 ⟶ 2,255:
F(n) = 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13
M(n) = 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
Like Lisp, symbols in Logo are late-bound so no special syntax is required for forward references.
 
<langsyntaxhighlight lang="logo">to m :n
if 0 = :n [output 0]
output :n - f m :n-1
Line 1,845 ⟶ 2,272:
[1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12]
show cascade 20 [lput f #-1 ?] []
[0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12]</langsyntaxhighlight>
 
=={{header|LSL}}==
To test it yourself; rez a box on the ground, and add the following as a New Script.
<langsyntaxhighlight LSLlang="lsl">integer iDEPTH = 100;
integer f(integer n) {
if(n==0) {
Line 1,878 ⟶ 2,305:
llOwnerSay(llList2CSV(llParseString2List(s, [" "], [])));
}
}</langsyntaxhighlight>
{{out}}
<pre>1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12, 13, 13, 14, 14, 15, 16, 16, 17, 17, 18, 19, 19, 20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 37, 37, 38, 38, 39, 40, 40, 41, 42, 42, 43, 43, 44, 45, 45, 46, 46, 47, 48, 48, 49, 50, 50, 51, 51, 52, 53, 53, 54, 55, 55, 56, 56, 57, 58, 58, 59, 59, 60, 61, 61
Line 1,884 ⟶ 2,311:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end</langsyntaxhighlight>
 
It is important to note, that if m and f are to be locally scoped functions rather than global, that they would need to be forward declared:
 
<langsyntaxhighlight lang="lua">
local m,n
function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,903 ⟶ 2,330:
 
Last module export to clipboard and that used for output here.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
\\ set console 70 characters by 40 lines
Form 70, 40
Line 1,981 ⟶ 2,408:
Checkit2
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,990 ⟶ 2,417:
=={{header|M4}}==
 
<langsyntaxhighlight lang="m4">define(`female',`ifelse(0,$1,1,`eval($1 - male(female(decr($1))))')')dnl
define(`male',`ifelse(0,$1,0,`eval($1 - female(male(decr($1))))')')dnl
define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl
loop(0,20,`female')
loop(0,20,`male')</langsyntaxhighlight>
 
=={{header|MAD}}==
Line 2,027 ⟶ 2,454:
or <code>MREC.</code>, which are the actual recursive functions, with a dummy zero argument.
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
R SET UP STACK SPACE
Line 2,083 ⟶ 2,510:
VECTOR VALUES FMT =
0 $2HF(,I2,4H) = ,I2,S8,2HM(,I2,4H) = ,I2*$
END OF PROGRAM</langsyntaxhighlight>
 
{{out}}
Line 2,110 ⟶ 2,537:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">female_seq := proc(n)
if (n = 0) then
return 1;
Line 2,126 ⟶ 2,553:
end proc;
seq(female_seq(i), i=0..10);
seq(male_seq(i), i=0..10);</langsyntaxhighlight>
{{Out|Output}}
<pre>1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6
0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Without caching:
<langsyntaxhighlight Mathematicalang="mathematica">f[0]:=1
m[0]:=0
f[n_]:=n-m[f[n-1]]
m[n_]:=n-f[m[n-1]]</langsyntaxhighlight>
With caching:
<langsyntaxhighlight Mathematicalang="mathematica">f[0]:=1
m[0]:=0
f[n_]:=f[n]=n-m[f[n-1]]
m[n_]:=m[n]=n-f[m[n-1]]</langsyntaxhighlight>
Example finding f(1) to f(30) and m(1) to m(30):
<langsyntaxhighlight Mathematicalang="mathematica">m /@ Range[30]
f /@ Range[30]</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">{0,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12,12,13,14,14,15,16,16,17,17,18,19}
{1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12,13,13,14,14,15,16,16,17,17,18,19}</langsyntaxhighlight>
 
=={{header|MATLAB}}==
female.m:
<langsyntaxhighlight MATLABlang="matlab">function Fn = female(n)
 
if n == 0
Line 2,159 ⟶ 2,586:
Fn = n - male(female(n-1));
end</langsyntaxhighlight>
 
male.m:
<langsyntaxhighlight MATLABlang="matlab">function Mn = male(n)
if n == 0
Line 2,170 ⟶ 2,597:
Mn = n - female(male(n-1));
end</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> n = (0:10);
>> arrayfun(@female,n)
 
Line 2,184 ⟶ 2,611:
ans =
 
0 0 1 2 2 3 4 4 5 6 6</langsyntaxhighlight>
 
=={{header|Maxima}}==
 
<langsyntaxhighlight lang="maxima">f[0]: 1$
m[0]: 0$
f[n] := n - m[f[n - 1]]$
Line 2,210 ⟶ 2,637:
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6]
 
remfunction(f, m)$</langsyntaxhighlight>
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module mutual_recursion.
:- interface.
Line 2,234 ⟶ 2,661:
 
m(N) = ( if N = 0 then 0 else N - f(m(N - 1)) ).
</syntaxhighlight>
</lang>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">f = function(n)
if n > 0 then return n - m(f(n - 1))
return 1
Line 2,248 ⟶ 2,675:
 
print f(12)
print m(12)</langsyntaxhighlight>
{{out}}
<pre>8
7</pre>
 
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
function var int: F(var int:n) =
if n == 0 then
1
else
n - M(F(n - 1))
endif;
function var int: M(var int:n) =
if (n == 0) then
0
else
n - F(M(n - 1))
endif;
</syntaxhighlight>
 
=={{header|MMIX}}==
<langsyntaxhighlight lang="mmix"> LOC Data_Segment
 
GREG @
Line 2,331 ⟶ 2,775:
LDA $255,NL
TRAP 0,Fputs,StdOut
TRAP 0,Halt,0</langsyntaxhighlight>
 
{{out}}
Line 2,338 ⟶ 2,782:
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12 13 14 14 15
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE MutualRecursion;
FROM InOut IMPORT WriteCard, WriteString, WriteLn;
 
TYPE Fn = PROCEDURE(CARDINAL): CARDINAL;
 
PROCEDURE F(n: CARDINAL): CARDINAL;
BEGIN
IF n=0 THEN RETURN 1;
ELSE RETURN n-M(F(n-1));
END;
END F;
 
PROCEDURE M(n: CARDINAL): CARDINAL;
BEGIN
IF n=0 THEN RETURN 0;
ELSE RETURN n-F(M(n-1));
END;
END M;
 
(* Print the first few values of one of the functions *)
PROCEDURE Show(name: ARRAY OF CHAR; fn: Fn);
CONST Max = 15;
VAR i: CARDINAL;
BEGIN
WriteString(name);
WriteString(": ");
FOR i := 0 TO Max DO
WriteCard(fn(i), 0);
WriteString(" ");
END;
WriteLn;
END Show;
 
(* Show the first values of both F and M *)
BEGIN
Show("F", F);
Show("M", M);
END MutualRecursion.</syntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 </pre>
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 2,362 ⟶ 2,848:
foreach (n in [0 .. 20]) Write("{0} ", M(n));
}
}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc m(n: int): int
 
proc f(n: int): int =
if n == 0: 1
else: n - m(f(n-1))
 
proc m(n: int): int =
if n == 0: 0
else: n - f(m(n-1))
Line 2,377 ⟶ 2,863:
for i in 1 .. 10:
echo f(i)
echo m(i)</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{trans|Modula-2}}
<syntaxhighlight lang="oberon2">
MODULE MutualRecursion;
 
IMPORT Out;
 
TYPE
Fn = PROCEDURE(n:INTEGER):INTEGER;
PROCEDURE^ M(n:INTEGER):INTEGER;
PROCEDURE F(n:INTEGER):INTEGER;
BEGIN
IF n=0 THEN RETURN 1
ELSE RETURN n-M(F(n-1))
END;
END F;
 
PROCEDURE M(n:INTEGER):INTEGER;
BEGIN
IF n=0 THEN RETURN 0
ELSE RETURN n-F(M(n-1))
END;
END M;
 
(* Print the first few values of one of the functions *)
PROCEDURE Show(name:ARRAY OF CHAR;fn:Fn);
CONST Max = 15;
VAR i:INTEGER;
BEGIN
Out.String(name);
Out.String(": ");
FOR i := 0 TO Max DO
Out.Int(fn(i),0);
Out.String(" ");
END;
Out.Ln;
END Show;
 
(* Show the first values of both F and M *)
BEGIN
Show("F", F);
Show("M", M);
END MutualRecursion.
</syntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 </pre>
 
=={{header|Objeck}}==
{{trans|C}}
 
<langsyntaxhighlight lang="objeck">
class MutualRecursion {
function : Main(args : String[]) ~ Nil {
Line 2,402 ⟶ 2,938:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
Line 2,408 ⟶ 2,944:
Objective-C has prior declaration rules similar to those stated above for [[Mutual Recursion#C|C]], for C-like types. In this example we show the use of a two class method; this works since we need an <tt>interface</tt> block that is like declaration of functions in C code.
 
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface Hofstadter : NSObject
Line 2,441 ⟶ 2,977:
printf("\n");
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec f = function
| 0 -> 1
| n -> n - m(f(n-1))
Line 2,450 ⟶ 2,986:
| 0 -> 0
| n -> n - f(m(n-1))
;;</langsyntaxhighlight>
 
The <code>let '''rec''' ''f'' ... '''and''' ''m'' ...</code> construct indicates that the functions call themselves (<code>'''rec'''</code>) and each other (<code>'''and'''</code>).
Line 2,459 ⟶ 2,995:
(The code is written to handle vectors, as the testing part shows)
 
<langsyntaxhighlight lang="octave">function r = F(n)
for i = 1:length(n)
if (n(i) == 0)
Line 2,477 ⟶ 3,013:
endif
endfor
endfunction</langsyntaxhighlight>
 
<langsyntaxhighlight lang="octave"># testing
ra = F([0:19]);
rb = M([0:19]);
disp(ra);
disp(rb);</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,489 ⟶ 3,025:
Oforth can declare methods objects without any implementation. This allows to implement mutual recursion. This does not work with functions (declaration and implementation must be together).
 
<langsyntaxhighlight Oforthlang="oforth">Method new: M
 
Integer method: F
Line 2,500 ⟶ 3,036:
 
0 20 seqFrom map(#F) println
0 20 seqFrom map(#M) println</langsyntaxhighlight>
 
{{out}}
Line 2,510 ⟶ 3,046:
=={{header|Ol}}==
The `letrec` indicates that the definitions can be recursive, and fact that we placed these two in the same letrec block makes them mutually recursive.
<langsyntaxhighlight lang="scheme">
(letrec ((F (lambda (n)
(if (= n 0) 1
Line 2,519 ⟶ 3,055:
(print (F 19)))
; produces 12
</syntaxhighlight>
</lang>
 
=={{header|Order}}==
Line 2,525 ⟶ 3,061:
Since Order is powered by the C preprocessor, definitions follow the same rule as CPP macros: they can appear in any order relative to each other as long as all are defined before the ORDER_PP block that calls them.
 
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8f \
Line 2,541 ⟶ 3,077:
//Test
ORDER_PP(8for_each_in_range(8fn(8N, 8print(8f(8N))), 0, 19))
ORDER_PP(8for_each_in_range(8fn(8N, 8print(8m(8N))), 0, 19))</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {F N}
if N == 0 then 1
Line 2,558 ⟶ 3,094:
in
{Show {Map {List.number 0 9 1} F}}
{Show {Map {List.number 0 9 1} M}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">F(n)=if(n,n-M(F(n-1)),1)
M(n)=if(n,n-F(M(n-1)),0)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,568 ⟶ 3,104:
In Pascal we need to pre-declare functions/procedures; to do so, the <tt>forward</tt> statement is used.
 
<langsyntaxhighlight lang="pascal">Program MutualRecursion;
 
{M definition comes after F which uses it}
Line 2,601 ⟶ 3,137:
end;
writeln;
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 }
sub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 }
 
Line 2,610 ⟶ 3,146:
foreach my $sequence (\&F, \&M) {
print join(' ', map $sequence->($_), 0 .. 19), "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,618 ⟶ 3,154:
 
=={{header|Phix}}==
You should normally explicitly declare forward routines since it often makes things easier to understand (strictly necessary only necessary when using optional or named parameters), since it often makes things easier to understand. There would be no point pre-declaring F, since it is not called before it is defined anyway.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>forward function M(integer n)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">forward</span> <span style="color: #008080;">function</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
function F(integer n)
return iff(n?n-M(F(n-1)):1)
<span style="color: #008080;">function</span> <span style="color: #000000;">F</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end function
<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;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">M</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;">1</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function M(integer n)
return iff(n?n-F(M(n-1)):0)
<span style="color: #008080;">function</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end function
<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;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">F</span><span style="color: #0000FF;">(</span><span style="color: #000000;">M</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;">0</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
for i=0 to 20 do
printf(1," %d",F(i))
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">F</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))</span>
printf(1,"\n")
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
for i=0 to 20 do
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
printf(1," %d",M(i))
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
end for</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">M</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;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,644 ⟶ 3,183:
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php"><?php
function F($n)
{
Line 2,666 ⟶ 3,205:
echo implode(" ", $ra) . "\n";
echo implode(" ", $rb) . "\n";
?></langsyntaxhighlight>
 
=={{header|Picat}}==
Here are two approaches, both using tabling. For small values (say N < 50) tabling is not really needed.
===Tabled functions===
<syntaxhighlight lang="picat">table
f(0) = 1.
f(N) = N - m(f(N-1)), N > 0 => true.
 
table
m(0) = 0.
m(N) = N - f(m(N-1)), N > 0 => true.</syntaxhighlight>
 
===Tabled predicates===
{{trans|Prolog}}
<syntaxhighlight lang="picat">table
female(0,1).
female(N,F) :-
N>0,
N1 = N-1,
female(N1,R),
male(R, R1),
F = N-R1.
table
male(0,0).
male(N,F) :-
N>0,
N1 = N-1,
male(N1,R),
female(R, R1),
F = N-R1.</syntaxhighlight>
 
===Test===
<syntaxhighlight lang="picat">go =>
N = 30,
println(func),
test_func(N),
println(pred),
test_pred(N),
nl.
nl.
 
% Testing the function based approach
test_func(N) =>
println([M : I in 0..N, male(I,M)]),
println([F : I in 0..N, female(I,F)]),
nl.
 
% Testing the predicate approach
test_pred(N) =>
println([M : I in 0..N, male(I,M)]),
println([F : I in 0..N, female(I,F)]),
nl.</syntaxhighlight>
{{out}}
<pre>func
[0,0,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12,12,13,14,14,15,16,16,17,17,18,19]
[1,1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12,13,13,14,14,15,16,16,17,17,18,19]
 
pred
[0,0,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12,12,13,14,14,15,16,16,17,17,18,19]
[1,1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12,13,13,14,14,15,16,16,17,17,18,19]</pre>
 
===Larger values===
For larger values, tabling is essential and then one can discern that the predicate based approach is a little faster. Here are the times for testing N=1 000 000:
 
* func: 1.829s
* pred: 1.407s
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de f (N)
(if (=0 N)
1
Line 2,677 ⟶ 3,284:
(if (=0 N)
0
(- N (f (m (dec N)))) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">test: procedure options (main);
 
M: procedure (n) returns (fixed) recursive; /* 8/1/2010 */
Line 2,699 ⟶ 3,306:
put skip list ( F(i), M(i) );
end;
end test;</langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/female{
/n exch def
Line 2,720 ⟶ 3,327:
}ifelse
}def
</syntaxhighlight>
</lang>
 
{{libheader|initlib}}
 
<langsyntaxhighlight lang="postscript">
/F {
{
Line 2,739 ⟶ 3,346:
}.
 
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function F($n) {
if ($n -eq 0) { return 1 }
return $n - (M (F ($n - 1)))
Line 2,750 ⟶ 3,357:
if ($n -eq 0) { return 0 }
return $n - (F (M ($n - 1)))
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">female(0,1).
female(N,F) :- N>0,
N1 is N-1,
Line 2,765 ⟶ 3,372:
male(N1,R),
female(R, R1),
F is N-R1.</langsyntaxhighlight>
 
{{works with|GNU Prolog}}
<langsyntaxhighlight lang="prolog">flist(S) :- for(X, 0, S), female(X, R), format('~d ', [R]), fail.
mlist(S) :- for(X, 0, S), male(X, R), format('~d ', [R]), fail.</langsyntaxhighlight>
 
'''Testing'''
Line 2,783 ⟶ 3,390:
The Pure definitions very closely maps to the mathematical definitions.
 
<langsyntaxhighlight lang="pure">F 0 = 1;
M 0 = 0;
F n = n - M(F(n-1)) if n>0;
M n = n - F(M(n-1)) if n>0;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="pure">> let females = map F (0..10); females;
[1,1,2,2,3,3,4,5,5,6,6]
> let males = map M (0..10); males;
[0,0,1,2,2,3,4,4,5,6,6]</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Declare M(n)
 
Procedure F(n)
Line 2,835 ⟶ 3,442:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12
Line 2,842 ⟶ 3,449:
=={{header|Python}}==
{{works with|Python|3.0}}.<br>{{works with|Python|2.6}}<br>
<langsyntaxhighlight lang="python">def F(n): return 1 if n == 0 else n - M(F(n-1))
def M(n): return 0 if n == 0 else n - F(M(n-1))
 
print ([ F(n) for n in range(20) ])
print ([ M(n) for n in range(20) ])</langsyntaxhighlight>
 
{{out}}
Line 2,856 ⟶ 3,463:
=={{header|Quackery}}==
 
See also [http://rosettacode.org/wiki/Even_or_odd#Quackery:_With_Anonymous_Mutual_Recursion Even or Odd#Quackery: With Anonymous Mutual recursion].
<lang Quackery> forward is f ( n --> n )
 
<syntaxhighlight lang="quackery"> forward is f ( n --> n )
 
[ dup 0 = if done
Line 2,868 ⟶ 3,477:
20 times [ i^ f echo sp ] cr
say "m = "
20 times [ i^ m echo sp ] cr</langsyntaxhighlight>
 
{{out}}
Line 2,876 ⟶ 3,485:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">F <- function(n) ifelse(n == 0, 1, n - M(F(n-1)))
M <- function(n) ifelse(n == 0, 0, n - F(M(n-1)))</langsyntaxhighlight>
 
<langsyntaxhighlight Rlang="r">print.table(lapply(0:19, M))
print.table(lapply(0:19, F))</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (F n)
(if (>= 0 n)
Line 2,892 ⟶ 3,501:
(if (>= 0 n)
0
(- n (F (M (sub1 n))))))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
A direct translation of the definitions of <math>F</math> and <math>M</math>:
<syntaxhighlight lang="raku" perl6line>multi F(0) { 1 }; multi M(0) { 0 }
multi F(\𝑛) { 𝑛 - M(F(𝑛 - 1)) }
multi M(\𝑛) { 𝑛 - F(M(𝑛 - 1)) }
 
say map &F, ^20;
say map &M, ^20;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,910 ⟶ 3,519:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Mutual Recursion"
URL: http://rosettacode.org/wiki/Mutual_Recursion
Line 2,927 ⟶ 3,536:
 
fs: [] ms: [] for i 0 19 1 [append fs f i append ms m i]
print ["F:" mold fs crlf "M:" mold ms]</langsyntaxhighlight>
 
{{out}}
Line 2,933 ⟶ 3,542:
<pre>F: [1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12]
M: [0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12]</pre>
 
=={{header|REFAL}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout 'F: ' <S F 0 14>>
<Prout 'M: ' <S M 0 14>>;
};
 
 
F { 0 = 1; s.N = <- s.N <M <F <- s.N 1>>>>; };
M { 0 = 0; s.N = <- s.N <F <M <- s.N 1>>>>; };
 
S {
s.F s.N s.M, <Compare s.N s.M>: '+' = ;
s.F s.N s.M = <Mu s.F s.N> <S s.F <+ s.N 1> s.M>;
};</syntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9
M: 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9</pre>
 
=={{header|REXX}}==
===vanilla===
This version uses vertical formatting of the output.
<langsyntaxhighlight lang="rexx">/*REXX program shows mutual recursion (via the Hofstadter Male and Female sequences). */
parse arg lim .; if lim='' then lim= 40; w= length(lim); pad= left('', 20)
 
Line 2,946 ⟶ 3,573:
/*──────────────────────────────────────────────────────────────────────────────────────*/
F: procedure; parse arg n; if n==0 then return 1; return n - M( F(n-1) )
M: procedure; parse arg n; if n==0 then return 0; return n - F( M(n-1) )</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 40 </tt>}}
 
Line 2,997 ⟶ 3,624:
This version uses memoization as well as a horizontal (aligned) output format.
<br><br>The optimization due to memoization is faster by many orders of magnitude.
<langsyntaxhighlight lang="rexx">/*REXX program shows mutual recursion (via the Hofstadter Male and Female sequences). */
parse arg lim .; if lim=='' then lim=40 /*assume the default for LIM? */
w= length(lim); $m.=.; $m.0= 0; $f.=.; $f.0= 1; Js=; Fs=; Ms=
Line 3,010 ⟶ 3,637:
/*──────────────────────────────────────────────────────────────────────────────────────*/
F: procedure expose $m. $f.; parse arg n; if $f.n==. then $f.n= n-M(F(n-1)); return $f.n
M: procedure expose $m. $f.; parse arg n; if $m.n==. then $m.n= n-F(M(n-1)); return $m.n</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 99 </tt>}}
<pre>
Line 3,021 ⟶ 3,648:
This version is identical in function to the previous example, but it also can compute and
<br>display a specific request (indicated by a negative number for the argument).
<langsyntaxhighlight lang="rexx">/*REXX program shows mutual recursion (via the Hofstadter Male and Female sequences). */
/*───────────────── If LIM is negative, a single result is shown for the abs(lim) entry.*/
 
Line 3,038 ⟶ 3,665:
/*──────────────────────────────────────────────────────────────────────────────────────*/
F: procedure expose $m. $f.; parse arg n; if $f.n==. then $f.n= n-M(F(n-1)); return $f.n
M: procedure expose $m. $f.; parse arg n; if $m.n==. then $m.n= n-F(M(n-1)); return $m.n</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> -70000 </tt>}}
<pre>
Line 3,053 ⟶ 3,680:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "F sequence : "
for i = 0 to 20
Line 3,073 ⟶ 3,700:
if n != 0 mr = n - f(m(n - 1)) ok
return mr
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
≪ IF DUP THEN DUP 1 - '''FEML MALE''' - ELSE DROP 1 END
≫ ''''FEML'''' STO ( n -- F(n) )
For M(n), here is a little variant, less readable but saving one word !
≪ IF THEN LAST DUP 1 - '''MALE FEML''' - ELSE 0 END
≫ ''''MALE'''' STO ( n -- M(n) )
{{in}}
<pre>
≪ {} 0 20 FOR n n MALE + NEXT ≫ EVAL
≪ {} 0 20 FOR n n FEML + NEXT ≫ EVAL
</pre>
{{out}}
<pre>
2: { 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12 }
1: { 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13 }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def F(n)
n == 0 ? 1 : n - M(F(n-1))
end
Line 3,084 ⟶ 3,728:
 
p (Array.new(20) {|n| F(n) })
p (Array.new(20) {|n| M(n) })</langsyntaxhighlight>
 
{{out}}
Line 3,093 ⟶ 3,737:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">print "F sequence:";
for i = 0 to 20
print f(i);" ";
Line 3,111 ⟶ 3,755:
m = 0
if n <> 0 then m = n - f(m(n - 1))
end function</langsyntaxhighlight>
{{out}}
<pre>F sequence:1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13
Line 3,117 ⟶ 3,761:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn f(n: u32) -> u32 {
match n {
0 => 1,
Line 3,141 ⟶ 3,785:
}
println!("")
}</langsyntaxhighlight>
{{out}}
<pre>1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12
Line 3,147 ⟶ 3,791:
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">% Forward definitions: [also deletes any existing definition]
define f();
define m();
Line 3,168 ⟶ 3,812:
foreach $1 ([0:19])
() = printf("%d ", m($1));
() = printf("\n");</langsyntaxhighlight>
{{out}}
<pre>1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12
Line 3,174 ⟶ 3,818:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
 
f(n:INT):INT
Line 3,199 ⟶ 3,843:
end;
end;
end;</langsyntaxhighlight>
 
There's no need to pre-declare F or M.
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def F(n:Int):Int =
if (n == 0) 1 else n - M(F(n-1))
def M(n:Int):Int =
Line 3,210 ⟶ 3,854:
 
println((0 until 20).map(F).mkString(", "))
println((0 until 20).map(M).mkString(", "))</langsyntaxhighlight>
 
{{out}}
Line 3,218 ⟶ 3,862:
=={{header|Scheme}}==
<code>define</code> declarations are automatically mutually recursive:
<langsyntaxhighlight lang="scheme">(define (F n)
(if (= n 0) 1
(- n (M (F (- n 1))))))
Line 3,224 ⟶ 3,868:
(define (M n)
(if (= n 0) 0
(- n (F (M (- n 1))))))</langsyntaxhighlight>
 
If you wanted to use a <code>let</code>-like construct to create local bindings, you would do the following. The <code>define</code> construct above is just a syntactic sugar for the following where the entire rest of the scope is used as the body.
<langsyntaxhighlight lang="scheme">(letrec ((F (lambda (n)
(if (= n 0) 1
(- n (M (F (- n 1)))))))
Line 3,233 ⟶ 3,877:
(if (= n 0) 0
(- n (F (M (- n 1))))))))
(F 19)) # evaluates to 12</langsyntaxhighlight>
 
The <code>letrec</code> indicates that the definitions can be recursive, and fact that we placed these two in the same <code>letrec</code> block makes them mutually recursive.
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func integer: m (in integer: n) is forward;
Line 3,276 ⟶ 3,920:
end for;
writeln;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,283 ⟶ 3,927:
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program mutual_recursion;
print("F", [f(n) : n in [0..14]]);
print("M", [m(n) : n in [0..14]]);
 
proc f(n);
return {[0,1]}(n) ? n - m(f(n-1));
end proc;
 
proc m(n);
return {[0,0]}(n) ? n - f(m(n-1));
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>F [1 1 2 2 3 3 4 5 5 6 6 7 8 8 9]
M [0 0 1 2 2 3 4 4 5 6 6 7 7 8 9]</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func F(){}
func M(){}
 
Line 3,293 ⟶ 3,954:
[F, M].each { |seq|
{|i| seq.call(i)}.map(^20).join(' ').say
}</langsyntaxhighlight>
{{out}}
<pre>1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12
Line 3,302 ⟶ 3,963:
Using block closure.
 
<langsyntaxhighlight lang="smalltalk">|F M ra rb|
 
F := [ :n |
Line 3,324 ⟶ 3,985:
 
ra displayNl.
rb displayNl.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
 
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('f(n)') :(f_end)
f f = eq(n,0) 1 :s(return)
f = n - m(f(n - 1)) :(return)
Line 3,342 ⟶ 4,003:
i = le(i,25) i + 1 :s(L1)
output = 'M: ' s1; output = 'F: ' s2
end</langsyntaxhighlight>
 
{{out}}
Line 3,350 ⟶ 4,011:
=={{header|SNUSP}}==
The program shown calculates F(3) and demonstrates simple and mutual recursion.
<langsyntaxhighlight SNUSPlang="snusp"> /======\
F==!/=!\?\+# | />-<-\
| \@\-@/@\===?/<#
Line 3,370 ⟶ 4,031:
| | recursion
| n-1
check for zero</langsyntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">f(n)=
? n=0, <= 1
<= n-m(f(n-1))
Line 3,386 ⟶ 4,047:
<
#.output("F:",fs)
#.output("M:",ms)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,394 ⟶ 4,055:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun f 0 = 1
| f n = n - m (f (n-1))
and m 0 = 0
| m n = n - f (m (n-1))
;</langsyntaxhighlight>
 
The <code>'''fun'''</code> construct creates recursive functions, and the <code>'''and'''</code> allows a group of functions to call each other. The above is just a shortcut for the following:
 
<langsyntaxhighlight lang="sml">val rec f = fn 0 => 1
| n => n - m (f (n-1))
and m = fn 0 => 0
| n => n - f (m (n-1))
;</langsyntaxhighlight>
 
which indicates that the functions call themselves (<code>'''rec'''</code>) and each other (<code>'''and'''</code>).
{{out}}
<pre>
> val terms = List.tabulate (10, fn x => x);
val terms = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: int list
> map f terms;
val it = [1, 1, 2, 2, 3, 3, 4, 5, 5, 6]: int list
> map m terms;
val it = [0, 0, 1, 2, 2, 3, 4, 4, 5, 6]: int list
</pre>
 
=={{header|Swift}}==
It just works. No special pre-declaration is necessary.
<langsyntaxhighlight lang="swift">func F(n: Int) -> Int {
return n == 0 ? 1 : n - M(F(n-1))
}
Line 3,427 ⟶ 4,097:
print("\(M(i)) ")
}
println()</langsyntaxhighlight>
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>
F param Fn
if Fn = 0
Line 3,487 ⟶ 4,157:
endif
$s []
</syntaxhighlight>
</lang>
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates male
when <=0> do 0 !
Line 3,504 ⟶ 4,174:
0..10 -> 'M$;: $->male; F$;: $->female;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,521 ⟶ 4,191:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc m {n} {
if { $n == 0 } { expr 0; } else {
expr {$n - [f [m [expr {$n-1}] ]]};
Line 3,541 ⟶ 4,211:
puts -nonewline " ";
}
puts ""</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
<langsyntaxhighlight lang="ti89b">Define F(n) = when(n=0, 1, n - M(F(n - 1)))
Define M(n) = when(n=0, 0, n - F(M(n - 1)))</langsyntaxhighlight>
 
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txrlisp">(defun f (n)
(if (>= 0 n)
1
Line 3,561 ⟶ 4,231:
 
(each ((n (range 0 15)))
(format t "f(~s) = ~s; m(~s) = ~s\n" n (f n) n (m n)))</langsyntaxhighlight>
 
<pre>$ txr mutual-recursion.txr
Line 3,584 ⟶ 4,254:
{{trans|BBC BASIC}}
uBasic/4tH supports mutual recursion. However, the underlying system can't support the stress this puts on the stack - at least not for the full sequence. This version uses [https://en.wikipedia.org/wiki/Memoization memoization] to alleviate the stress and speed up execution.
<syntaxhighlight lang="text">LOCAL(1) ' main uses locals as well
 
FOR a@ = 0 TO 200 ' set the array
Line 3,614 ⟶ 4,284:
IF a@ = 0 THEN RETURN (0) ' memoize the solution
IF @(a@+100) < 0 THEN @(a@+100) = a@ - FUNC(_f(FUNC(_m(a@ - 1))))
RETURN (@(a@+100)) ' return array element</langsyntaxhighlight>
{{out}}
<pre>F sequence:
Line 3,625 ⟶ 4,295:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
<langsyntaxhighlight lang="bash">M()
{
local n
Line 3,656 ⟶ 4,326:
echo -n " "
done
echo</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,670 ⟶ 4,340:
than by mutual recursion, but fixed points are useful for other things as well.)
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
#import sol
Line 3,677 ⟶ 4,347:
 
F = ~&?\1! difference^/~& M+ F+ predecessor
M = ~&?\0! difference^/~& F+ M+ predecessor</langsyntaxhighlight>
This test program applies both functions to the first
twenty natural numbers.
<langsyntaxhighlight Ursalalang="ursala">#cast %nLW
 
test = ^(F*,M*) iota 20</langsyntaxhighlight>
{{out}}
<pre>
Line 3,688 ⟶ 4,358:
<1,1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12>,
<0,0,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12>)</pre>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">int F(int n) {
if (n == 0) return 1;
return n - M(F(n - 1));
}
 
int M(int n) {
if (n == 0) return 0;
return n - F(M(n - 1));
}
 
void main() {
print("n : ");
for (int s = 0; s < 25; s++){
print("%2d ", s);
}
print("\n------------------------------------------------------------------------------\n");
print("F : ");
for (int s = 0; s < 25; s++){
print("%2d ", F(s));
}
print("\nM : ");
for (int s = 0; s < 25; s++){
print("%2d ", M(s));
}
}</syntaxhighlight>
{{out}}
<pre>
n : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
------------------------------------------------------------------------------
F : 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13 13 14 14 15
M : 0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12 13 14 14 15
</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function F(ByVal n As Integer) As Integer
If n = 0 Then
F = 1
Line 3,715 ⟶ 4,419:
Debug.Print M(i);
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre> 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 13
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12 12 </pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var F = Fn.new { |n|
<lang ecmascript>var M // forward declaration
 
var F = Fn.new { |n|
if (n == 0) return 1
return n - M.call(F.call(n-1))
}
 
var M = Fn.new { |n|
if (n == 0) return 0
return n - F.call(M.call(n-1))
Line 3,736 ⟶ 4,438:
System.write("\nM(0..20): ")
(0..20).each { |i| System.write("%(M.call(i)) ") }
System.print()</langsyntaxhighlight>
 
{{out}}
Line 3,749 ⟶ 4,451:
Since all "labels" (symbols), if not ''local'', can be seen by the whole code in the same source unit, we don't need special care to let the subroutine <tt>func_f</tt> call <tt>func_m</tt>. If the function would have been in another source unit, we should have declared it <tt>extern</tt> (the linker will resolve the symbol), as done for <tt>printf</tt>.<br>
(It must be linked with the C standard library <tt>libc</tt> or similar and a startup code; lazyly a <tt>gcc mutrec.o</tt> works, being <tt>mutrec.o</tt> produced by e.g. <tt>nasm -f elf mutrec.asm</tt>)
<langsyntaxhighlight lang="asm"> global main
extern printf
 
Line 3,830 ⟶ 4,532:
db 10,0
 
end</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, IntOut=11;
 
ffunc M; \forward-referenced function declaration
Line 3,850 ⟶ 4,552:
for I:= 0 to 19 do [IntOut(0, M(I)); ChOut(0, ^ )];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,860 ⟶ 4,562:
=={{header|Yabasic}}==
{{trans|AWK}}
<langsyntaxhighlight Yabasiclang="yabasic">// User defined functions
sub F(n)
if n = 0 return 1
Line 3,880 ⟶ 4,582:
print M(i) using "###";
next
print</langsyntaxhighlight>
 
=={{header|zkl}}==
This works if the functions are in a file or on one line (in the REPL) as
zkl doesn't like referencing undefined objects. You could also pass/close the other function.
<langsyntaxhighlight lang="zkl">fcn f(n){ if(n==0)return(1); n-m(f(n-1,m),f) }
fcn m(n){ if(n==0)return(0); n-f(m(n-1,f),m) }
[0..19].apply(f).println(); // or foreach n in ([0..19]){ print(f(n)," ") }
[0..19].apply(m).println(); // or foreach n in ([0..19]){ print(m(n)," ") }</langsyntaxhighlight>
{{out}}
<pre>
2,093

edits