12

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
Community
  • 1
  • 1
rysama
  • 1,674
  • 16
  • 28

3 Answers3

29

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
elmattic
  • 12,046
  • 5
  • 43
  • 79
  • 1
    Beat me to it by 42 seconds... :-) – J D Sep 01 '10 at 18:56
  • 1
    +1, Nice, didn't realize you could use `and` with let bindings. I thought it's usage was restricted to `type` declarations. – JaredPar Sep 01 '10 at 19:02
  • It's specially useful (necessary) if you have mutually recursive types (like two DUs) and two functions that take each as an input argument. – elmattic Sep 01 '10 at 19:11
2

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
  • 733,204
  • 149
  • 1,241
  • 1,454
2

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
J D
  • 48,105
  • 13
  • 171
  • 274