[{"data":1,"prerenderedAt":92},["ShallowReactive",2],{"course-en-maybe-either":3},{"lesson":4,"number":83,"prev":84,"next":88},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":53,"exercises":64},"maybe-either",{"ru":7,"en":8},"","Maybe and Either",{"ru":7,"en":10},"Maybe and Either in JavaScript with Sanctuary: reading nested data safely, errors with a reason instead of exceptions, and when to use map or chain.",{"ru":7,"en":12},"Learn to do without null checks and try\u002Fcatch in a pipeline: Maybe from Sanctuary for a value that may be missing, Either for an error with a reason; and understand when a step needs map and when it needs chain.",[14,17,21,23,25,28,30,33,35,38,40,42,44,46,48,51],{"type":15,"ru":7,"en":16},"text","In JS a missing value is usually expressed with null and undefined, and an error with an exception. Both fit poorly into the pipeline from the \"Function composition\" lesson: reading a property of undefined throws a TypeError, and an exception leaves the middle of the chain and skips the remaining steps. The signature cityOf :: Object -> String does not show that the function can crash.",{"type":18,"code":19},"code",{"ru":7,"en":20},"\u002F\u002F The problem: the value may be missing\nconst users = [\n  { name: 'Ann', address: { city: 'Riga' } },\n  { name: 'Bob' }, \u002F\u002F no address\n]\n\n\u002F\u002F cityOf :: Object -> String\nconst cityOf = (user) => user.address.city\n\nconsole.log(cityOf(users[0])) \u002F\u002F Riga\n\ntry {\n  cityOf(users[1]) \u002F\u002F Bob has no address: we read city of undefined\n} catch (error) {\n  console.log(error.name) \u002F\u002F TypeError\n}\n\n\u002F\u002F ?. prevents the crash here, but undefined travels further\nconst city = users[1].address?.city\nconsole.log(city) \u002F\u002F undefined\n\ntry {\n  city.toUpperCase() \u002F\u002F and the program crashes somewhere else\n} catch (error) {\n  console.log(error.name) \u002F\u002F TypeError\n}\n\n\u002F\u002F an exception is not visible in the signature either: JSON.parse throws on an invalid string\ntry {\n  JSON.parse('{ name: Ann }')\n} catch (error) {\n  console.log(error.name) \u002F\u002F SyntaxError\n}",{"type":15,"ru":7,"en":22},"Optional chaining ?. prevents the crash in one place, but undefined travels further and breaks the program where nobody expects it. Checks like if (user && user.address) work, but they spread across the code and one of them is easy to forget. We need a way to make a missing value and an error part of the result, so that they are hard to forget.",{"type":15,"ru":7,"en":24},"Maybe makes a missing value part of the type: a value of Maybe a is either Just (value) or Nothing. You have met it already: in the \"Functional programming\" lesson S.head returned a Maybe, and in the \"Functors and their laws\" lesson we wrote a Maybe-like container ourselves. Sanctuary has a ready-made one: S.Just, S.Nothing and functions to work with them. Maybe is a functor: S.map applies the function only to Just, and Nothing passes through unchanged.",{"type":18,"code":26},{"ru":7,"en":27},"\u002F\u002F Maybe a: Just (value) or Nothing\n\u002F\u002F Sanctuary is available in the playground as S\n\nconsole.log(S.Just(42)) \u002F\u002F Just (42)\nconsole.log(S.Nothing) \u002F\u002F Nothing\n\n\u002F\u002F head :: [a] -> Maybe a, there may be no first element\nconsole.log(S.head(['Riga', 'Oslo'])) \u002F\u002F Just (\"Riga\")\nconsole.log(S.head([])) \u002F\u002F Nothing\n\n\u002F\u002F map :: (a -> b) -> Maybe a -> Maybe b\n\u002F\u002F the function is applied only to Just\nconst shout = (text) => text.toUpperCase()\nconsole.log(S.map(shout)(S.head(['Riga']))) \u002F\u002F Just (\"RIGA\")\nconsole.log(S.map(shout)(S.head([]))) \u002F\u002F Nothing, shout was not called\n\n\u002F\u002F the value is taken out once, at the exit\n\u002F\u002F fromMaybe :: a -> Maybe a -> a\nconsole.log(S.fromMaybe('no city')(S.head([]))) \u002F\u002F no city\n\u002F\u002F maybe :: b -> (a -> b) -> Maybe a -> b, map and fromMaybe in one step\nconsole.log(S.maybe('no city')(shout)(S.head(['Oslo']))) \u002F\u002F OSLO",{"type":15,"ru":7,"en":29},"The value is taken out of a Maybe once, at the exit of the pipeline: S.fromMaybe substitutes a fallback for Nothing, and S.maybe also applies a function to the value in Just, which is map and fromMaybe in one step. Inside the pipeline the value stays in the Maybe, and every step is written as if the value is definitely there.",{"type":31,"ru":7,"en":32},"heading","map and chain",{"type":15,"ru":7,"en":34},"If the function returns an ordinary value, you need map. If it returns a Maybe itself, like S.head or S.get, map gives a Maybe inside a Maybe: Just (Just (\"Riga\")). For such functions there is chain :: (a -> Maybe b) -> Maybe a -> Maybe b: it applies the function and removes the extra layer, and does nothing for Nothing. The rule is simple: the function returns a value, use map; it returns a Maybe, use chain.",{"type":18,"code":36},{"ru":7,"en":37},"\u002F\u002F Reading nested data safely\n\n\u002F\u002F isObject :: * -> Boolean\nconst isObject = (x) => typeof x === 'object' && x !== null\n\u002F\u002F isString :: * -> Boolean\nconst isString = (x) => typeof x === 'string'\n\n\u002F\u002F get :: (* -> Boolean) -> String -> a -> Maybe b\n\u002F\u002F Just if the property exists and its value passes the predicate, Nothing otherwise\nconst getAddress = S.get(isObject)('address')\nconst getCity = S.get(isString)('city')\n\nconst ann = { name: 'Ann', address: { city: 'Riga' } }\nconst bob = { name: 'Bob' }\n\n\u002F\u002F map: getCity returns a Maybe, so we get a Maybe inside a Maybe\nconsole.log(S.map(getCity)(getAddress(ann))) \u002F\u002F Just (Just (\"Riga\"))\n\u002F\u002F chain :: (a -> Maybe b) -> Maybe a -> Maybe b, applies and removes the extra layer\nconsole.log(S.chain(getCity)(getAddress(ann))) \u002F\u002F Just (\"Riga\")\nconsole.log(S.chain(getCity)(getAddress(bob))) \u002F\u002F Nothing\n\n\u002F\u002F cityName :: a -> String\nconst cityName = S.pipe([\n  getAddress, \u002F\u002F Maybe Object\n  S.chain(getCity), \u002F\u002F getCity returns a Maybe: chain\n  S.map((city) => city.toUpperCase()), \u002F\u002F toUpperCase returns a string: map\n  S.fromMaybe('no city given'),\n])\n\nconsole.log(cityName(ann)) \u002F\u002F RIGA\nconsole.log(cityName(bob)) \u002F\u002F no city given\nconsole.log(cityName({ address: { city: null } })) \u002F\u002F no city given\nconsole.log(cityName(null)) \u002F\u002F no city given\n\n\u002F\u002F for a whole path there is S.gets\nconsole.log(S.gets(isString)(['address', 'city'])(ann)) \u002F\u002F Just (\"Riga\")\n\n\u002F\u002F careful: S.prop is for objects that definitely have the property\ntry {\n  S.prop('address')(bob)\n} catch (error) {\n  console.log(error.name) \u002F\u002F TypeError: the property is missing\n}\n\n\u002F\u002F and the predicate in S.get is not a formality: S.get also finds properties of the prototype\nconsole.log(S.isJust(S.get(() => true)('toString')(bob))) \u002F\u002F true\nconsole.log(S.get(isString)('toString')(bob)) \u002F\u002F Nothing",{"type":15,"ru":7,"en":39},"S.get takes a predicate, a property name and an object, and returns Just only if the property exists and the value passes the predicate. The predicate is not a formality: S.get also finds properties of the prototype and the value null, so check the type of the value. S.prop returns the value without a Maybe and throws a TypeError if the property is missing: it suits objects that definitely have the property.",{"type":15,"ru":7,"en":41},"A type that has chain and of, obeying their laws, is called a monad; of puts a value into the container, and for Maybe it is S.Just. Maybe is a monad, the very kind the \"Functional programming\" lesson suggested wrapping the data in so that the composition does not crash. On the diagram from the \"Fantasy-land\" lesson, Monad sits below Applicative and Chain.",{"type":31,"ru":7,"en":43},"Either: an error with a reason",{"type":15,"ru":7,"en":45},"Maybe says that there is no value but not why. Either a b holds either a Left with the reason for the error or a Right with the result (\"right\" as in correct). S.map and S.chain work with Right, while Left passes them by unchanged, like Nothing. At the exit S.either takes two functions, one for Left and one for Right.",{"type":15,"ru":7,"en":47},"S.encase turns a function that throws into a function that returns an Either: a Right with the result or a Left with the caught error. S.maybeToEither gives a reason to absence: Nothing becomes a Left holding the value passed in, and Just becomes a Right. S.mapLeft changes the reason for the error and leaves Right alone.",{"type":18,"code":49},{"ru":7,"en":50},"\u002F\u002F Either a b: Left (the reason for the error) or Right (the result)\n\u002F\u002F Parsing input: string -> JSON -> the age field -> range check\n\n\u002F\u002F isNumber :: * -> Boolean\nconst isNumber = (x) => typeof x === 'number'\n\n\u002F\u002F encase :: (a -> b) -> a -> Either e b, where e is what the function threw\n\u002F\u002F mapLeft :: (e -> c) -> Either e b -> Either c b\n\u002F\u002F the text of a JSON.parse error differs between browsers, so we take only the name\n\u002F\u002F parseJson :: String -> Either String *\nconst parseJson = (text) =>\n  S.mapLeft((error) => `not JSON: ${error.name}`)(S.encase(JSON.parse)(text))\n\n\u002F\u002F maybeToEither :: a -> Maybe b -> Either a b\n\u002F\u002F getAge :: * -> Either String Number\nconst getAge = (data) => S.maybeToEither('no numeric age field')(S.get(isNumber)('age')(data))\n\n\u002F\u002F checkRange :: Number -> Either String Number\nconst checkRange = (age) =>\n  age >= 0 && age \u003C= 150 ? S.Right(age) : S.Left(`age out of range: ${age}`)\n\n\u002F\u002F readAge :: String -> Either String Number\nconst readAge = S.pipe([\n  parseJson,\n  S.chain(getAge), \u002F\u002F every step returns an Either: chain\n  S.chain(checkRange),\n])\n\nconsole.log(readAge('{\"age\": 30}')) \u002F\u002F Right (30)\nconsole.log(readAge('{\"age\": 200}')) \u002F\u002F Left (\"age out of range: 200\")\n\n\u002F\u002F either :: (a -> c) -> (b -> c) -> Either a b -> c\n\u002F\u002F report :: Either String Number -> String\nconst report = S.either((reason) => `Invalid input — ${reason}`)((age) => `Age: ${age}`)\n\nconst inputs = ['{\"age\": 30}', '{ age: 30 }', '{\"name\": \"Ann\"}', '{\"age\": 200}', 'null']\ninputs.forEach((input) => console.log(report(readAge(input))))\n\u002F\u002F Age: 30\n\u002F\u002F Invalid input — not JSON: SyntaxError\n\u002F\u002F Invalid input — no numeric age field\n\u002F\u002F Invalid input — age out of range: 200\n\u002F\u002F Invalid input — no numeric age field",{"type":15,"ru":7,"en":52},"When to choose which. Maybe is for when a missing value is normal and the reason is obvious: a search, the first element, an optional field. Either is for when the calling code needs to know what went wrong: parsing and validating input, business rules, messages to the user. In both cases absence and errors become ordinary values: they are visible in the signature, they can be passed on and shown, instead of being caught with try\u002Fcatch somewhere up the stack.",[54,56,58,60,62],{"ru":7,"en":55},"Maybe a is Just (value) or Nothing. A missing value becomes part of the type instead of null and undefined, and the value is taken out once at the exit with S.fromMaybe or S.maybe.",{"ru":7,"en":57},"If the function returns an ordinary value, use S.map; if it returns a Maybe or an Either, use S.chain: it applies the function and removes the extra layer.",{"ru":7,"en":59},"S.get(predicate)(name)(object) reads a property safely and checks the type of the value, while S.prop throws a TypeError if the property is missing.",{"ru":7,"en":61},"Either a b is Left (the reason for the error) or Right (the result). S.encase turns an exception into a Left, S.maybeToEither gives a reason to absence, and S.either handles both cases at the exit.",{"ru":7,"en":63},"Maybe is for when the reason for absence is obvious, Either for when the calling code needs to know what went wrong.",[65,74],{"task":66,"starter":68,"solution":70,"expected":72},{"ru":7,"en":67},"Write firstTag: it returns the first tag of the author's first post with a hash in front, or the string \"no tags\" if there are no posts or no tags. The posts field may be missing, and the posts and tags arrays may be empty. Build a pipeline from S.get, S.head, S.chain, S.map and S.fromMaybe, and decide for each step whether it needs map or chain.",{"ru":7,"en":69},"const authors = [\n  { name: 'Ann', posts: [{ title: 'Functors', tags: ['fp', 'js'] }] },\n  { name: 'Bob', posts: [] },\n  { name: 'Eve' },\n  { name: 'Max', posts: [{ title: 'Draft', tags: [] }] },\n]\n\n\u002F\u002F isArray :: * -> Boolean\nconst isArray = (x) => Array.isArray(x)\n\n\u002F\u002F firstTag :: Object -> String\n\u002F\u002F your code\n\nauthors.forEach((author) => console.log(`${author.name}: ${firstTag(author)}`))",{"ru":7,"en":71},"const authors = [\n  { name: 'Ann', posts: [{ title: 'Functors', tags: ['fp', 'js'] }] },\n  { name: 'Bob', posts: [] },\n  { name: 'Eve' },\n  { name: 'Max', posts: [{ title: 'Draft', tags: [] }] },\n]\n\n\u002F\u002F isArray :: * -> Boolean\nconst isArray = (x) => Array.isArray(x)\n\n\u002F\u002F firstTag :: Object -> String\nconst firstTag = S.pipe([\n  S.get(isArray)('posts'), \u002F\u002F Maybe [Object]\n  S.chain(S.head), \u002F\u002F S.head returns a Maybe: chain\n  S.chain(S.get(isArray)('tags')), \u002F\u002F S.get returns a Maybe too: chain\n  S.chain(S.head), \u002F\u002F Maybe String\n  S.map((tag) => `#${tag}`), \u002F\u002F an ordinary function: map\n  S.fromMaybe('no tags'),\n])\n\nauthors.forEach((author) => console.log(`${author.name}: ${firstTag(author)}`))",{"ru":7,"en":73},"Ann: #fp\nBob: no tags\nEve: no tags\nMax: no tags",{"task":75,"starter":77,"solution":79,"expected":81},{"ru":7,"en":76},"A port in a settings form arrives as a string. Write parsePort :: String -> Either String Number: if the string is not an integer, return a Left with the reason \"not an integer\"; if the number is outside the range 1–65535, a Left with the reason \"outside 1–65535\"; otherwise a Right (port). S.parseInt(10)(text) returns Just (an integer) or Nothing. Use S.maybeToEither and S.chain, and build the line for each input in describe with S.either.",{"ru":7,"en":78},"\u002F\u002F parsePort :: String -> Either String Number\n\u002F\u002F your code\n\n\u002F\u002F describe :: Either String Number -> String\n\u002F\u002F your code\n\nconst inputs = ['8080', 'http', '70000', '443']\ninputs.forEach((input) => console.log(`${input}: ${describe(parsePort(input))}`))",{"ru":7,"en":80},"\u002F\u002F checkRange :: Number -> Either String Number\nconst checkRange = (port) =>\n  port >= 1 && port \u003C= 65535 ? S.Right(port) : S.Left('outside 1–65535')\n\n\u002F\u002F parsePort :: String -> Either String Number\nconst parsePort = S.pipe([\n  S.parseInt(10), \u002F\u002F Maybe Number\n  S.maybeToEither('not an integer'), \u002F\u002F Nothing becomes a Left with the reason\n  S.chain(checkRange), \u002F\u002F checkRange returns an Either: chain\n])\n\n\u002F\u002F describe :: Either String Number -> String\nconst describe = S.either((reason) => `invalid — ${reason}`)((port) => `port ${port}`)\n\nconst inputs = ['8080', 'http', '70000', '443']\ninputs.forEach((input) => console.log(`${input}: ${describe(parsePort(input))}`))",{"ru":7,"en":82},"8080: port 8080\nhttp: invalid — not an integer\n70000: invalid — outside 1–65535\n443: port 443",23,{"slug":85,"title":86},"fantasy-land",{"ru":7,"en":87},"Fantasy-land",{"slug":89,"title":90},"neural-networks",{"ru":7,"en":91},"Neural networks and category theory",1792684725079]