What is a Monad?
A Monad is something that supports flatMap.
flatMap is the same as
>>= in Haskell.
What is referential transparency?
An expression is referentially transparent if it can be replaced with its corresponding value without changing the program's behavior.
var x = 1; x + x
Has the same result as:
1 + 1
And vice versa.
A counter example is:
var x = prompt("Name:"); x + x
Does not have the same result as:
prompt("Name:") + prompt("Name:")
Not referentially transparent:
- Functions with I/O operations, like console print, file- and networking-operations
- Factories which produce mutable objects
Easier to reason about code
Less error-prone refactoring possible
Compiler optimizations like "Common subexpression elimination"
What is a side-effect?
Every expression which is not referentially transparent has side-effects.
What is a pure function?
A pure function is referentially transparent.
What is an IO-Monad?
An IO-Monad is an anonymous function with side-effects that can be used like a Monad.
How can I program side-effects with only pure functions?
Side-effects are not avoided, but executed as late as possible ("at the end of the World/Universe").
For example: Haskell's main function returns an IO-Monad wich contains all desired side-effects.
Strategy: Compose the side-effects as IO-Monads using pure functions and execute them as late as possible.