Created
March 6, 2021 12:22
-
-
Save mkulke/4d2d3e3a53634adab5a20c25a910c361 to your computer and use it in GitHub Desktop.
sample code with fp-ts reader monads
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
// ts 4.2.0 | |
// fp-ts 2.9.5 | |
import * as RE from 'fp-ts/lib/Reader'; | |
import { pipe } from 'fp-ts/lib/pipeable'; | |
import * as assert from 'assert'; | |
interface Dependencies { | |
logger: { log: (message: string) => void }; | |
env: 'development' | 'production'; | |
} | |
function inner(n: number): RE.Reader<Dependencies, string> { | |
return function({ env, logger }) { | |
logger.log(`[${env}] calling inner`); | |
return n.toString(); | |
}; | |
} | |
function isEven(n: number): boolean { | |
return n % 2 === 0; | |
} | |
function unrelated(s: string): string { | |
return `${s}kg`; | |
} | |
function related(s: string): RE.Reader<Dependencies, string> { | |
return function({ env }) { | |
return `${s} in ${env}`; | |
}; | |
} | |
function sizeOf(s: string): number { | |
return s.length; | |
} | |
const logger = { | |
log: (message: string) => { | |
console.log(message); | |
}, | |
}; | |
const deps: Dependencies = { logger, env: 'development' }; | |
let outer = pipe( | |
inner(3), | |
RE.map(unrelated), | |
RE.chain(related), | |
RE.map(sizeOf), | |
); | |
let result = outer(deps); | |
assert(result === 18); | |
// equivalent to the outer pipe: sizeOf(....) | |
const outer2 = pipe( | |
RE.of(sizeOf), | |
RE.ap(pipe(inner(3), RE.map(unrelated), RE.chain(related))), | |
); | |
result = outer2(deps); | |
assert(result === 18); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment