I would like to know if there is a non-artificial example, where mutual recursion is the most elegant solution to a problem and it cannot be easily reduced/inlined to a single recursive function.
I already know this example (from Wikipedia)
function even?(number : Integer)
if number == 0 then
return true
else
return odd?(abs(number)-1)
function odd?(number : Integer)
if number == 0 then
return false
else
return even?(abs(number)-1)
But seriously, no one in their right mind would check the number's parity this way.
I checked the previous answer on this topic here on SO - Are there any example of Mutual recursion? but none of the answers are what I am looking for.
I know it can be useful in recursive parsing - probably the only logical way to implement it, but I need a cleaner, more specific example (preferably a mathematical one).
Thank you for help?
Edit:
Since apparently every tuple of mutually-recursive functions CAN be reduced to a single functions, I would rather want to know if there is a case where use of mutually recursive functions is the best/most readable way.
f
,g
,h
. Define an enum Fun with the valuesF
,G
, andH
. Define a function fgh whose parameters aretype
of typeFun
followed by a union off
's,g
's andh
's parameters and whose body has the formif(type == F) { fs body} else if (type==G) { gs body} etc.
. Replace each occurrence off
in the body withfgh(F, arg1, arg2, null, null)
, each occurrence ofg
withfgh(G, null, null, arg, null)
and each occurrence ofh
withfgh(H, null, null, null, arg)
. Done. – Devonne