22 Fantasy-land
Lesson goal Understand what the Fantasy Land specification is and learn to implement a functor according to it: the fantasy-land/map method and the two laws a functor must obey.
The Fantasy Land specification is a set of rules and public interfaces describing abstractions from algebra and category theory.
These rules and laws describe algebraic structures.
In essence, by implementing these interfaces and laws, we follow the Fantasy Land specification.
// This is what it looks like
Setoid Semigroupoid Semigroup Foldable Functor Contravariant Filterable
(equals) (compose) (concat) (reduce) (map) (contramap) (filter)
| | | \ / | | | | \
| | | \ / | | | | \
| | | \ / | | | | \
| | | \ / | | | | \
| | | \ / | | | | \
Ord Category Monoid Traversable | | | | \
(lte) (id) (empty) (traverse) / | | \ \
| / | | \ \
| / / \ \ \
| Profunctor / \ Bifunctor \
| (promap) / \ (bimap) \
| / \ \
Group / \ \
(invert) Alt Apply Extend
(alt) (ap) (extend)
/ / \ \
/ / \ \
/ / \ \
/ / \ \
/ / \ \
Plus Applicative Chain Comonad
(zero) (of) (chain) (extract)
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
\ / \ / \
Alternative Monad ChainRec
(chainRec)Let's try to create a Functor according to the Fantasy Land specification. Besides the fantasy-land/map method, a functor must obey two laws. Identity: u['fantasy-land/map'](a => a) is equivalent to u. Composition: u['fantasy-land/map'](x => f(g(x))) is equivalent to u['fantasy-land/map'](g)['fantasy-land/map'](f).
// Signature
// fantasy-land/map :: Functor f => f a ~> (a -> b) -> f b
// Creating a functor
// ==== es5 syntax ======
// prepare the prototype for the constructor function
// without the inheritance from Object.prototype that is there by default
var prototypeFunctor = Object.create(null)
// The method name as defined by the specification
var FANTASY_LAND_MAP = 'fantasy-land/map'
// create the constructor function
function Functor(value) {
this.value = value
}
// wire up the prototype and the constructor function correctly
Functor.prototype = prototypeFunctor
prototypeFunctor.constructor = Functor
// and now the most important part: implement the functor interface
prototypeFunctor[FANTASY_LAND_MAP] = function (fn) {
return new Functor(fn(this.value))
}
// Let's break the key logic into parts
// return new Functor(fn(this.value))
// 1. We pass the current contents of the container through the function
// fn(this.value)
// 2. We return a new functor instance that holds the new value
// return new Functor(the result of the step above)
// Example
var functorObj = new Functor(5)
var functorResult = functorObj[FANTASY_LAND_MAP](function (value) { return value * 2 })
// no mutations
// the specification interface is implemented
console.log(functorObj.value) // 5
console.log(functorResult.value) // 10
// =========================
// Polyfill
// roughly how Object.create(objectProto) works inside
// (simplified: no second argument and no support for null)
var createObjectProto = function (obj) {
// build a constructor to create the instance
function XXX() {}
// set up the correct links
XXX.prototype = obj || Object.prototype
// we don't overwrite constructor: otherwise we would change the obj passed in,
// or, without an argument, Object.prototype, which all objects share
// create the instance and return it
return new XXX()
}// ==== es6 syntax ======
// everything is much simpler here
// here we can also remove the default inheritance from Object.prototype in the prototype
const FANTASY_LAND_MAP = 'fantasy-land/map'
class Functor {
constructor (value) {
this.value = value
}
// this method is stored in the prototype by default anyway
[FANTASY_LAND_MAP] (fn) {
return new Functor(fn(this.value))
}
}
// The example described above will work as well
const functorObj = new Functor(5)
// =========================
// ==== with pure functions ======
// Creating a functor without creating instances
// using pure functions
const functor = value => ({
value,
[FANTASY_LAND_MAP]: (fn) => functor(fn(value))
})
// we created an object and returned it
const objA = functor(10)
const objB = objA[FANTASY_LAND_MAP](value => value - 5)
console.log(objA.value) // 10
console.log(objB.value) // 5
// =========================Key points
- Fantasy Land is a specification: a set of rules and public interfaces describing abstractions from algebra and category theory. By implementing these interfaces and laws, we follow the specification.
- A functor implements the fantasy-land/map :: Functor f => f a ~> (a -> b) -> f b method: it passes the contents of the container through the function and returns a new functor that holds the new value.
- Besides the method, a functor obeys two laws: identity, where u['fantasy-land/map'](a => a) is equivalent to u, and composition, where u['fantasy-land/map'](x => f(g(x))) is equivalent to u['fantasy-land/map'](g)['fantasy-land/map'](f).
- map does not mutate the original functor: it keeps its previous value.
Exercises
Exercise 1
Following the pure-function functor from the lesson, implement a list functor for arrays: list(items) returns an object with an items field and a fantasy-land/map method that applies the function to every element and returns a new list. Apply two maps in a row to a list of words: first convert the words to upper case, then replace them with their lengths. Make sure the original list has not changed.
Starter code
const FANTASY_LAND_MAP = 'fantasy-land/map'
// your code: list :: [a] -> List a
const names = list(['map', 'filter', 'reduce'])
const upper = names[FANTASY_LAND_MAP]((word) => word.toUpperCase())
const lengths = upper[FANTASY_LAND_MAP]((word) => word.length)
console.log(JSON.stringify(names.items))
console.log(JSON.stringify(upper.items))
console.log(JSON.stringify(lengths.items))Expected output
["map","filter","reduce"] ["MAP","FILTER","REDUCE"] [3,6,6]
Show solution
const FANTASY_LAND_MAP = 'fantasy-land/map'
// list :: [a] -> List a
const list = (items) => ({
items,
// apply the function to every element and return a new list
[FANTASY_LAND_MAP]: (fn) => list(items.map(fn)),
})
const names = list(['map', 'filter', 'reduce'])
const upper = names[FANTASY_LAND_MAP]((word) => word.toUpperCase())
const lengths = upper[FANTASY_LAND_MAP]((word) => word.length)
console.log(JSON.stringify(names.items)) // the original list has not changed
console.log(JSON.stringify(upper.items))
console.log(JSON.stringify(lengths.items))Exercise 2
Write checkLaws(name, u, f, g): it checks both functor laws for the container u and prints two lines, one for identity and one for composition, for example "functor — identity: true" and "functor — composition: true". Compare containers via JSON.stringify: it skips methods, so only the data is compared. Check the functor from the lesson and a counted container that increases its count of calls on every map. Why is counted not a functor even though it has a fantasy-land/map method?
Starter code
const FANTASY_LAND_MAP = 'fantasy-land/map'
// the functor from the lesson
const functor = (value) => ({
value,
[FANTASY_LAND_MAP]: (fn) => functor(fn(value)),
})
// a container that counts the calls to map
const counted = (value, count = 0) => ({
value,
count,
[FANTASY_LAND_MAP]: (fn) => counted(fn(value), count + 1),
})
// JSON.stringify skips methods: we compare only the data
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
// your code: checkLaws
const double = (x) => x * 2
const inc = (x) => x + 1
checkLaws('functor', functor(5), double, inc)
checkLaws('counted', counted(5), double, inc)Expected output
functor — identity: true functor — composition: true counted — identity: false counted — composition: false
Show solution
const FANTASY_LAND_MAP = 'fantasy-land/map'
// the functor from the lesson
const functor = (value) => ({
value,
[FANTASY_LAND_MAP]: (fn) => functor(fn(value)),
})
// a container that counts the calls to map
const counted = (value, count = 0) => ({
value,
count,
[FANTASY_LAND_MAP]: (fn) => counted(fn(value), count + 1),
})
// JSON.stringify skips methods: we compare only the data
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
const checkLaws = (name, u, f, g) => {
const map = (container, fn) => container[FANTASY_LAND_MAP](fn)
// identity: map(a => a) is equivalent to u
console.log(`${name} — identity: ${same(map(u, (a) => a), u)}`)
// composition: map(x => f(g(x))) is equivalent to map(g) followed by map(f)
console.log(`${name} — composition: ${same(map(u, (x) => f(g(x))), map(map(u, g), f))}`)
}
const double = (x) => x * 2
const inc = (x) => x + 1
checkLaws('functor', functor(5), double, inc)
checkLaws('counted', counted(5), double, inc)
// counted is not a functor: map changes not only the value but also the count.
// So map(a => a) does not give the same container as u,
// and two maps in a row give a different count than one map with the compositionPlayground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.