Skip to content

Instantly share code, notes, and snippets.

@paulvictor
Created January 28, 2016 09:06
Show Gist options
  • Save paulvictor/87e8390c55b3dafcef2b to your computer and use it in GitHub Desktop.
Save paulvictor/87e8390c55b3dafcef2b to your computer and use it in GitHub Desktop.
Demonstrate how to use monadTransformers to combine monads(Observerable and IO in this case) to form higher order monads
"use strict"
var m = require("monet");
var MonadT = m.MonadT;
var IO = m.IO;
var Observable = require("rx").Observable;
class IOObs {
constructor(ioObservable){
this.value = ioObservable;
}
static of(x){
return new IOObs(IO(() => Observable.just(x)))
}
map(fn){
var newIOObs = this.value.map((observable) => observable.map(fn));
return new IOObs(newIOObs)
}
bind(fn){
var newIOObs = this.value.map((observableT) => {
return observableT.flatMap((t) => fn(t).run())
})
return new IOObs(newIOObs);
}
}
var f = function(i){
var inner = function(j){
return Observable.just(j+1); // Or you can do your async IO and return a promise or Observable,
//see https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/selectmany.md
};
var innerAsIO = inner.io1()(i);
return innerAsIO;
}
var o = Observable.just(42);
var ioObservable = new IOObs(IO(() => o));
var newO = ioObservable.bind(f);
var newOO = ioObservable.map((i) => i+2);
newO.value.run().subscribeOnNext(console.log)
newOO.value.run().subscribeOnNext(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment