F#: Mutually recursive functions [duplicate]
Asked Answered
T

3

13

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
Theall answered 1/9, 2010 at 18:30 Comment(3)
See also https://mcmap.net/q/430846/-f-forward-type-declarationsTusk
I hesitate to mark this one as the duplicate, because the title is probably better...Jimmyjimsonweed
@Benjol: Generally we don not delete duplicates with substantially different titles in order to improve searchability, but we still close them.Phototype
B
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
Brynne answered 1/9, 2010 at 18:53 Comment(3)
Beat me to it by 42 seconds... :-)Israel
+1, Nice, didn't realize you could use and with let bindings. I thought it's usage was restricted to type declarations.Padlock
It's specially useful (necessary) if you have mutually recursive types (like two DUs) and two functions that take each as an input argument.Brynne
P
3

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
Padlock answered 1/9, 2010 at 18:44 Comment(0)
I
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
Israel answered 1/9, 2010 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.