by wrong_variable · 10y ago · 0 comments
It seems the reader monad just delays execution of some code until you call 'runWith' and you can define state variables throughout your code before calling runWith.
var result = m.runWith(...)
Other than that its almost exactly the same. And so are other monads. The Array monad (that is, if JS arrays actually had that method, which they don't) var m = [1,2,3]
.chain(x => [x, x * 10])
.chain(y => y < 2 ? [] : [y])
result: [10,2,20,3,30]Same API (monad), totally different functionality.
so anything that is like this :
values = ['coffee','water']
AfterWebSocket = values.sendToWebSocket()
AfterWebSocket.compute (eachValue => x*2)
is that it ?
For array chain takes a function that returns an array. For promises, chain takes a function that returns a promise object. For Reader, chain takes a function that returns another reader object.
Here is a complete class Reader:
class Reader {
constructor(computation) {
this.computation = computation;
}
runWith(data) {
return this.computation(data)
}
chain(readerReturningFn) {
return new Reader(data => readerReturningFn(this.computation(data))
.runWith(data))
}
static of(val) {
return new Reader(data => val)
}
static getState() {
return new Reader(data => data)
}
}
Here is how you can use it: var r = Reader.of(5).chain(x => Reader.getState().chain(y => Reader.of(x + y)))
r.runWith(2)
> 7
For it to be useful, you want ReaderT, a monad transformer which takes another monad (such as Future) and creates a new monad that provides functionality from both. This gets fairly complicated fairly quickly :D But the result is also a monad, which means it will have the same familiar `chain` based API.And yes, monads in programming are this simple. Mathematical monads are a wider generalisation of computing monads (just like Iterable would be something more general in the real world, not "things with a next() method that acts like this"), but in terms of programming its a shared API (chain) that acts in a certain way (chains to another object of the same type and flattens one level, whatever that means for the concrete implementation)
More like a specs that if people follow the world would be a better place ?
what is a monad transformer ?
I understand your code - but fail to see why its so useful :(