Saturday 13 December 2008

The List Monad in F#

// The List Monad in F#

type ListMonad() =
   member o.Bind(  (m:'a list), (f: 'a -> 'b list) ) = List.concat( List.map (fun x -> f x) m )
   member o.Return(x) = [x]

let list = ListMonad()

let cartesian = list { let! x = [1..3]
                       let! y = [4..6]
                       return (x,y) }

printf "%A" cartesian

1 comment:

Anonymous said...

Thanks! Great post. I could not help but noticing that the bind function can be simplified somewhat:

List.concat( List.map f m )