Last active
November 16, 2019 09:14
-
-
Save evilsoft/ee2d6050d6364ac27cea626d818004e7 to your computer and use it in GitHub Desktop.
Valid Writer in javascript?
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
// Based on http://adit.io/posts/2013-06-10-three-useful-monads.html | |
import map from 'ramda/src/map' | |
import compose from 'ramda/src/compose' | |
import curry from 'ramda/src/curry' | |
import multiply from 'ramda/src/multiply' | |
const chain = curry((fn, m) => m.chain(fn)) | |
const read = m => m.read() | |
function Writer(log, value) { | |
const read = () => ({ log: log.slice(), value }) | |
const map = fn => Writer(log.slice(), fn(value)) | |
const of = x => Writer([], x) | |
function chain(fn) { | |
const w = fn(value).read() | |
// maybe think about using a Monoid for `log`? | |
return Writer([].concat.call(log, w.log), w.value) | |
} | |
return { read, map, chain, of } | |
} | |
const addWriter = curry((x, y) => Writer(`adding ${x} to ${y}`, x + y)) | |
const multiplyWriter = curry((x, y) => Writer(`multiplying ${x} by ${y}`, x * y)) | |
const flow = compose( | |
chain(multiplyWriter(25)), | |
chain(addWriter(200)), | |
map(multiply(10)), | |
addWriter(2) | |
) | |
const readFlow = compose(read, flow) | |
console.log(readFlow(23)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment