in javascipt monad ~ read.
Once again monad

Once again monad

What monad isn't like this article describes (update - deleted).

Monad is a design pattern used to describe computations as a series of steps. They are extensively used in pure functional programming languages to manage side effects but can also be used in multiparadigm languages to control complexity.

TL;dr: This guy talks a lot right things:

Short code from Jimmy Breck-McKye post:

function Foo(value) {  
    this.get = ()=> value; = fn => {
        let result = fn(value);
        return new Foo(result);

Its NOT A MONAD. Its a functor. And now you not understand monads.
(Next is not a right explanation of monads).

  1. A monad contains a value
  2. A monad has a method named map that takes a function
  3. Map has some logic around calling that function and processing the result
  4. Map then returns the result in a new monad, so that calls to map can be chained

This is the rules that Jimmy thinks but its not a right. Lets try to understant a simple rules:

  • Monad should have map
  • Monad should have flatMap
  • Monad should have join
  • Monad should have result (return)

What should results of that function be ?

//define a functions
const addOne = (value) => (value + 1);  
const addTwo = (value) => (value + 2);

// lets try to use this, its a map method, and result
new Monad(10)  

But lets be more curious in real life there is no such situations. Lets build more complex "monad".

const pow2 = (value) => (value * value);  
new Monad(10)  
    .map((value) = > {
        return new Monad(value).map(pow2)

Lets use math to make a solution

x = f(10)  
y = x + 1  

Pretty simple right ? But wtf is flatMap ? Its simple.

y === 11 // right ?  

But next one is return a new monad so we cant get simple value.

z = f(y)  

So z is function and we dont know whats value its returning but we know that is monad right?

z = f(y).result(); //that is a result from function  

so z = 121 we now know that. NICE.

and lets finish it with the value from the x

z.result() === 121  

Its pretty simple monad laws. More you can read on wikipedia.

What i think about monads its good idea to manage side effects and we should use it. But dont use it everyware.

PS: Good article about monads in javascript.

comments powered by Disqus