4

I want to add support to my Computation Expression builder for this construct:

let f = 
  foo {
    let! x =
      foo {
        return 1
      }
    and! y =
      foo {
        return 2
      }

    return x + y
  }

The compiler says I must implement either Bind2 or MergeSource. However, I cannot find them in the docs.

What signatures should these have? Can you give a simple example?

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • 1
    Check this out: https://devblogs.microsoft.com/dotnet/announcing-f-5-preview-1/#applicative-computation-expressions – Fyodor Soikin Sep 02 '21 at 17:56
  • 2
    Unfortunately the link to the RFC is dead in the announcement blog; here is the correct address: https://github.com/fsharp/fslang-design/blob/main/FSharp-5.0/FS-1063-support-letbang-andbang-for-applicative-functors.md – Tarmil Sep 02 '21 at 18:16

1 Answers1

3

Here's a simple builder that works with your example:

type Foo<'t> = MkFoo of 't

type FooBuilder() =
    member _.Bind(MkFoo x, f) = f x
    member _.Return(x) = MkFoo x
    member _.MergeSources(MkFoo x, MkFoo y) = MkFoo (x, y)

let foo = FooBuilder()

let f =
    foo {
        let! x = foo { return 1 }
        and! y = foo { return 2 }
        return x + y
    }
printfn "%A" f   // output: MkFoo 3

The purpose of MergeSources is to create a tuple of results that will be automatically de-tupled by the compiler. You might also find this example and this SO question useful.

Brian Berns
  • 15,499
  • 2
  • 30
  • 40