Reputation: 243
Here is Explanation of Monad laws in Haskell.
How do explain Monad laws in F#?
bind (M, return) is equivalent to M.
bind ((return x), f) is equivalent to f x.
bind (bind (m, f),g) is equivalent to bind(m, (fun x -> bind (f x, g))).
Upvotes: 9
Views: 1083
Reputation: 243061
I think that a good way to understand them in F# is to look at what they mean using the computation expression syntax. I'll write m
for some computation builder, but you can imagine that this is async
or any other computation type.
Left identity
m { let! x' = m { return x } = m { let x' = x
return! f x' } return! f x' }
Right identity
m { let! x = comp = m { return! comp }
return x }
Associativity
m { let! x = comp = m { let! y = m { let! x = comp
let! y = f x return! f x }
return! g y } return! g y }
The laws essentially tell you that you should be able to refactor one version of the program to the other without changing the meaning - just like you can refactor ordinary F# programs.
Upvotes: 14