Created
May 9, 2020 16:24
-
-
Save zaetrik/e9634b12950f62f2d88670f6cee7a4eb to your computer and use it in GitHub Desktop.
Functor: Compose a pure function with an effectful function
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
import { Option, isNone, none, some } from "fp-ts/lib/Option"; | |
// Here we lift a pure function to work with Option | |
// Taken from https://dev.to/gcanti/getting-started-with-fp-ts-functor-36ek | |
function lift<A, B>(f: (a: A) => B): (fa: Option<A>) => Option<B> { | |
return (fa) => (isNone(fa) ? none : some(f(fa.value))); | |
} | |
const effectfulDouble = (x: number) => some(x * 2); | |
const pureSay = (x: number) => `The result is ${x}`; | |
// Let's compose the two functions | |
const liftedSay = lift(pureSay); | |
liftedSay(effectfulDouble(5)); // { _tag: 'Some', value: 'The result is 10' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment