Learning path

Full curriculum

Full curriculum

Unit content

Optional and fallible computations as explicit context

A computation can return more than a plain value. It may produce no value, fail with an explanation, or carry some other context together with its result.

Instead of encoding these cases through exceptions or sentinel values, a program can represent them explicitly:

Option<A> = None | Some(A)
Result<E,A> = Error(E) | Success(A)

Chaining with map

If the next step is an ordinary function

$$f:A\to B,$$

map transforms only the successful value while preserving None or Error unchanged.

When the next step can also fail

Suppose parsing text may fail and looking up the parsed identifier may also fail:

parse : String → Result<Error, Id>
lookup : Id → Result<Error, User>

Ordinary function composition does not fit directly because parse returns Result<Error, Id>, not a bare Id.

Unwrapping the result manually at every step produces repetitive branching. The next abstraction, flatMap or bind, captures this repeated rule for continuing only when the previous contextual computation succeeded.

The important idea is not the names Option or Result; it is representing computational context as part of the value's type so composition can account for it explicitly.