Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutual recursion with computation expressions

Tags:

f#

Currently I have the following structure:

let rec foo x = State.state{
    let rec bar =
        //...
        foo 5
        //...
    //...
    bar
    //...
}

I would like to extract the 'bar' function and obtain a structure such as:

let rec foo x = State.state{
    //...
    bar
    //...
}
and bar =  State.state{
    //...
    foo 5
    //...
}

This would allow me to have another function foo2 that could also use bar and avoid code duplication.

The question is: my proposal does not compile in F# and apparently that is because of the State context. So what is the syntactically correct way to reach the desired code structure?

like image 660
Friedrich Gretz Avatar asked Mar 22 '26 23:03

Friedrich Gretz


1 Answers

This works fine for me:

let rec foo x = 
  async {
    return! bar x
  }
and bar x = 
  async {
    if x = 0
      then printfn "bar"
      else do! foo (x - 1) 
  }
Async.RunSynchronously (foo 10)

I had problems with the formatting first so make sure your indentations are correct and that your exclamation marks are at the right place, otherwise the type won't work out.

like image 61
erdeszt Avatar answered Mar 25 '26 20:03

erdeszt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!