Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom computation expressions in F#

I've been toying with monads in F# (aka computation expressions) and I wrote this simple Identity monad:

type Identity<'a> = 
    | Identity of 'a

type IdentityBuilder() =
    member x.Bind (Identity v) f  = f(v)
    member x.Return v = Identity v
let identity = new IdentityBuilder()

let getInt() = identity { return Int32.Parse(Console.ReadLine()) }

let calcs() = identity {
    let! a = getInt()    // <- I get an error here
    let! b = getInt()
    return a + b }

I don't understand the error I'm getting in the marked line:

This expression was expected to have type Identity<'a> but here has type 'b * 'c

I think this makes no sense as getInt() is clearly a value of type Identity<'a>.

Can anyone tell me what am I doing wrong?

like image 237
R. Martinho Fernandes Avatar asked Dec 16 '09 20:12

R. Martinho Fernandes


2 Answers

The computation expression syntax wants Bind to have a tupled, not curried argument. So

member x.Bind((Identity v), f) = f(v)

See this article for all signatures.

like image 78
Dario Avatar answered Nov 20 '22 02:11

Dario


The problem is the type of your Bind function - it shouldn't take curried arguments. If you change it to:

member x.Bind (Identity v, f)  = f(v)

then it should work.

like image 30
kvb Avatar answered Nov 20 '22 02:11

kvb