87Data Lens
Common encodings for alternatives
type DigitalPayment = CreditCard | GiftCard | App;
type AnalogPayment = Cash | LoyaltyCard | Comped;
type Payment = DigitalPayment | AnalogPayment;
interface Size {
name: string;
}
type Size = "super" |
"mega" |
"galactic";
Union type
enum Size {
super = "super",
mega = "mega",
galactic = "galactic",
}
Enum
Interface and classes
1
2
3
Natural numbers
Super
Mega
Galactic
Alternatives are encoded easily in most programming
languages. Here are some common language features that
share the “choice of one among many” structure. In this
case, we are encoding the size:
class Super implements Size {
name = "super";
}
class Mega implements Size {
name = "mega";
}
class Galactic implements Size {
name = "galactic";
}
We can encode alternatives as natural
numbers because natural numbers them-
selves are an alternative.
Numbers also have a natural ordering, like
size. The biggest mis-t is that the number
of sizes is nite while natural numbers are
innite.
type NatNumber = 1 | 2 | 3 | ...;
Remember, we can use these language features to encode
alternatives because they have the same “choose one
among many” structure as alternatives.
Adding structure
Sum types give us lots of options for how to encode an
alternative without losing t. Besides using a different
language feature, we could also introduce a new layer of
structure. For instance, we could encode payment like
this and get the same number of states: