Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of Monad laws in F#

Tags:

monads

f#

Here is Explanation of Monad laws in Haskell.

How do explain Monad laws in F#?

  1. bind (M, return) is equivalent to M.

  2. bind ((return x), f) is equivalent to f x.

  3. bind (bind (m, f),g) is equivalent to bind(m, (fun x -> bind (f x, g))).

like image 485
dagelee Avatar asked Sep 02 '13 09:09

dagelee


People also ask

What are the monad laws?

A proper monad must satisfy the three monad laws: left identity, right identity, and associativity. Together, left identity and right identity are know as simply identity.

What the F is a monad?

This is, in essence, what a monad is: a structure that lets you map a function into the structure which may, as a side-effect, change the structure. Different monads allow for different side-effects.

What is a monad in simple terms?

A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.

What is a monad example?

Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it. For example, you can create a type to wrap another one, in Haskell: data Wrapped a = Wrap a. To wrap stuff we define return :: a -> Wrapped a return x = Wrap x.


1 Answers

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.

like image 167
Tomas Petricek Avatar answered Nov 06 '22 05:11

Tomas Petricek