Skip to content

Instantly share code, notes, and snippets.

@gabejohnson
Last active January 11, 2018 15:40
Show Gist options
  • Save gabejohnson/bb9f0087de91aa930451b4e2f38dd8f9 to your computer and use it in GitHub Desktop.
Save gabejohnson/bb9f0087de91aa930451b4e2f38dd8f9 to your computer and use it in GitHub Desktop.

Types

In Fantasy Land, types are specified by an object containing a catamorphic method cata. cata has an arity matching the number of constructor functions belonging to each type. Each argument to cata is either:

  1. a value
  2. a function with an arity matching the number of arguments to the constructor function.
    1. Each function argument to cata must return a value of the same type as cata itself.

ex.

Identity a = { cata: (a -> b) -> b }
identity :: a -> Identity a

Conforming libraries may provide custom data constructors corresponding to these functions. No provided constructors are required to share the names of the constructor functions defined herein. For example, instead of Identity, the constructor could be named Id. If custom constructors are provided, they must return values which contain a cata method. This method must exhibit the same behaviour as described above.

ex.

var identity = require('fantasy-land/identity');

function Id(x) {
  this.x = x;
}

Id.prototype['fantasy-land/cata'] = function cata(f) {
  return f(this.x);
}

// Alternatively
Id.prototype['fantasy-land/cata'] = function cata(f) {
  return identity(this.x).cata(f);
}

(new Id(42)).cata(x => x) === identity(42).cata(x => x);

Either

The Either type encodes the concept of binary possibility (Left a and Right b).

Either a b = { cata :: ((a -> c), (b -> c)) -> c }
left :: a -> Either a b
right :: b -> Either a b

A value which conforms to the Either specification must provide an cata method.

The cata method takes two arguments:

e.cata(f, g)
  1. f must be a function which returns a value

    1. If f is not a function, the behaviour of cata is unspecified.
    2. No parts of f's return value should be checked.
  2. g must be a function which returns a value

    1. If g is not a function, the behaviour of cata is unspecified.
    2. No parts of g's return value should be checked.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment