3.1 General-Purpose Libraries
3.1.1 Global Utilities
3.1.2 Numbers
3.1.3 Strings
3.1.4 Booleans
3.1.5 option
3.1.6 either
3.1.7 pick
3.1.8 lists
3.1.9 sets
3.1.10 arrays
3.1.11 string-dict
3.1.12 Tables
3.1.13 gdrive-sheets
3.1.14 csv
3.1.15 color
3.1.16 The image libraries
3.1.17 reactors
3.1.18 chart
3.1.19 plot
3.1.20 statistics
3.1.21 math
3.1.22 matrices
3.1.23 Timing
3.1.24 fetch
3.1.25 filesystem
3.1.6 either
On this page:
3.1.6.1 Data types
Either
left
right
is-left
is-right
3.1.6 either🔗

Usage:
include either
import either as ...

3.1.6.1 Data types🔗

data Either<a, b>:
| left(v :: a)
| right(v :: b)
end

left :: (v :: a) -> Either<a, b>

right :: (v :: b) -> Either<a, b>

is-left :: (val :: Any) -> Boolean

is-right :: (val :: Any) -> Boolean

Either implements a functional programming idiom that is often used when a function may return either a meaningful value or an error message. By convention, the left variant is used to return an error, usually as a string, and the right variant returns a valid value.

The following example is based on a function that searches for a student with a specific numeric id in a list. find-person-from-id returns Either a valid Person as right or one of two error messages as Strings in left.

Examples:

import either as E data Person: | student(id :: Number, name :: String) end people = [list: student(001, "Charlie Brown"), student(002, "Sally Brown"), student(003, "Lucy van Pelt"), student(003, "Linus van Pelt")] fun find-person-from-id(p :: List<Person>, i :: Number) -> E.Either: results = p.filter(lam(a): a.id == i end) result-count = results.length() ask: | result-count == 0 then: E.left("Not found error.") | result-count == 1 then: E.right(results.get(0)) | otherwise: E.left("Duplicate ID error.") end where: find-person-from-id(people, 007) is E.left("Not found error.") find-person-from-id(people, 001) is E.right(student(001, "Charlie Brown")) find-person-from-id(people, 003) is E.left("Duplicate ID error.") end

Typically, the Either variants are processed by a cases expression, for example:

Examples:

fun search(id :: Number): doc: "Hypothetical function calls resulting from either result." result = find-person-from-id(people, id) cases(E.Either) result: | left(s) => display-error-dialog(s) | right(p) => display-person(p) end end