3 { This is my poor understanding of a monad. I am not actually sure if it's correct lol :D TODO: get back to this. ~drummyfish }
5 Monad is a [mathematical](math.md) concept which has become useful in [functional programming](functional.md) and is one of the very basic [design patterns](design_pattern.md) in this paradigm. A monad basically wraps some [data type](data_type) into an "envelope" type and gives a way to operate with these wrapped data types which greatly simplifies things like error checking or abstracting [input/output](io.md) side effects.
7 A typical example is a **maybe** monad which wraps a type such as integer to handle exceptions such as division by zero. A maybe monad consists of:
9 1. The *maybe(T)* data type where *T* is some other data type, e.g. *maybe(int)*. Type *maybe(T)* can have these values:
10 - *just(X)* where *X* is any possible value of *T* (for int: -1, 0, 1, 2, ...), or
11 - *nothing*, a special value that says no value is present
12 2. A special function *return(X)* that converts value of given type into this maybe type, e.g. *return(3)* will return *just(3)*
13 3. A special combinator *X >>= f* which takes a monadic (*maybe*) values *X* and a function *f* and does the following:
14 - if *X* is *nothing*, gives back *nothing*
15 - if *X* is a value *just(N)*, gives back the value *f(N)* (i.e. unwraps the value and hand it over to the function)
17 Let's look at a pseudocode example of writing a safe division function. Without using the combinator it's kind of ugly:
20 divSafe(x,y) = // takes two maybe values, returns a maybe value
30 With the combinator it gets much nicer (note the use of [lambda expression](lambda.md)):
34 x >>= { a: y >== { b: if b == 0 nothing else a / b } }
37 Languages will typicall make this even nicer with a [syntax sugar](syntax_sugar.md) such as:
43 if y == 0 nothing else return(a / b)
48 TODO: example in real lang, e.g. haskell