Skip to content

Instantly share code, notes, and snippets.

@ulve
Last active October 18, 2017 11:37
Show Gist options
  • Save ulve/921808cc1f9020bf79c0e31446daf664 to your computer and use it in GitHub Desktop.
Save ulve/921808cc1f9020bf79c0e31446daf664 to your computer and use it in GitHub Desktop.
MonadWriter
class MonadWriter<T, V> {
private v:T;
private log:V[];
constructor(v:T, log:V[] | V) {
this.v = v;
if(log instanceof Array)
this.log = log;
else
this.log = [log];
};
public Map = <U>(f:(a:T) => U) : MonadWriter<U, V> => new MonadWriter(f(this.v), this.log);
public Run = ():[T, V[]] => [this.v, this.log];
public FlatMap = <U>(f:(b:T) => MonadWriter<U, V>) : MonadWriter<U, V> => {
const a = f(this.v)
return new MonadWriter(a.v,[ ...this.log, ...a.log])
}
}
const sum = x => y => new MonadWriter(x + y, "sum")
const mul = x => y => new MonadWriter(x * y, "mul")
const tostr = x => new MonadWriter(x.toString(), "tostr")
const a = sum(5)(5)
const b = a.FlatMap(mul(2))
const c = b.FlatMap(mul(8))
const d = c.Map(f => f.toString())
const e = c.FlatMap(tostr)
console.log(c.Run()) // [160, ['sum', 'mul', 'mul']]
console.log(d.Run()) // ['160', ['sum', 'mul', 'mul']]
console.log(e.Run()) // ['160', ['sum', 'mul', 'mul', 'tostr']]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment