Mutual recursion: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
(→‎{{header|CLU}}: Correct and clarify the Clu example. No special tricks are needed for mutual recursion, it's standard practice to "spec" the clu file before compiling it.)
Line 1,049: Line 1,049:


=={{header|CLU}}==
=={{header|CLU}}==
<syntaxhighlight lang="clu">% At the top level, definitions can only see the definitions above.
<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
% But if we put F and M in a cluster, they can see each other.
% idiom is to spec and compile the same source file:
mutrec = cluster is F, M
%
rep = null
% pclu -spec mutrec.clu -clu mutrec.clu
%
F = proc (n: int) returns (int)
start_up = proc ()
if n=0 then return(1)
else return(n - M(F(n-1)))
print_first_16("F", F)
print_first_16("M", M)
end
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
% Print the first few values for F and M
Line 1,076: Line 1,064:
po: stream := stream$primary_output()
po: stream := stream$primary_output()
stream$puts(po, name || ":")
stream$puts(po, name || ":")
for i: int in int$from_to(0,15) do
for i: int in int$from_to(0, 15) do
stream$puts(po, " " || int$unparse(fn(i)))
stream$puts(po, " " || int$unparse(fn(i)))
end
end
stream$putl(po, "")
stream$putl(po, "")
end print_first_16
end print_first_16


start_up = proc ()
F = 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</syntaxhighlight>
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}}
{{out}}
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
<pre>F: 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9