Quick actions

cmd+k|ctrl+k

Navigation

Languages

PromiseReader Monad

Snippet info

Language

JavaScript

Visibility

public

Author

homam

Created

2016-06-14T15:48:35Z

Updated

2016-06-14T15:48:35Z

class Reader {
    constructor(f) { 
        this.f = f
    }

    run(e) {
        return this.f(e)
    }
    
    fmap(g) {
        return new Reader(e => this.run(e).then(g))
    }

    bind(g) {
        return new Reader(e => this.run(e).then(x => g(x).run(e)))
    }
}
 
const returnR = a => new Reader(_ => Promise.resolve(a))
const ask = new Reader(x => Promise.resolve(x))
 
const comp3 = v => 
    ask.bind(({myNum}) => 
        returnR(myNum * v))
        
const comp2 = _ =>
    ask.bind(({myNum}) => 
        returnR(myNum * 3)
    )
        

comp2().bind(comp3).fmap(x => x * 100).run({myNum: 5}).then(x => console.log(x))
INFO