A Monad is something that supports flatMap.
Examples: Option
, List
, Future
flatMap
is the same as >>=
in Haskell.
- http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
- https://typelevel.org/cats/typeclasses/functor.html
An expression is referentially transparent if it can be replaced with its corresponding value without changing the program's behavior.
Example (source):
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
Advantages:
-
Easier to reason about code
-
Less error-prone refactoring possible
-
Compiler optimizations like "Common subexpression elimination"
Every expression which is not referentially transparent has side-effects.
A pure function is referentially transparent.
An IO-Monad is an anonymous function with side-effects that can be used like a Monad.
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.