jonnifyelixir
F2 / F2.07 / sum

F2.07 · part 2 of 3

Sum types

A sum type is one of several variants — one at a time, never together. Elixir spells it with tagged tuples: an atom in the first position names the variant, and the rest carries that variant’s data. The number of values a sum can hold is the sum of its variants’.

The tag is what makes the variants distinguishable. {:circle, r} and {:rectangle, w, h} are both tuples, but the leading :circle or :rectangle tells them apart at a glance and in a pattern match. The most common sum of all is {:ok, value} or {:error, reason}.

One of several shapes

A shape is a circle, a rectangle, or a triangle — each carrying different fields. The tag selects which, and a function can compute over all of them by matching the tag. Pick a variant.

sum type
one of several variants; its values are their sum.
variant
one alternative shape the value can take.
tag
the leading atom naming the variant.
discriminate
tell variants apart — by their tags.

a shape · the tag picks the variant

value {:circle, 5} tag :circle area 3.14159 * r * r = 78.54


      
{:circle, 5} · tag :circle selects the circle clause · area 78.54

Idea

Different variants can carry different fields; the tag says which you have.

F2.07.3 · matching

A function clause per tag handles every variant in one definition.

A sum type lets one value be any of several shapes. The tag is how code knows which it has.

Why they add

Because a value is exactly one variant, the totals do not multiply — they add. A result that is {:ok, a} or {:error, b} can take as many values as a has, plus as many as b has. A nullary variant like :pending contributes exactly one.

Set how many values each variant carries.

{:ok, a} | {:error, b} · totals add

2
3
{:ok, a} {:error, b}


      
2 in :ok + 3 in :error = 5 possible values

Idea

Mutually exclusive options add; a no-field variant adds one.

Elixir

This is why {:ok, _} | {:error, _} models “success or failure” exactly.

Variants add because only one holds at a time. Counting a sum is adding its variants’ values.