23 Maybe and Either

Lesson goal Learn to do without null checks and try/catch 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.

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.

// The problem: the value may be missing
const users = [
  { name: 'Ann', address: { city: 'Riga' } },
  { name: 'Bob' }, // no address
]

// cityOf :: Object -> String
const cityOf = (user) => user.address.city

console.log(cityOf(users[0])) // Riga

try {
  cityOf(users[1]) // Bob has no address: we read city of undefined
} catch (error) {
  console.log(error.name) // TypeError
}

// ?. prevents the crash here, but undefined travels further
const city = users[1].address?.city
console.log(city) // undefined

try {
  city.toUpperCase() // and the program crashes somewhere else
} catch (error) {
  console.log(error.name) // TypeError
}

// an exception is not visible in the signature either: JSON.parse throws on an invalid string
try {
  JSON.parse('{ name: Ann }')
} catch (error) {
  console.log(error.name) // SyntaxError
}

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.

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.

// Maybe a: Just (value) or Nothing
// Sanctuary is available in the playground as S

console.log(S.Just(42)) // Just (42)
console.log(S.Nothing) // Nothing

// head :: [a] -> Maybe a, there may be no first element
console.log(S.head(['Riga', 'Oslo'])) // Just ("Riga")
console.log(S.head([])) // Nothing

// map :: (a -> b) -> Maybe a -> Maybe b
// the function is applied only to Just
const shout = (text) => text.toUpperCase()
console.log(S.map(shout)(S.head(['Riga']))) // Just ("RIGA")
console.log(S.map(shout)(S.head([]))) // Nothing, shout was not called

// the value is taken out once, at the exit
// fromMaybe :: a -> Maybe a -> a
console.log(S.fromMaybe('no city')(S.head([]))) // no city
// maybe :: b -> (a -> b) -> Maybe a -> b, map and fromMaybe in one step
console.log(S.maybe('no city')(shout)(S.head(['Oslo']))) // OSLO

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.

map and chain

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.

// Reading nested data safely

// isObject :: * -> Boolean
const isObject = (x) => typeof x === 'object' && x !== null
// isString :: * -> Boolean
const isString = (x) => typeof x === 'string'

// get :: (* -> Boolean) -> String -> a -> Maybe b
// Just if the property exists and its value passes the predicate, Nothing otherwise
const getAddress = S.get(isObject)('address')
const getCity = S.get(isString)('city')

const ann = { name: 'Ann', address: { city: 'Riga' } }
const bob = { name: 'Bob' }

// map: getCity returns a Maybe, so we get a Maybe inside a Maybe
console.log(S.map(getCity)(getAddress(ann))) // Just (Just ("Riga"))
// chain :: (a -> Maybe b) -> Maybe a -> Maybe b, applies and removes the extra layer
console.log(S.chain(getCity)(getAddress(ann))) // Just ("Riga")
console.log(S.chain(getCity)(getAddress(bob))) // Nothing

// cityName :: a -> String
const cityName = S.pipe([
  getAddress, // Maybe Object
  S.chain(getCity), // getCity returns a Maybe: chain
  S.map((city) => city.toUpperCase()), // toUpperCase returns a string: map
  S.fromMaybe('no city given'),
])

console.log(cityName(ann)) // RIGA
console.log(cityName(bob)) // no city given
console.log(cityName({ address: { city: null } })) // no city given
console.log(cityName(null)) // no city given

// for a whole path there is S.gets
console.log(S.gets(isString)(['address', 'city'])(ann)) // Just ("Riga")

// careful: S.prop is for objects that definitely have the property
try {
  S.prop('address')(bob)
} catch (error) {
  console.log(error.name) // TypeError: the property is missing
}

// and the predicate in S.get is not a formality: S.get also finds properties of the prototype
console.log(S.isJust(S.get(() => true)('toString')(bob))) // true
console.log(S.get(isString)('toString')(bob)) // Nothing

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.

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.

Either: an error with a reason

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.

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.

// Either a b: Left (the reason for the error) or Right (the result)
// Parsing input: string -> JSON -> the age field -> range check

// isNumber :: * -> Boolean
const isNumber = (x) => typeof x === 'number'

// encase :: (a -> b) -> a -> Either e b, where e is what the function threw
// mapLeft :: (e -> c) -> Either e b -> Either c b
// the text of a JSON.parse error differs between browsers, so we take only the name
// parseJson :: String -> Either String *
const parseJson = (text) =>
  S.mapLeft((error) => `not JSON: ${error.name}`)(S.encase(JSON.parse)(text))

// maybeToEither :: a -> Maybe b -> Either a b
// getAge :: * -> Either String Number
const getAge = (data) => S.maybeToEither('no numeric age field')(S.get(isNumber)('age')(data))

// checkRange :: Number -> Either String Number
const checkRange = (age) =>
  age >= 0 && age <= 150 ? S.Right(age) : S.Left(`age out of range: ${age}`)

// readAge :: String -> Either String Number
const readAge = S.pipe([
  parseJson,
  S.chain(getAge), // every step returns an Either: chain
  S.chain(checkRange),
])

console.log(readAge('{"age": 30}')) // Right (30)
console.log(readAge('{"age": 200}')) // Left ("age out of range: 200")

// either :: (a -> c) -> (b -> c) -> Either a b -> c
// report :: Either String Number -> String
const report = S.either((reason) => `Invalid input — ${reason}`)((age) => `Age: ${age}`)

const inputs = ['{"age": 30}', '{ age: 30 }', '{"name": "Ann"}', '{"age": 200}', 'null']
inputs.forEach((input) => console.log(report(readAge(input))))
// Age: 30
// Invalid input — not JSON: SyntaxError
// Invalid input — no numeric age field
// Invalid input — age out of range: 200
// Invalid input — no numeric age field

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/catch somewhere up the stack.

Key points

  • 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.
  • 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.
  • 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.
  • 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.
  • Maybe is for when the reason for absence is obvious, Either for when the calling code needs to know what went wrong.

Exercises

Exercise 1

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.

Starter code

const authors = [
  { name: 'Ann', posts: [{ title: 'Functors', tags: ['fp', 'js'] }] },
  { name: 'Bob', posts: [] },
  { name: 'Eve' },
  { name: 'Max', posts: [{ title: 'Draft', tags: [] }] },
]

// isArray :: * -> Boolean
const isArray = (x) => Array.isArray(x)

// firstTag :: Object -> String
// your code

authors.forEach((author) => console.log(`${author.name}: ${firstTag(author)}`))

Expected output

Ann: #fp
Bob: no tags
Eve: no tags
Max: no tags
Show solution
const authors = [
  { name: 'Ann', posts: [{ title: 'Functors', tags: ['fp', 'js'] }] },
  { name: 'Bob', posts: [] },
  { name: 'Eve' },
  { name: 'Max', posts: [{ title: 'Draft', tags: [] }] },
]

// isArray :: * -> Boolean
const isArray = (x) => Array.isArray(x)

// firstTag :: Object -> String
const firstTag = S.pipe([
  S.get(isArray)('posts'), // Maybe [Object]
  S.chain(S.head), // S.head returns a Maybe: chain
  S.chain(S.get(isArray)('tags')), // S.get returns a Maybe too: chain
  S.chain(S.head), // Maybe String
  S.map((tag) => `#${tag}`), // an ordinary function: map
  S.fromMaybe('no tags'),
])

authors.forEach((author) => console.log(`${author.name}: ${firstTag(author)}`))

Exercise 2

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.

Starter code

// parsePort :: String -> Either String Number
// your code

// describe :: Either String Number -> String
// your code

const inputs = ['8080', 'http', '70000', '443']
inputs.forEach((input) => console.log(`${input}: ${describe(parsePort(input))}`))

Expected output

8080: port 8080
http: invalid — not an integer
70000: invalid — outside 1–65535
443: port 443
Show solution
// checkRange :: Number -> Either String Number
const checkRange = (port) =>
  port >= 1 && port <= 65535 ? S.Right(port) : S.Left('outside 1–65535')

// parsePort :: String -> Either String Number
const parsePort = S.pipe([
  S.parseInt(10), // Maybe Number
  S.maybeToEither('not an integer'), // Nothing becomes a Left with the reason
  S.chain(checkRange), // checkRange returns an Either: chain
])

// describe :: Either String Number -> String
const describe = S.either((reason) => `invalid — ${reason}`)((port) => `port ${port}`)

const inputs = ['8080', 'http', '70000', '443']
inputs.forEach((input) => console.log(`${input}: ${describe(parsePort(input))}`))

Playground

Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.

Connected:
playground
Output
—