An enum with two choices is different from a boolean

While an enum with two choices might be encoded as a boolean, the semantics differ, and they need to be used in a different way.

Consider a Target enum:

enum Target {

This could be encoded as a boolean (false is staging, true is production), but this limits extensibility.

Consider a function that returns the other target:

fun otherTarget(t: Target): Target

Adding a third option for target would break this function. It would be better to write it to return an array:

fun otherTargets(t: Target): [Target]

If there are only two options for Target, this would be a little strange: it would only ever return an array with one element in it. However, adding a third Target is now easy.

Option types and lists

There is an interesting parallel between option types and lists. Consider an otherTarget function that could return a target or nothing:

fun otherTarget(t: Target): Option<Target>

The analogue for the otherTargets function (returning a list) is that this function could return a list of one element (if there is a target) or an empty list (if there is no target).

See also Minimal language with arrays in Ruby, where false and true are encoded as an empty and a non-empty list, respectively.

Note last edited November 2023.
Backlinks: Perpetual interests.