views:

139

answers:

3

Possible Duplicate:
[F#] How to have two methods calling each other?

Hello all,

I Have a scenario where I have two functions that would benefit from being mutually recursive but I'm not really sure how to do this in F#

My scenario is not as simple as the following code, but I'd like to get something similar to compile:

let rec f x =
  if x>0 then
    g (x-1)
  else
    x

let rec g x =
  if x>0 then
    f (x-1)
  else
    x
+2  A: 

To get mutually recursive functions simply pass one to the other as a parameter

let rec f g x =
  if x>0 then
    g (x-1)
  else
    x

let rec g x =
  if x>0 then
    f g (x-1)
  else
    x
JaredPar
+8  A: 

You can also use let rec ... and form:

let rec f x =
  if x>0 then
    g (x-1)
  else
    x

and g x =
  if x>0 then
    f (x-1)
  else
    x
Stringer Bell
Beat me to it by 42 seconds... :-)
Jon Harrop
+1, Nice, didn't realize you could use `and` with let bindings. I thought it's usage was restricted to `type` declarations.
JaredPar
It's specially useful (necessary) if you have mutually recursive types (like two DUs) and two functions that take each as an input argument.
Stringer Bell
+1  A: 

Use the let rec ... and ... construct:

let rec f x =
  if x>0 then
    g (x-1)
  else
    x

and g x =
  if x>0 then
    f (x-1)
  else
    x
Jon Harrop