Last active
October 18, 2017 16:38
-
-
Save aaruel/1e760cd78669d96824d4b7a325ffa7a0 to your computer and use it in GitHub Desktop.
Javascript (kinda) Monad test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Monad { | |
static ret(input) { | |
return { | |
bind: (lambda, ...args) => this.bind(lambda, input, ...args), | |
flatten: function*() { | |
yield* input; | |
} | |
}; | |
} | |
static unit(...input) { | |
return this.ret([...input]) | |
} | |
static bind(lambda, input, ...args) { | |
return this.ret( | |
input.map((x) => { | |
if (x == null) return null; | |
else return lambda(x, ...args); | |
}) | |
); | |
} | |
static compose(inputlambda, defaultlambda = (a) => a) { | |
const compose = (value) => inputlambda(defaultlambda(value)); | |
compose.compose = (clambda) => this.compose(clambda, compose); | |
return compose; | |
} | |
} | |
const add2 = (a) => a * 7 | |
const add1 = (a) => a * 6 | |
const add3 = (a) => a * 8 | |
const addall = Monad.compose(add2).compose(add1).compose(add3).compose(add2) | |
// constructing new functions | |
console.log( | |
addall(4) | |
) | |
// on the fly binding | |
var bind = | |
Monad.unit(5, 1, null) | |
.bind(add2) | |
.bind(add1) | |
.bind(add3) | |
.flatten() | |
console.log( | |
bind.next(), | |
bind.next(), | |
bind.next() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment