Mutual recursion: Difference between revisions

Add ABC
(Add Draco)
(Add ABC)
 
(24 intermediate revisions by 18 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}}
<langsyntaxhighlight lang="apl">f ← {⍵=0:1 ⋄ ⍵-m∇⍵-1}
m ← {⍵=0:0 ⋄ ⍵-f∇⍵-1}
⍉'nFM'⍪↑(⊢,f,m)¨0,⍳20</langsyntaxhighlight>
{{out}}
<pre>n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Line 348 ⟶ 368:
=={{header|AppleScript}}==
 
<langsyntaxhighlight AppleScriptlang="applescript">-- f :: Int -> Int
on f(x)
if x = 0 then
Line 413 ⟶ 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|ARM Assembly}}==
Line 441 ⟶ 461:
the link register must be saved by hand (as the code below shows several ways of doing).
 
<syntaxhighlight lang="text">.text
.global _start
@@@ Implementation of F(n), n in R0. n is considered unsigned.
Line 506 ⟶ 526:
dstr: .ascii "\2"
dgt: .ascii "* "
nl: .ascii "\1\n"</langsyntaxhighlight>
 
{{out}}
Line 514 ⟶ 534:
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">f: $[n][ if? n=0 -> 1 else -> n-m f n-1 ]
m: $[n][ if? n=0 -> 0 else -> n-f m n-1 ]
Line 521 ⟶ 541:
print ["m(" i ")=" m i]
print ""
]</langsyntaxhighlight>
 
{{out}}
Line 589 ⟶ 609:
 
=={{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 599 ⟶ 619:
M(n) {
Return n ? n - F(M(n-1)) : 0
}</langsyntaxhighlight>
 
{{trans|C}}
Line 605 ⟶ 625:
This one is an alternative to the above.
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">main()
Return
 
Line 635 ⟶ 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 659 ⟶ 679:
}
print ""
}</langsyntaxhighlight>
 
{{out}}
Line 669 ⟶ 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 689 ⟶ 709:
PRINT M(i) FORMAT "%2d "
NEXT
PRINT</langsyntaxhighlight>
 
{{out}}
Line 698 ⟶ 718:
=={{header|BASIC}}==
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic">DECLARE FUNCTION f! (n!)
DECLARE FUNCTION m! (n!)
 
Line 715 ⟶ 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 733 ⟶ 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 743 ⟶ 763:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Hofstad.bas"
110 PRINT "F sequence:"
120 FOR I=0 TO 20
Line 765 ⟶ 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 778 ⟶ 820:
if ( n == 0 ) return(0);
return(n - f(m(n-1)));
}</langsyntaxhighlight>
 
{{works with|GNU bc}}
Line 784 ⟶ 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 793 ⟶ 835:
}
print "\n";
quit</langsyntaxhighlight>
 
{{out}}
Line 807 ⟶ 849:
 
=={{header|BCPL}}==
<langsyntaxhighlight BCPLlang="bcpl">get "libhdr"
 
// Mutually recursive functions
Line 826 ⟶ 868:
$)
writes("*N")
$)</langsyntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
Line 832 ⟶ 874:
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">F ← {0:1; 𝕩-M F𝕩-1}
M ← {0:0; 𝕩-F M𝕩-1}
⍉"FM"∾>(F∾M)¨↕15</langsyntaxhighlight>
{{out}}
<pre>┌─
Line 842 ⟶ 884:
 
=={{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 849 ⟶ 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 867 ⟶ 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 873 ⟶ 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 902 ⟶ 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 925 ⟶ 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 964 ⟶ 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 970 ⟶ 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 987 ⟶ 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 1,004 ⟶ 1,069:
printAll((0:20).map(f));
printAll((0:20).map(m));
}</langsyntaxhighlight>
 
{{out}}
Line 1,014 ⟶ 1,079:
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">(declare F) ; forward reference
 
(defn M [n]
Line 1,024 ⟶ 1,089:
(if (zero? n)
1
(- n (M (F (dec n))))))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">
<lang clu>% At the top level, definitions can only see the definitions above.
% To declare things you can either write an .spc file or you can use
% But if we put F and M in a cluster, they can see each other.
% the clu file itself as a specfile. For a small program a common
mutrec = cluster is F, M
% idiom is to spec and compile the same source file:
rep = null
%
% pclu -spec mutrec.clu -clu mutrec.clu
F = proc (n: int) returns (int)
%
if n=0 then return(1)
start_up = proc ()
else return(n - M(F(n-1)))
print_first_16("F", F)
end
print_first_16("M", M)
end F
end start_up
 
M = proc (n: int) returns (int)
if n=0 then return(0)
else return(n - F(M(n-1)))
end
end M
end mutrec
 
% If we absolutely _must_ have them defined at the top level,
% we can then just take them out of the cluster.
F = mutrec$F
M = mutrec$M
 
% Print the first few values for F and M
Line 1,054 ⟶ 1,108:
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
 
start_upF = proc (n: int) returns (int)
if n = 0 then
print_first_16("F", F)
return (1)
print_first_16("M", M)
else
end start_up</lang>
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
Line 1,069 ⟶ 1,135:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
F = (n) ->
if n is 0 then 1 else n - M F n - 1
Line 1,078 ⟶ 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 1,097 ⟶ 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 1,113 ⟶ 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 1,119 ⟶ 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 1,130 ⟶ 1,196:
print("M: $m");
print("F: $f");
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
unit Hofstadter;
 
Line 1,162 ⟶ 1,228:
 
end.
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">F n:
if n:
- n M F -- n
Line 1,178 ⟶ 1,244:
 
for i range 0 10:
!.( M i F i )</langsyntaxhighlight>
{{out}}
<pre>0 1
Line 1,193 ⟶ 1,259:
 
=={{header|Draco}}==
<langsyntaxhighlight 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. */
Line 1,218 ⟶ 1,284:
for i from 0 upto 15 do write(M(i):2) od;
writeln()
corp</langsyntaxhighlight>
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
Line 1,225 ⟶ 1,291:
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func f(n) {
n == 0 ? 1 : n - m(f(n-1))
}
Line 1,231 ⟶ 1,297:
n == 0 ? 0 : n - f(m(n-1))
}
 
print( (0..20).mapMap(i => f(i)).toArrayToArray() )
print( (0..20).mapMap(i => m(i)).toArrayToArray() )</langsyntaxhighlight>
 
=={{header|E}}==
Line 1,241 ⟶ 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,305 ⟶ 1,395:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,314 ⟶ 1,404:
=={{header|Elena}}==
{{trans|Smalltalk}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'collections;
Line 1,326 ⟶ 1,416:
var rb := new ArrayList();
for(int i := 0,; i <= 19,; i += 1)
{
ra.append(F(i));
Line 1,334 ⟶ 1,424:
console.printLine(ra.asEnumerable());
console.printLine(rb.asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,342 ⟶ 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,350 ⟶ 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,359 ⟶ 1,449:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(mutrec).
-export([mutrec/0, f/1, m/1]).
 
Line 1,371 ⟶ 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,394 ⟶ 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,405 ⟶ 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,411 ⟶ 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,448 ⟶ 1,538:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FOCAL}}==
<langsyntaxhighlight FOCALlang="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
Line 1,469 ⟶ 1,559:
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)</langsyntaxhighlight>
 
{{out}}
Line 1,479 ⟶ 1,569:
=={{header|Forth}}==
Forward references required for mutual recursion may be set up using DEFER.
<langsyntaxhighlight lang="forth">defer m
 
: f ( n -- n )
Line 1,493 ⟶ 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,500 ⟶ 1,590:
 
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">module MutualRec
implicit none
contains
Line 1,523 ⟶ 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,543 ⟶ 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,578 ⟶ 1,668:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,590 ⟶ 1,680:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Mutual_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.
 
[[File:Fōrmulæ - Mutual recursion 01.png]]
In '''[https://formulae.org/?example=Mutual_recursion this]''' page you can see the program(s) related to this task and their results.
 
[[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,620 ⟶ 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,638 ⟶ 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,646 ⟶ 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,661 ⟶ 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,672 ⟶ 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,686 ⟶ 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,740 ⟶ 1,889:
 
}
</syntaxhighlight>
</lang>
{{out}}
First 20 values of the Female sequence:
Line 1,786 ⟶ 1,935:
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">function f(num) {
return (num === 0) ? 1 : num - m(f(num - 1));
}
Line 1,804 ⟶ 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,810 ⟶ 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,823 ⟶ 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,834 ⟶ 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,840 ⟶ 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,867 ⟶ 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,878 ⟶ 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,887 ⟶ 2,036:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun f(n: Int): Int =
Line 1,906 ⟶ 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,925 ⟶ 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,933 ⟶ 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,973 ⟶ 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 2,004 ⟶ 2,153:
end if
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>F sequence.
Line 2,012 ⟶ 2,161:
 
