Skip to content

Instantly share code, notes, and snippets.

@zaetrik
Created May 9, 2020 16:24
Show Gist options
  • Save zaetrik/e9634b12950f62f2d88670f6cee7a4eb to your computer and use it in GitHub Desktop.
Save zaetrik/e9634b12950f62f2d88670f6cee7a4eb to your computer and use it in GitHub Desktop.
Functor: Compose a pure function with an effectful function
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