Mutual recursion in F#

One of the annoyances of F#, well it is when you come from C# (or the likes), is that to use a function or type, the function or type needs to have been declared before it’s used. Obviously this is a problem if a type references another type which itself references the first type – but ofcourse they F# guys have a way to handle this and it’s called mutual type recursion.

Let’s look at an example of what I’m talking about and at the solution

[<Measure>
type g = 
   static member toKilograms value : float<g> = value / 1000.0<g/kg>
and [<Measure> kg = 
   static member toGrams value : float<kg> = value * 1000.0<g/kg>

The above is taken from my previous post on units of measure.

So in the above code we have type g returning a unit of measure type kg and type kg returns a unit of measure type g. Obviously g cannot use kg as it’s not declared before type g, but it can in the above example by using the and keyword. This can be thought of, as telling the compiler to wait until it’s read all the “chained” types in before evaluating them.

The same technique is used for creating recursive functions which might call other functions which might call the previous function, i.e. circular function calls.

Here’s some code taken from Microsoft’s MSDN site (referenced below) as this is a better example than any I’ve come up with to demonstrate this

let rec Even x =
   if x = 0 then true 
   else Odd (x - 1)
and Odd x =
   if x = 1 then true 
   else Even (x - 1)

So in this code we can see that the function Even is marked as rec so it’s recursive, it may call the function Odd which in turn may call function Even. Again we chain these functions together using the and keyword.

References

Mutually Recursive Functions
Mutually Recursive Types