Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Created July 16, 2019 11:02
Show Gist options
  • Save abiodun0/d570d8575a63cb1820772d7debe47de4 to your computer and use it in GitHub Desktop.
Save abiodun0/d570d8575a63cb1820772d7debe47de4 to your computer and use it in GitHub Desktop.
SomeRandoms.
// check this out; with the static land approach of modeling instances as values,
// you can actually witness functor instances for the classes themselves.
// this gives you instances for free when you have structure preserving morphisms from a
// type that has some instance to a type for which you want that instance:
const { adt, match } = require("@masaeedu/adt")
// :: type Eq v = { equals: v -> v -> Boolean }
// :: type Contravariant f = { contramap: (b -> a) -> f a -> f b }
// :: type Iso x y = { to: x -> y, from: y -> x }
// :: Contravariant Eq
const Eq = (() => {
// :: (b -> a) -> Eq a -> Eq b
const contramap = ba => ({ equals }) => ({ equals: b1 => b2 => equals(ba(b1))(ba(b2)) })
return { contramap }
})()
// Let's say NonNegativeInt is the type inhabited by non-negative JS integers
// :: Eq NonNegativeInt
const eqInt = (() => {
const equals = x => y => x === y
return { equals }
})()
const Nat = adt({ Z: [], S: ["Nat"] })
const { Z, S } = Nat
// :: Nat -> NonNegativeInt
const natToInt = match({
Z: 0,
S: x => 1 + natToInt(x)
})
const eqNat = Eq.contramap(natToInt)(eqInt)
const tests = [
eqNat.equals(Z)(Z),
eqNat.equals(Z)(S(Z)),
eqNat.equals(S(S(S(Z))))(S(S(S(Z))))
]
console.log(tests)
// => [true, false, true]
// in the contrived example above we have a simple `Eq` instance for integers, and we have an equivalence
// preserving morphism from church numerals to integers, so for free we get an `Eq` instance for church numerals
// in languages with typeclasses and typeclass instances as a distinct concept it would be quite annoying to express this,
// whereas when using simple types you don't even need a distinct `Functor`/`Contravariant`/etc.
// from the one you'd use to represent instances for normal types like arrays or functions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment