[{"data":1,"prerenderedAt":95},["ShallowReactive",2],{"course-en-functors":3},{"lesson":4,"number":86,"prev":87,"next":91},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":56,"exercises":67},"functors",{"ru":7,"en":8},"","Functors and their laws",{"ru":7,"en":10},"Functors in JavaScript: a container whose map keeps the structure. Arrays and a Maybe-like container, the functor laws and why a promise breaks composition.",{"ru":7,"en":12},"Understand what a functor is, a container whose map changes the values and keeps the structure, learn to check the identity and composition laws in code and rely on them when refactoring.",[14,17,19,23,25,27,30,33,35,38,40,42,44,47,49,51,54],{"type":15,"ru":7,"en":16},"text","In the lesson \"The map, filter, and reduce functions\", map worked with arrays, and in the \"Hindley–Milner type notation\" lesson we came across the signature map :: Functor f => (a -> b) -> f a -> f b. Instead of an array it has f, which stands for any functor. Let's find out what this f is and why map can be trusted.",{"type":15,"ru":7,"en":18},"A functor is a container that has map. map takes an ordinary function a -> b, applies it to the values inside the container and returns a new container of the same kind. The key property of map is that it keeps the structure: an array of three elements becomes an array of three elements in the same order, and only the values themselves change. The original container stays as it was.",{"type":20,"code":21},"code",{"ru":7,"en":22},"\u002F\u002F An array is the most familiar functor\n\u002F\u002F map :: (a -> b) -> [a] -> [b]\nconst words = ['functor', 'map', 'law']\nconst lengths = words.map((word) => word.length)\n\nconsole.log(JSON.stringify(lengths)) \u002F\u002F [7,3,3]\n\u002F\u002F the structure is the same: three elements in the same order, only the values changed\nconsole.log(words.length === lengths.length) \u002F\u002F true\n\u002F\u002F the original array has not changed\nconsole.log(JSON.stringify(words)) \u002F\u002F [\"functor\",\"map\",\"law\"]\n\n\u002F\u002F Box is the simplest functor: a container for exactly one value\n\u002F\u002F Box :: a -> Box a\nconst Box = (value) => ({\n  value,\n  \u002F\u002F map :: Box a ~> (a -> b) -> Box b\n  map: (fn) => Box(fn(value)),\n})\n\nconst box = Box('functor')\n  .map((word) => word.toUpperCase())\n  .map((word) => word.length)\nconsole.log(box.value) \u002F\u002F 7\n\n\u002F\u002F the same function works with any functor: it knows nothing about the container\n\u002F\u002F double :: Number -> Number\nconst double = (x) => x * 2\nconsole.log(JSON.stringify([1, 2, 3].map(double))) \u002F\u002F [2,4,6]\nconsole.log(Box(21).map(double).value) \u002F\u002F 42\n\n\u002F\u002F R.map accepts any functor: if the object has a map method, R.map calls it\nconsole.log(R.map(double, Box(21)).value) \u002F\u002F 42",{"type":15,"ru":7,"en":24},"Box is useless on its own, but it shows that map is not only about arrays. The double function knows nothing about the container, and it is the container's own map that decides how to reach the values: for an array, visit every element; for Box, take the single value. That is why R.map from Ramda works with both an array and a Box.",{"type":15,"ru":7,"en":26},"A more interesting container is one that may hold no value at all. Just holds a value, Nothing means it is absent. map on Just applies the function, while map on Nothing does nothing: there is nothing to apply the function to. The check for absence lives in one place, in map, and the functions in the chain work with ordinary values. The structure is kept here too: Just stays Just after map, and Nothing stays Nothing. The ready-made Maybe from the Sanctuary library is covered in the \"Maybe and Either\" lesson.",{"type":20,"code":28},{"ru":7,"en":29},"\u002F\u002F A Maybe-like container: there is a value (Just) or there is none (Nothing)\n\n\u002F\u002F Just :: a -> Maybe a\nconst Just = (value) => ({\n  \u002F\u002F apply the function and put the result back into Just\n  map: (fn) => Just(fn(value)),\n  \u002F\u002F getOrElse :: Maybe a ~> a -> a\n  getOrElse: () => value,\n})\n\n\u002F\u002F Nothing :: Maybe a\nconst Nothing = {\n  \u002F\u002F there is nothing to apply the function to: Nothing stays Nothing\n  map: () => Nothing,\n  getOrElse: (fallback) => fallback,\n}\n\nconst users = [\n  { id: 1, name: 'ann' },\n  { id: 2, name: 'bob' },\n]\n\n\u002F\u002F findUser :: Number -> Maybe Object\nconst findUser = (id) => {\n  const user = users.find((u) => u.id === id)\n  return user === undefined ? Nothing : Just(user)\n}\n\n\u002F\u002F greet :: Number -> String\n\u002F\u002F the functions in the chain don't check whether the user was found: map does that\nconst greet = (id) =>\n  findUser(id)\n    .map((user) => user.name)\n    .map((name) => name.toUpperCase())\n    .map((name) => `Hello, ${name}`)\n    .getOrElse('User not found')\n\nconsole.log(greet(2)) \u002F\u002F Hello, BOB\nconsole.log(greet(7)) \u002F\u002F User not found",{"type":31,"ru":7,"en":32},"heading","The functor laws",{"type":15,"ru":7,"en":34},"A map method alone is not enough to make a container a functor: map must obey two laws. Identity: u.map(x => x) is equivalent to u, so if the function changes nothing, map changes nothing either. Composition: u.map(x => f(g(x))) is equivalent to u.map(g).map(f), so one pass with the composition gives the same as two passes in a row. In the notation from the \"Category theory\" lesson, where the dot means composition, they are written more briefly: map(id) = id and map(f . g) = map(f) . map(g).",{"type":20,"code":36},{"ru":7,"en":37},"\u002F\u002F The functor laws on an array and on Box\n\u002F\u002F identity:    u.map(x => x) is equivalent to u\n\u002F\u002F composition: u.map(x => f(g(x))) is equivalent to u.map(g).map(f)\n\n\u002F\u002F id :: a -> a\nconst id = (x) => x\n\u002F\u002F compose :: ((b -> c), (a -> b)) -> a -> c\nconst compose = (f, g) => (x) => f(g(x))\n\u002F\u002F \"equivalent\" means the same structure and the same values\n\u002F\u002F same :: (a, a) -> Boolean\nconst same = (a, b) => JSON.stringify(a) === JSON.stringify(b)\n\nconst inc = (x) => x + 1\nconst tenTimes = (x) => x * 10\nconst u = [1, 2, 3]\n\nconsole.log(u.map(id) === u) \u002F\u002F false: map returned a new array\nconsole.log(same(u.map(id), u)) \u002F\u002F true: identity holds\nconsole.log(same(u.map(compose(tenTimes, inc)), u.map(inc).map(tenTimes))) \u002F\u002F true: so does composition\n\n\u002F\u002F Box from the first example\n\u002F\u002F Box :: a -> Box a\nconst Box = (value) => ({\n  value,\n  map: (fn) => Box(fn(value)),\n})\n\n\u002F\u002F the laws hold for Box too: we compare the values inside\nconsole.log(Box(5).map(id).value === Box(5).value) \u002F\u002F true: identity\nconsole.log(Box(5).map(compose(tenTimes, inc)).value === Box(5).map(inc).map(tenTimes).value) \u002F\u002F true: composition\n\n\u002F\u002F A \"convenient\" map that also throws away empty results\n\u002F\u002F compactMap :: (a -> b) -> [a] -> [b]\nconst compactMap = (fn) => (arr) => arr.map(fn).filter((x) => x != null)\n\n\u002F\u002F identity is broken: there were three elements, now there are two, and 30 moved from index 2 to 1\nconst scores = [10, null, 30]\nconsole.log(JSON.stringify(compactMap(id)(scores))) \u002F\u002F [10,30]\nconsole.log(same(compactMap(id)(scores), scores)) \u002F\u002F false\n\n\u002F\u002F composition is broken too: two passes can no longer be merged into one\nconst hideBig = (x) => (x > 15 ? null : x) \u002F\u002F hide the big values\nconst orZero = (x) => (x == null ? 0 : x) \u002F\u002F replace an empty value with zero\nconst values = [10, 30]\nconsole.log(JSON.stringify(compactMap(compose(orZero, hideBig))(values))) \u002F\u002F [10,0]\nconsole.log(JSON.stringify(compactMap(orZero)(compactMap(hideBig)(values)))) \u002F\u002F [10]",{"type":15,"ru":7,"en":39},"\"Equivalent\" means the same structure and the same values, not the same object: map always returns a new container, so u.map(id) === u gives false. The laws guarantee that map changes the values and nothing else: it does not throw elements away, does not reorder them and does not change the shape of the container. compactMap breaks both laws, and code that relies on the array length or on indexes breaks after such a map.",{"type":31,"ru":7,"en":41},"Laws and refactoring",{"type":15,"ru":7,"en":43},"The composition law is a refactoring rule: map(f) . map(g) = map(f . g). A chain of two maps can be merged into one pass without an intermediate array, and a long function inside map can be split into several maps. The result will not change, and there is no need to check it on every example: the law guarantees it. With compactMap this is not possible, as the example above showed.",{"type":20,"code":45},{"ru":7,"en":46},"\u002F\u002F The composition law as a refactoring rule:\n\u002F\u002F map(f) . map(g) = map(f . g)\n\nconst orders = [\n  { id: 1, total: 1200 },\n  { id: 2, total: 450 },\n  { id: 3, total: 3100 },\n]\n\n\u002F\u002F a call journal: the order in which the functions run\nlet journal = []\n\u002F\u002F traced :: (String, (a -> b)) -> a -> b\nconst traced = (name, fn) => (x) => {\n  journal.push(name)\n  return fn(x)\n}\n\n\u002F\u002F getTotal :: Object -> Number\nconst getTotal = traced('getTotal', (order) => order.total)\n\u002F\u002F format :: Number -> String\nconst format = traced('format', (total) => total.toFixed(2))\n\n\u002F\u002F two passes: two traversals and an intermediate array of totals\nconst twoPasses = R.map(format, R.map(getTotal, orders))\nconsole.log(journal.join(' '))\n\u002F\u002F getTotal getTotal getTotal format format format\n\njournal = []\n\u002F\u002F one pass: the composition inside map; R.compose runs the functions right to left\nconst onePass = R.map(R.compose(format, getTotal), orders)\nconsole.log(journal.join(' '))\n\u002F\u002F getTotal format getTotal format getTotal format\n\n\u002F\u002F the result is the same\nconsole.log(JSON.stringify(onePass)) \u002F\u002F [\"1200.00\",\"450.00\",\"3100.00\"]\nconsole.log(R.equals(twoPasses, onePass)) \u002F\u002F true",{"type":15,"ru":7,"en":48},"Look at the journal: the result is the same, but the order of calls is different. With two passes, every getTotal runs first and then every format, while one pass interleaves them. For pure functions the order does not matter, as the \"Pure functions\" lesson explains. But if the functions write to a log or change outside data, after such a refactoring the effects will happen in a different order.",{"type":15,"ru":7,"en":50},"A promise's then method looks like map: it applies the function to the value once the value arrives and returns a new promise. But a promise is not a strict functor. If the function returns a promise, or any other object with a then method, then does not put it inside but unwraps it and waits for its value. There is no such thing as a promise inside a promise, and the composition law is broken. That is why libraries that follow the laws strictly, Sanctuary for example, do not treat a promise as a functor: S.map does not work with it.",{"type":20,"code":52},{"ru":7,"en":53},"\u002F\u002F a promise's then looks like map: it applies the function to the value inside\nPromise.resolve(21)\n  .then((x) => x * 2)\n  .then((x) => console.log(x)) \u002F\u002F 42\n\n\u002F\u002F but then unwraps the promise that the function returned\n\u002F\u002F f :: a -> Promise a\nconst f = (x) => Promise.resolve(x)\n\u002F\u002F g :: a -> Boolean, whether a promise came in\nconst g = (value) => value instanceof Promise\n\nconst p = Promise.resolve(1)\nPromise.all([\n  p.then(f).then(g), \u002F\u002F then unwrapped the promise from f, so g got 1\n  p.then((x) => g(f(x))), \u002F\u002F and here g got the promise itself\n]).then(([twoThens, composed]) => {\n  console.log(twoThens) \u002F\u002F false\n  console.log(composed) \u002F\u002F true\n  \u002F\u002F the results differ: the composition law does not hold for then\n})",{"type":15,"ru":7,"en":55},"The name \"functor\" comes from category theory. In the \"Category theory\" lesson a category is types as objects and functions as morphisms between them. A functor maps one category to another: it assigns to each type a a type F a (to the type Number, the type [Number]), and to each function f :: a -> b a function map(f) :: F a -> F b. The functor laws say exactly that this mapping preserves identity morphisms and composition. In programming a functor takes the language's types to types of the same language, which is why it is called an endofunctor. This is an idealization: it holds for pure functions that finish without exceptions.",[57,59,61,63,65],{"ru":7,"en":58},"A functor is a container with map: map applies a function to the values inside and returns a new container with the same structure. An array, Box and a Maybe-like container are functors.",{"ru":7,"en":60},"The functor laws: identity, where u.map(x => x) is equivalent to u, and composition, where u.map(x => f(g(x))) is equivalent to u.map(g).map(f). A map method without the laws does not make a container a functor.",{"ru":7,"en":62},"The composition law is a refactoring rule: map(f) . map(g) = map(f . g). Two passes can be merged into one: the result stays the same but the order of calls changes, so the functions must be pure.",{"ru":7,"en":64},"A promise's then looks like map, but it unwraps a promise returned by the function, so a promise is not a strict functor.",{"ru":7,"en":66},"In category theory a functor maps types and the functions between them, preserving identity and composition.",[68,77],{"task":69,"starter":71,"solution":73,"expected":75},{"ru":7,"en":70},"A tree is a functor too. A tree node is an object { value, children }, where children is an array of nodes. Write mapTree(fn, tree): it applies fn to the value of every node and returns a new tree of the same shape, where every node has as many children as before, in the same order. Recursion from the \"Recursion\" lesson and the array's map will come in handy. The starter prints the tree after mapTree and checks both functor laws on it.",{"ru":7,"en":72},"\u002F\u002F mapTree :: ((a -> b), Tree a) -> Tree b\n\u002F\u002F your code\n\nconst tree = {\n  value: 1,\n  children: [\n    { value: 2, children: [] },\n    { value: 3, children: [{ value: 4, children: [] }] },\n  ],\n}\n\nconst id = (x) => x\nconst inc = (x) => x + 1\nconst double = (x) => x * 2\n\u002F\u002F same :: (a, a) -> Boolean\nconst same = (a, b) => JSON.stringify(a) === JSON.stringify(b)\n\nconsole.log(JSON.stringify(mapTree(double, tree)))\nconsole.log(`identity: ${same(mapTree(id, tree), tree)}`)\nconsole.log(`composition: ${same(mapTree((x) => double(inc(x)), tree), mapTree(double, mapTree(inc, tree)))}`)",{"ru":7,"en":74},"\u002F\u002F mapTree :: ((a -> b), Tree a) -> Tree b\nconst mapTree = (fn, tree) => ({\n  value: fn(tree.value),\n  \u002F\u002F the same children in the same order: the array's map keeps the structure\n  children: tree.children.map((child) => mapTree(fn, child)),\n})\n\nconst tree = {\n  value: 1,\n  children: [\n    { value: 2, children: [] },\n    { value: 3, children: [{ value: 4, children: [] }] },\n  ],\n}\n\nconst id = (x) => x\nconst inc = (x) => x + 1\nconst double = (x) => x * 2\n\u002F\u002F same :: (a, a) -> Boolean\nconst same = (a, b) => JSON.stringify(a) === JSON.stringify(b)\n\nconsole.log(JSON.stringify(mapTree(double, tree)))\nconsole.log(`identity: ${same(mapTree(id, tree), tree)}`)\nconsole.log(`composition: ${same(mapTree((x) => double(inc(x)), tree), mapTree(double, mapTree(inc, tree)))}`)",{"ru":7,"en":76},"{\"value\":2,\"children\":[{\"value\":4,\"children\":[]},{\"value\":6,\"children\":[{\"value\":8,\"children\":[]}]}]}\nidentity: true\ncomposition: true",{"task":78,"starter":80,"solution":82,"expected":84},{"ru":7,"en":79},"In the starter a list of products goes through three maps in a row: take the price, apply a 10% discount and format the string. The passes counter counts how many times the array was traversed. Relying on the composition law, get the same result after in a single pass: one call to map with the composition of the three functions via R.pipe or R.compose. After the refactoring the counter should show 1, and the result should match the previous one.",{"ru":7,"en":81},"const products = [\n  { title: 'keyboard', price: 1000 },\n  { title: 'mouse', price: 450 },\n  { title: 'cable', price: 120 },\n]\n\n\u002F\u002F how many times the array was traversed\nlet passes = 0\n\u002F\u002F map :: (a -> b) -> [a] -> [b]\nconst map = (fn) => (arr) => {\n  passes += 1\n  return arr.map(fn)\n}\n\n\u002F\u002F getPrice :: Object -> Number\nconst getPrice = (product) => product.price\n\u002F\u002F discount :: Number -> Number, a 10% discount\nconst discount = (price) => price * 0.9\n\u002F\u002F format :: Number -> String\nconst format = (price) => price.toFixed(2)\n\n\u002F\u002F three passes\nconst before = map(format)(map(discount)(map(getPrice)(products)))\nconst passesBefore = passes\n\npasses = 0\n\u002F\u002F your code: after, the same result in a single pass\n\nconsole.log(JSON.stringify(before))\nconsole.log(`passes before: ${passesBefore}`)\nconsole.log(`passes after: ${passes}`)\nconsole.log(`same result: ${JSON.stringify(after) === JSON.stringify(before)}`)",{"ru":7,"en":83},"const products = [\n  { title: 'keyboard', price: 1000 },\n  { title: 'mouse', price: 450 },\n  { title: 'cable', price: 120 },\n]\n\n\u002F\u002F how many times the array was traversed\nlet passes = 0\n\u002F\u002F map :: (a -> b) -> [a] -> [b]\nconst map = (fn) => (arr) => {\n  passes += 1\n  return arr.map(fn)\n}\n\n\u002F\u002F getPrice :: Object -> Number\nconst getPrice = (product) => product.price\n\u002F\u002F discount :: Number -> Number, a 10% discount\nconst discount = (price) => price * 0.9\n\u002F\u002F format :: Number -> String\nconst format = (price) => price.toFixed(2)\n\n\u002F\u002F three passes\nconst before = map(format)(map(discount)(map(getPrice)(products)))\nconst passesBefore = passes\n\npasses = 0\n\u002F\u002F map(format) . map(discount) . map(getPrice) = map(format . discount . getPrice)\n\u002F\u002F R.pipe runs the functions left to right: getPrice first, then discount and format\nconst after = map(R.pipe(getPrice, discount, format))(products)\n\nconsole.log(JSON.stringify(before))\nconsole.log(`passes before: ${passesBefore}`)\nconsole.log(`passes after: ${passes}`)\nconsole.log(`same result: ${JSON.stringify(after) === JSON.stringify(before)}`)",{"ru":7,"en":85},"[\"900.00\",\"405.00\",\"108.00\"]\npasses before: 3\npasses after: 1\nsame result: true",21,{"slug":88,"title":89},"category-theory",{"ru":7,"en":90},"Category theory",{"slug":92,"title":93},"fantasy-land",{"ru":7,"en":94},"Fantasy-land",1792684725073]