Builtins and Libraries
3.1 Global Utilities
3.2 Numbers
3.3 Strings
3.4 Booleans
3.5 Raw  Array
3.6 Tables
3.7 lists
3.8 sets
3.9 arrays
3.10 string-dict
3.11 option
3.12 pick
3.13 either
3.14 srcloc
3.15 pprint
3.16 s-exp
3.17 s-exp-structs
3.18 image-structs
3.19 image
3.20 world
3.21 gdrive-sheets
3.22 data-source
3.23 reactors
3.24 chart
3.25 plot
3.26 statistics
3.27 math
3.13 either
On this page:
3.13.1 Data types
Either
left
right
is-left
is-right

3.13 either

Usage:
include either
import either as ...

3.13.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