Saturday, December 8, 2012

Mutual Recursion in F#

(In learning from "Programming F# 3.0, 2nd Edition")

F# can do "Mutual recursion" by using two reserved words - rec and and. The most famous mutual recursion is "tarai and laziest tarai" case in here. In F#, :
module MutualRecursion =
  let rec laziestTarai x y z'x z'y z'z =
    if y < x then
      laziestTarai
        (tarai (x-1) y (tarai z'x z'y z'z))
        (tarai (y-1) (tarai z'x z'y z'z) x)
        ((tarai z'x z'y z'z)-1)
        x
        y
    else y
  and tarai x y z =
    if y < x then
      laziestTarai
        (tarai (x-1) y z)
        (tarai (y-1) z x)
        (z-1)
        x
        y
    else y
> MutualRecursion.tarai 100 50 0;;
val it : int = 100

(see also : phosphorescence: Refactored Mutual Recursion in F#)

No comments:

Post a Comment