Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Last active October 12, 2017 13:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briancavalier/ad2354418c9e35249c9ffbc6fbf52f21 to your computer and use it in GitHub Desktop.
Save briancavalier/ad2354418c9e35249c9ffbc6fbf52f21 to your computer and use it in GitHub Desktop.
Fun with a Lazy type and pairs
// Pair helpers
// Map the first element of a pair
const first = <A, B, C> (f: A => B, [a, c]: [A, C]): [B, C] =>
[f(a), c]
// Map the second element of a pair
const second = <A, B, C> (f: B => C, [a, b]: [A, B]): [A, C] =>
[a, f(b)]
// Lazy type
type Lazy<A> = () => A
const lazy = <A> (a: A): Lazy<A> =>
() => a
const force = <A> (la: Lazy<A>): A =>
la()
const mapLazy = <A, B> (f: A => B, la: Lazy<A>): Lazy<B> =>
() => f(force(la))
const firstLazy = <A, B, C> (f: A => B, lp: Lazy<[A, C]>): Lazy<[B, C]> =>
() => first(f, force(lp))
const secondLazy = <A, B, C> (f: B => C, lp: Lazy<[A, B]>): Lazy<[A, C]> =>
() => second(f, force(lp))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment