Skip to content

Instantly share code, notes, and snippets.

@robkuz
Last active June 16, 2016 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robkuz/6f44af11e26a9f2043083e21a6e4ea31 to your computer and use it in GitHub Desktop.
Save robkuz/6f44af11e26a9f2043083e21a6e4ea31 to your computer and use it in GitHub Desktop.
Emulating Haskell Type classes in F# and creating a bind (>>=) function

Here is someway to support method overloading with F# and to create a bind function.

first create an inline operator

    let inline (>>=) (f: ^U -> ^T) (t:^T)  = 
        let bind' = (^T : (member bind : (^U -> ^T) -> ^T) (t, f))
        bind'

then implement member functions for bind on those types that should support bind

    type Baz = Baz of int with
        member this.bind (f: 'a -> 'b): 'b = match this with | Baz i ->  f i
    
    type Foo = Foo of string with
        member this.bind (f: 'a -> 'b): 'b = match this with | Foo i ->  f i

finally call the the bind

    let x = (fun x -> (Baz(x+1))) >>= (Baz 1)
    let y = (fun x -> (Foo(x+"!"))) >>= (Foo "yeah")

And the below fails with an compile error

    type FooBar = FooBar of string 
    let y = (fun x -> (FooBar(x+"!"))) >>= (FooBar "yeah")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment