Created
September 13, 2018 11:40
-
-
Save pfgray/67c75489d699ab8ca32c684cce2fcdba to your computer and use it in GitHub Desktop.
This file contains 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
// Do works with any Monad that implements the fantasy-land spec | |
// https://github.com/fantasyland/fantasy-land#monad | |
function Do(Type) { return (a, ...fns) => { | |
function doIt(as, fns) { | |
const [fn, ...rest] = fns; | |
if(rest.length === 0) { | |
return as['fantasy-land/chain'](a2s => { | |
return Type['fantasy-land/of'](fn.apply(null, a2s)); | |
}); | |
} else { | |
return as['fantasy-land/chain'](a2s => { | |
const aPrime = fn.apply(null, a2s); | |
return doIt(aPrime['fantasy-land/map']((aP) => [aP, ...a2s]), rest); | |
}); | |
} | |
} | |
return doIt(a['fantasy-land/map'](a2 => [a2]), fns); | |
}} | |
/** | |
* Maybe from https://github.com/origamitower/folktale | |
*/ | |
const Maybe = require('folktale/maybe'); | |
const maybe = | |
Do(Maybe)( | |
Maybe.Just(5), | |
(five) => Maybe.Just(7), | |
(seven, five) => Maybe.Just(seven + five), | |
(added, seven, five) => Maybe.Just(added * seven * five), | |
(multiplied, added, seven, five) => { | |
// last function is just 'mapped', so we can return anything and have | |
// it wrapped in Type["fantasy-land/of"]() | |
return multiplied + added + seven + five; | |
} | |
); | |
console.log(maybe) // folktale:Maybe.Just({ value: 444 }) ((5 + 7) * 5 * 7) + (5 + 7) + 5 + 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment