[{"data":1,"prerenderedAt":71},["ShallowReactive",2],{"course-en-fantasy-land":3},{"lesson":4,"number":62,"prev":63,"next":67},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":34,"exercises":43},"fantasy-land",{"ru":7,"en":8},"","Fantasy-land",{"ru":7,"en":10},"What the Fantasy Land specification describes and how to implement a JavaScript functor with fantasy-land\u002Fmap that obeys the identity and composition laws.",{"ru":7,"en":12},"Understand what the Fantasy Land specification is and learn to implement a functor according to it: the fantasy-land\u002Fmap method and the two laws a functor must obey.",[14,17,19,21,26,28,31],{"type":15,"ru":7,"en":16},"text","The Fantasy Land specification is a set of rules and public interfaces describing abstractions from algebra and category theory.",{"type":15,"ru":7,"en":18},"These rules and laws describe algebraic structures.",{"type":15,"ru":7,"en":20},"In essence, by implementing these interfaces and laws, we follow the Fantasy Land specification.",{"type":22,"pseudo":23,"code":24},"code",true,{"ru":7,"en":25},"\u002F\u002F This is what it looks like\n\nSetoid   Semigroupoid  Semigroup   Foldable        Functor      Contravariant  Filterable\n(equals)    (compose)    (concat)   (reduce)         (map)        (contramap)    (filter)\n    |           |           |           \\         \u002F | | | | \\\n    |           |           |            \\       \u002F  | | | |  \\\n    |           |           |             \\     \u002F   | | | |   \\\n    |           |           |              \\   \u002F    | | | |    \\\n    |           |           |               \\ \u002F     | | | |     \\\n  Ord      Category     Monoid         Traversable | | | |      \\\n  (lte)       (id)       (empty)        (traverse)  \u002F | | \\       \\\n                            |                      \u002F  | |  \\       \\\n                            |                     \u002F   \u002F \\   \\       \\\n                            |             Profunctor \u002F   \\ Bifunctor \\\n                            |              (promap) \u002F     \\ (bimap)   \\\n                            |                      \u002F       \\           \\\n                          Group                   \u002F         \\           \\\n                        (invert)               Alt        Apply      Extend\n                                              (alt)        (ap)     (extend)\n                                                \u002F           \u002F \\           \\\n                                              \u002F           \u002F   \\           \\\n                                              \u002F           \u002F     \\           \\\n                                            \u002F           \u002F       \\           \\\n                                            \u002F           \u002F         \\           \\\n                                          Plus    Applicative    Chain      Comonad\n                                        (zero)       (of)      (chain)    (extract)\n                                            \\         \u002F \\         \u002F \\\n                                            \\       \u002F   \\       \u002F   \\\n                                              \\     \u002F     \\     \u002F     \\\n                                              \\   \u002F       \\   \u002F       \\\n                                                \\ \u002F         \\ \u002F         \\\n                                            Alternative    Monad     ChainRec\n                                                                    (chainRec)",{"type":15,"ru":7,"en":27},"Let's try to create a Functor according to the Fantasy Land specification. Besides the fantasy-land\u002Fmap method, a functor must obey two laws. Identity: u['fantasy-land\u002Fmap'](a => a) is equivalent to u. Composition: u['fantasy-land\u002Fmap'](x => f(g(x))) is equivalent to u['fantasy-land\u002Fmap'](g)['fantasy-land\u002Fmap'](f).",{"type":22,"code":29},{"ru":7,"en":30},"\u002F\u002F Signature\n\u002F\u002F fantasy-land\u002Fmap :: Functor f => f a ~> (a -> b) -> f b\n\n\u002F\u002F Creating a functor\n\u002F\u002F ==== es5 syntax ======\n\n\u002F\u002F prepare the prototype for the constructor function\n\u002F\u002F without the inheritance from Object.prototype that is there by default\nvar prototypeFunctor = Object.create(null)\n\n\u002F\u002F The method name as defined by the specification\nvar FANTASY_LAND_MAP = 'fantasy-land\u002Fmap'\n\n\u002F\u002F create the constructor function\nfunction Functor(value) {\n  this.value = value\n}\n\n\u002F\u002F wire up the prototype and the constructor function correctly\nFunctor.prototype = prototypeFunctor\nprototypeFunctor.constructor = Functor\n\n\u002F\u002F  and now the most important part: implement the functor interface\nprototypeFunctor[FANTASY_LAND_MAP] = function (fn) {\n  return new Functor(fn(this.value))\n}\n\n\u002F\u002F Let's break the key logic into parts\n\u002F\u002F return new Functor(fn(this.value))\n\u002F\u002F 1. We pass the current contents of the container through the function\n\u002F\u002F fn(this.value)\n\u002F\u002F 2. We return a new functor instance that holds the new value\n\u002F\u002F return new Functor(the result of the step above)\n\n\u002F\u002F Example\nvar functorObj = new Functor(5)\n\nvar functorResult = functorObj[FANTASY_LAND_MAP](function (value) { return value * 2 })\n\n\u002F\u002F no mutations\n\u002F\u002F the specification interface is implemented\nconsole.log(functorObj.value) \u002F\u002F 5\nconsole.log(functorResult.value) \u002F\u002F 10\n\n\u002F\u002F =========================\n\n\u002F\u002F Polyfill\n\u002F\u002F roughly how Object.create(objectProto) works inside\n\u002F\u002F (simplified: no second argument and no support for null)\nvar createObjectProto = function (obj) {\n  \u002F\u002F build a constructor to create the instance\n  function XXX() {}\n\n  \u002F\u002F set up the correct links\n  XXX.prototype = obj || Object.prototype\n  \u002F\u002F we don't overwrite constructor: otherwise we would change the obj passed in,\n  \u002F\u002F or, without an argument, Object.prototype, which all objects share\n\n  \u002F\u002F create the instance and return it\n  return new XXX()\n}",{"type":22,"code":32},{"ru":7,"en":33},"\u002F\u002F ==== es6 syntax ======\n\u002F\u002F everything is much simpler here\n\u002F\u002F here we can also remove the default inheritance from Object.prototype in the prototype\nconst FANTASY_LAND_MAP = 'fantasy-land\u002Fmap'\n\nclass Functor {\n  constructor (value) {\n    this.value = value\n  }\n\n  \u002F\u002F this method is stored in the prototype by default anyway\n  [FANTASY_LAND_MAP] (fn) {\n    return new Functor(fn(this.value))\n  }\n}\n\n\u002F\u002F The example described above will work as well\nconst functorObj = new Functor(5)\n\u002F\u002F =========================\n\n\n\u002F\u002F ==== with pure functions ======\n\u002F\u002F Creating a functor without creating instances\n\u002F\u002F using pure functions\nconst functor = value => ({\n  value,\n  [FANTASY_LAND_MAP]: (fn) => functor(fn(value))\n})\n\n\u002F\u002F we created an object and returned it\nconst objA = functor(10)\nconst objB = objA[FANTASY_LAND_MAP](value => value - 5)\n\nconsole.log(objA.value) \u002F\u002F 10\nconsole.log(objB.value) \u002F\u002F 5\n\n\u002F\u002F =========================",[35,37,39,41],{"ru":7,"en":36},"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.",{"ru":7,"en":38},"A functor implements the fantasy-land\u002Fmap :: 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.",{"ru":7,"en":40},"Besides the method, a functor obeys two laws: identity, where u['fantasy-land\u002Fmap'](a => a) is equivalent to u, and composition, where u['fantasy-land\u002Fmap'](x => f(g(x))) is equivalent to u['fantasy-land\u002Fmap'](g)['fantasy-land\u002Fmap'](f).",{"ru":7,"en":42},"map does not mutate the original functor: it keeps its previous value.",[44,53],{"task":45,"starter":47,"solution":49,"expected":51},{"ru":7,"en":46},"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\u002Fmap 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.",{"ru":7,"en":48},"const FANTASY_LAND_MAP = 'fantasy-land\u002Fmap'\n\n\u002F\u002F your code: list :: [a] -> List a\n\nconst names = list(['map', 'filter', 'reduce'])\nconst upper = names[FANTASY_LAND_MAP]((word) => word.toUpperCase())\nconst lengths = upper[FANTASY_LAND_MAP]((word) => word.length)\n\nconsole.log(JSON.stringify(names.items))\nconsole.log(JSON.stringify(upper.items))\nconsole.log(JSON.stringify(lengths.items))",{"ru":7,"en":50},"const FANTASY_LAND_MAP = 'fantasy-land\u002Fmap'\n\n\u002F\u002F list :: [a] -> List a\nconst list = (items) => ({\n  items,\n  \u002F\u002F apply the function to every element and return a new list\n  [FANTASY_LAND_MAP]: (fn) => list(items.map(fn)),\n})\n\nconst names = list(['map', 'filter', 'reduce'])\nconst upper = names[FANTASY_LAND_MAP]((word) => word.toUpperCase())\nconst lengths = upper[FANTASY_LAND_MAP]((word) => word.length)\n\nconsole.log(JSON.stringify(names.items)) \u002F\u002F the original list has not changed\nconsole.log(JSON.stringify(upper.items))\nconsole.log(JSON.stringify(lengths.items))",{"ru":7,"en":52},"[\"map\",\"filter\",\"reduce\"]\n[\"MAP\",\"FILTER\",\"REDUCE\"]\n[3,6,6]",{"task":54,"starter":56,"solution":58,"expected":60},{"ru":7,"en":55},"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\u002Fmap method?",{"ru":7,"en":57},"const FANTASY_LAND_MAP = 'fantasy-land\u002Fmap'\n\n\u002F\u002F the functor from the lesson\nconst functor = (value) => ({\n  value,\n  [FANTASY_LAND_MAP]: (fn) => functor(fn(value)),\n})\n\n\u002F\u002F a container that counts the calls to map\nconst counted = (value, count = 0) => ({\n  value,\n  count,\n  [FANTASY_LAND_MAP]: (fn) => counted(fn(value), count + 1),\n})\n\n\u002F\u002F JSON.stringify skips methods: we compare only the data\nconst same = (a, b) => JSON.stringify(a) === JSON.stringify(b)\n\n\u002F\u002F your code: checkLaws\n\nconst double = (x) => x * 2\nconst inc = (x) => x + 1\n\ncheckLaws('functor', functor(5), double, inc)\ncheckLaws('counted', counted(5), double, inc)",{"ru":7,"en":59},"const FANTASY_LAND_MAP = 'fantasy-land\u002Fmap'\n\n\u002F\u002F the functor from the lesson\nconst functor = (value) => ({\n  value,\n  [FANTASY_LAND_MAP]: (fn) => functor(fn(value)),\n})\n\n\u002F\u002F a container that counts the calls to map\nconst counted = (value, count = 0) => ({\n  value,\n  count,\n  [FANTASY_LAND_MAP]: (fn) => counted(fn(value), count + 1),\n})\n\n\u002F\u002F JSON.stringify skips methods: we compare only the data\nconst same = (a, b) => JSON.stringify(a) === JSON.stringify(b)\n\nconst checkLaws = (name, u, f, g) => {\n  const map = (container, fn) => container[FANTASY_LAND_MAP](fn)\n  \u002F\u002F identity: map(a => a) is equivalent to u\n  console.log(`${name} — identity: ${same(map(u, (a) => a), u)}`)\n  \u002F\u002F composition: map(x => f(g(x))) is equivalent to map(g) followed by map(f)\n  console.log(`${name} — composition: ${same(map(u, (x) => f(g(x))), map(map(u, g), f))}`)\n}\n\nconst double = (x) => x * 2\nconst inc = (x) => x + 1\n\ncheckLaws('functor', functor(5), double, inc)\ncheckLaws('counted', counted(5), double, inc)\n\n\u002F\u002F counted is not a functor: map changes not only the value but also the count.\n\u002F\u002F So map(a => a) does not give the same container as u,\n\u002F\u002F and two maps in a row give a different count than one map with the composition",{"ru":7,"en":61},"functor — identity: true\nfunctor — composition: true\ncounted — identity: false\ncounted — composition: false",22,{"slug":64,"title":65},"functors",{"ru":7,"en":66},"Functors and their laws",{"slug":68,"title":69},"maybe-either",{"ru":7,"en":70},"Maybe and Either",1792684725075]