=={{header|LibreOffice Basic}}==
<langsyntaxhighlight LibreOfficelang="libreoffice Basicbasic">'// LibreOffice Basic Implementation of Hofstadter Female-Male sequences
 
'// Utility functions
Line 2,106 ⟶ 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 2,123 ⟶ 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 2,156 ⟶ 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 2,162 ⟶ 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 2,181 ⟶ 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 2,259 ⟶ 2,408:
Checkit2
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,268 ⟶ 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,305 ⟶ 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,361 ⟶ 2,510:
VECTOR VALUES FMT =
0 $2HF(,I2,4H) = ,I2,S8,2HM(,I2,4H) = ,I2*$
END OF PROGRAM</langsyntaxhighlight>
 
{{out}}
Line 2,388 ⟶ 2,537:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">female_seq := proc(n)
if (n = 0) then
return 1;
Line 2,404 ⟶ 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
Line 2,411 ⟶ 2,560:
=={{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,437 ⟶ 2,586:
Fn = n - male(female(n-1));
end</langsyntaxhighlight>
 
male.m:
<langsyntaxhighlight MATLABlang="matlab">function Mn = male(n)
if n == 0
Line 2,448 ⟶ 2,597:
Mn = n - female(male(n-1));
end</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> n = (0:10);
>> arrayfun(@female,n)
 
Line 2,462 ⟶ 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,488 ⟶ 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,512 ⟶ 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,526 ⟶ 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,609 ⟶ 2,775:
LDA $255,NL
TRAP 0,Fputs,StdOut
TRAP 0,Halt,0</langsyntaxhighlight>
 
{{out}}
Line 2,617 ⟶ 2,783:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE MutualRecursion;
FROM InOut IMPORT WriteCard, WriteString, WriteLn;
 
Line 2,654 ⟶ 2,820:
Show("F", F);
Show("M", M);
END MutualRecursion.</langsyntaxhighlight>
{{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,682 ⟶ 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 =
Line 2,697 ⟶ 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,722 ⟶ 2,938:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
Line 2,728 ⟶ 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,761 ⟶ 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,770 ⟶ 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,779 ⟶ 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,797 ⟶ 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,809 ⟶ 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,820 ⟶ 3,036:
 
0 20 seqFrom map(#F) println
0 20 seqFrom map(#M) println</langsyntaxhighlight>
 
{{out}}
Line 2,830 ⟶ 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,839 ⟶ 3,055:
(print (F 19)))
; produces 12
</syntaxhighlight>
</lang>
 
=={{header|Order}}==
Line 2,845 ⟶ 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,861 ⟶ 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,878 ⟶ 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,888 ⟶ 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,921 ⟶ 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,930 ⟶ 3,146:
foreach my $sequence (\&F, \&M) {
print join(' ', map $sequence->($_), 0 .. 19), "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,938 ⟶ 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,964 ⟶ 3,183:
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php"><?php
function F($n)
{
Line 2,986 ⟶ 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,997 ⟶ 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 3,019 ⟶ 3,306:
put skip list ( F(i), M(i) );
end;
end test;</langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/female{
/n exch def
Line 3,040 ⟶ 3,327:
}ifelse
}def
</syntaxhighlight>
</lang>
 
{{libheader|initlib}}
 
<langsyntaxhighlight lang="postscript">
/F {
{
Line 3,059 ⟶ 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 3,070 ⟶ 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 3,085 ⟶ 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 3,103 ⟶ 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 3,155 ⟶ 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 3,162 ⟶ 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 3,178 ⟶ 3,465:
See also [http://rosettacode.org/wiki/Even_or_odd#Quackery:_With_Anonymous_Mutual_Recursion Even or Odd#Quackery: With Anonymous Mutual recursion].
 
<langsyntaxhighlight Quackerylang="quackery"> forward is f ( n --> n )
 
[ dup 0 = if done
Line 3,190 ⟶ 3,477:
20 times [ i^ f echo sp ] cr
say "m = "
20 times [ i^ m echo sp ] cr</langsyntaxhighlight>
 
{{out}}
Line 3,198 ⟶ 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 3,214 ⟶ 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 3,232 ⟶ 3,519:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Mutual Recursion"
URL: http://rosettacode.org/wiki/Mutual_Recursion
Line 3,249 ⟶ 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 3,255 ⟶ 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 3,268 ⟶ 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 3,319 ⟶ 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,332 ⟶ 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,343 ⟶ 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,360 ⟶ 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,375 ⟶ 3,680:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "F sequence : "
for i = 0 to 20
Line 3,395 ⟶ 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,406 ⟶ 3,728:
 
p (Array.new(20) {|n| F(n) })
p (Array.new(20) {|n| M(n) })</langsyntaxhighlight>
 
{{out}}
Line 3,415 ⟶ 3,737:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">print "F sequence:";
for i = 0 to 20
print f(i);" ";
Line 3,433 ⟶ 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,439 ⟶ 3,761:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn f(n: u32) -> u32 {
match n {
0 => 1,
Line 3,463 ⟶ 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,469 ⟶ 3,791:
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">% Forward definitions: [also deletes any existing definition]
define f();
define m();
Line 3,490 ⟶ 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,496 ⟶ 3,818:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
 
f(n:INT):INT
Line 3,521 ⟶ 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,532 ⟶ 3,854:
 
println((0 until 20).map(F).mkString(", "))
println((0 until 20).map(M).mkString(", "))</langsyntaxhighlight>
 
{{out}}
Line 3,540 ⟶ 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,546 ⟶ 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,555 ⟶ 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,598 ⟶ 3,920:
end for;
writeln;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,605 ⟶ 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,615 ⟶ 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,624 ⟶ 3,963:
Using block closure.
 
<langsyntaxhighlight lang="smalltalk">|F M ra rb|
 
F := [ :n |
Line 3,646 ⟶ 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,664 ⟶ 4,003:
i = le(i,25) i + 1 :s(L1)
output = 'M: ' s1; output = 'F: ' s2
end</langsyntaxhighlight>
 
{{out}}
Line 3,672 ⟶ 4,011:
=={{header|SNUSP}}==
The program shown calculates F(3) and demonstrates simple and mutual recursion.
<langsyntaxhighlight SNUSPlang="snusp"> /======\
F==!/=!\?\+# | />-<-\
| \@\-@/@\===?/<#
Line 3,692 ⟶ 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,708 ⟶ 4,047:
<
#.output("F:",fs)
#.output("M:",ms)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,716 ⟶ 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>).
Line 3,743 ⟶ 4,082:
=={{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,758 ⟶ 4,097:
print("\(M(i)) ")
}
println()</langsyntaxhighlight>
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>
F param Fn
if Fn = 0
Line 3,818 ⟶ 4,157:
endif
$s []
</syntaxhighlight>
</lang>
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates male
when <=0> do 0 !
Line 3,835 ⟶ 4,174:
0..10 -> 'M$;: $->male; F$;: $->female;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,852 ⟶ 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,872 ⟶ 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,892 ⟶ 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,915 ⟶ 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,945 ⟶ 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,956 ⟶ 4,295:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
<langsyntaxhighlight lang="bash">M()
{
local n
Line 3,987 ⟶ 4,326:
echo -n " "
done
echo</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 4,001 ⟶ 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 4,008 ⟶ 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 4,021 ⟶ 4,360:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">int F(int n) {
if (n == 0) return 1;
return n - M(F(n - 1));
Line 4,045 ⟶ 4,384:
print("%2d ", M(s));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,055 ⟶ 4,394:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function F(ByVal n As Integer) As Integer
If n = 0 Then
F = 1
Line 4,080 ⟶ 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 4,101 ⟶ 4,438:
System.write("\nM(0..20): ")
(0..20).each { |i| System.write("%(M.call(i)) ") }
System.print()</langsyntaxhighlight>
 
{{out}}
Line 4,114 ⟶ 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 4,195 ⟶ 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 4,215 ⟶ 4,552:
for I:= 0 to 19 do [IntOut(0, M(I)); ChOut(0, ^ )];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 4,225 ⟶ 4,562:
=={{header|Yabasic}}==
{{trans|AWK}}
<langsyntaxhighlight Yabasiclang="yabasic">// User defined functions
sub F(n)
if n = 0 return 1
Line 4,245 ⟶ 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