Home / Learn / 4 Kinds

Release v0.4.0Edition 0.2

4.2 Sum kinds, and is

Page 3 of 10

4.2.1 What a sum kind is

A sum kind is a type whose values are each one of a fixed list of cases. Each case is a variant. A zone is local, national or abroad; a delivery goes to the door, to a locker or to a store. Think of a box on a paper form where you tick exactly one option: "door", "locker" or "store". A sum is that box, and a value is the ticked option.

A variant may carry data of its own, its fields, written in parentheses after its name: a delivery to a locker needs the locker's name, and a delivery to a store needs the store and its opening hour. Each variant has only the fields that make sense for it. A record has all its fields at once; a sum has one variant at a time, with that variant's fields. (The fields of a variant are also called its payload.)

4.2.2 Why a value needs a sum

Without a sum, a status is often written as a text, and the code compares texts:

steps/05-text-status/src/board.unacheckrununa
module board

--- What the store tells a customer about a shipment, from its status written as a text.
customer_note(status: Text) -> Text = if status == "in_transit" then "on its way" else if status == "delivered" then "arrived" else "being packed"

pub main() -> Unit
  uses @console: Console[print]
=
  @console.print(customer_note("in_transit"))
  @console.print(customer_note("in_trnasit"))
  @console.print(customer_note("returned"))

una run . prints:

Output
on its way
being packed
being packed

The program checks and runs, and two of its three lines are wrong. "in_trnasit" is a typo, and "returned" is a status that customer_note does not know. Both fall into the last else of the if (section 3.4), so a parcel on its way and a parcel that came back are both "being packed". Any text is a valid Text, so the checker cannot tell a status from a typo, and nothing points at customer_note when a new status appears.

A sum fixes the list of statuses in one declaration. A misspelt variant is a name that does not exist, which does not check, and a when over the sum must say what to do with every variant (section 4.3).

4.2.3 How to write a sum kind

A sum kind is written kind, its name, =, then its variants separated by |, all on one line. A variant's name starts with a capital letter, as a kind's name does.

4.2.3.1 Variants without fields

steps/06-sums/src/carriers.unauna
--- How far a parcel travels, nearest first.
kind Zone = Local | National | Abroad

Each variant is a value of its own: Local is a Zone, and so are National and Abroad. There are exactly three zones.

4.2.3.2 Variants with fields

steps/06-sums/src/carriers.unauna
--- Where a customer collects a parcel. Each variant carries what that place needs.
kind Delivery = AtDoor | AtLocker(locker: Text) | AtStore(store: Text, opens: Int)

AtDoor has no fields. AtLocker has one, locker, a Text. AtStore has two, store and opens. Fields are written as parameters are: a name, : and a type, separated by commas. Variants with and without fields mix freely in one sum.

4.2.3.3 A sum of one variant

steps/06-sums/src/carriers.unauna
--- A sum with one variant starts with a bar.
kind QuoteError = | NoCarrier

A sum with a single variant starts with |. Without it, kind QuoteError = NoCarrier would be an alias of a type named NoCarrier, as A sum of one variant without its bar shows. Sums of one variant are common for failures, which chapter 7 declares.

4.2.3.4 Building a variant

A variant without fields is written by its name: AtDoor. A variant with fields is built like a record, with its fields labeled: AtStore(store: "Harbour Road", opens: 9). A variant of one field may leave out the label: AtLocker("Station 14") is AtLocker(locker: "Station 14").

4.2.4 Zones and deliveries

The module carriers declares three sum kinds, then builds, tests and compares their variants:

steps/06-sums/src/carriers.unacheckrununa
module carriers

--- How far a parcel travels, nearest first.
kind Zone = Local | National | Abroad

--- Where a customer collects a parcel. Each variant carries what that place needs.
kind Delivery = AtDoor | AtLocker(locker: Text) | AtStore(store: Text, opens: Int)

--- A sum with one variant starts with a bar.
kind QuoteError = | NoCarrier

--- Whether a customer needs a code to collect the parcel.
needs_code(delivery: Delivery) -> Bool = delivery is AtLocker

pub main() -> Unit
  uses @console: Console[print]
=
  let locker = AtLocker(locker: "Station 14")
  let store = AtStore(store: "Harbour Road", opens: 9)
  @console.print("{locker} {store} {AtDoor}")
  @console.print("code needed: {needs_code(locker)} {needs_code(AtDoor)}")
  @console.print("Local before Abroad: {Local < Abroad}; same zone: {National == National}")
  @console.print("{NoCarrier}")
  let later = AtStore(store: "Harbour Road", opens: 10)
  @console.print("{Abroad > National} {store == later} {needs_code(store)}")
  1. kind Zone = Local | National | Abroad. Three variants with no fields. Each is a value of its own: Local is a Zone.
  2. kind Delivery = AtDoor | AtLocker(locker: Text) | AtStore(store: Text, opens: Int). Variants with fields. Only a locker delivery has a locker, and only a store delivery has an opening hour. A value such as "at the door, locker 14" cannot be built.
  3. kind QuoteError = | NoCarrier. A sum with one variant starts with a bar.
  4. delivery is AtLocker. is tests which variant a value is, and gives a Bool. It does not need the fields.
  5. AtLocker(locker: "Station 14"). A variant with fields is built like a record.
  6. Local < Abroad and National == National. Variants without fields are ordered as they are declared, so list them in an order that means something: here, nearest first. == compares any two values of the same kind.

una run . prints, among other lines:

Output
AtLocker("Station 14") AtStore(store: "Harbour Road", opens: 9) AtDoor
code needed: true false
Local before Abroad: true; same zone: true
NoCarrier

A variant with fields prints as you would build it: one field without its label, as AtLocker("Station 14"), and two or more with their labels.

4.2.5 How a sum behaves

4.2.5.1 A variant is tested with is

delivery is AtLocker is true when delivery is a locker delivery, whatever its locker. is names the variant only, never its fields, and works on a variant with fields or without. It gives a Bool, so it fits wherever a condition goes: in an if, after not, or as a function's whole body, as needs_code shows.

4.2.5.2 Equality compares whole values

== and != compare two values of the same sum. They are equal when they are the same variant and every field is equal. AtDoor == AtDoor is true. Two store deliveries to the same store at different hours are not equal.

4.2.5.3 Only variants without fields have an order

<, <=, > and >= work on a sum whose variants have no fields, in the order the declaration lists them: Local < Abroad is true. A sum with fields has no order, since nothing says whether a locker comes before a store.

4.2.5.4 A variant with fields is not a value alone

AtLocker on its own names the variant, not a value: a locker delivery needs its locker. These three changes break the rules of this part:

src/carriers.unadiff
--- a/src/carriers.una
+++ b/src/carriers.una
@@ -7,0 +8,3 @@
+
+--- How a parcel is packed. `AtDoor` is a variant of `Delivery` already.
+kind Packing = Box | AtDoor
@@ -23,0 +27,2 @@
+  let pending = AtLocker
+  let first = locker < store

una check . reports three errors. The first is about the new kind:

Diagnostic
[U1002] Error: `AtDoor` is defined twice in this module, both times as a variant
    ╭─[ src/carriers.una:10:22 ]
    │
  7 │ kind Delivery = AtDoor | AtLocker(locker: Text) | AtStore(store: Text, opens: Int)
    │                 ───┬──
    │                    ╰──── first defined here
    │
 10 │ kind Packing = Box | AtDoor
    │                      ───┬──
    │                         ╰──── `AtDoor` is defined twice in this module, both times as a variant
    │
    │ Note: run `una explain U1002` for an explanation
────╯

A variant's name is unique in its module. The two marks show the two places: AtDoor is first a variant of Delivery, on line 7, and then of Packing, on line 10. A variant's name is a value, so AtDoor must mean one thing in the module. Rename one of them.

The second error is the variant without its fields:

Diagnostic
[U2009] Error: variant `AtLocker` needs its fields: `locker`

The message lists what is missing: the field locker. Write AtLocker(locker: "Station 14"), or, to ask whether a value is a locker delivery, value is AtLocker.

The third is an order on a sum with fields:

Diagnostic
[U2001] Error: `<` orders `Int`, `Text` and variants without fields, not `Delivery`

4.2.5.5 A sum of one variant without its bar

Remove the bar from QuoteError:

src/carriers.unadiff
--- a/src/carriers.una
+++ b/src/carriers.una
@@ -10 +10 @@
-kind QuoteError = | NoCarrier
+kind QuoteError = NoCarrier
Diagnostic
[U1001] Error: cannot find type `NoCarrier` in this module, its imports or the prelude
    ╭─[ src/carriers.una:10:19 ]
    │
 10 │ kind QuoteError = NoCarrier
    │                   ────┬────
    │                       ╰────── cannot find type `NoCarrier` in this module, its imports or the prelude
    │
    │ Note: run `una explain U1001` for an explanation
────╯

Without |, what follows = is a type, so QuoteError is read as an alias, and the checker looks for a type named NoCarrier. It finds none, and reports U1001 at that name. A second U1001 follows where main uses NoCarrier as a value. Both go away when the bar is back: kind QuoteError = | NoCarrier.

4.2.6 A record, a sum or an alias

Which to use:

Your data… Use
Has several parts that are all there at once A record: kind Parcel with fields
Is one of several cases, each with its own data A sum: kind Delivery = AtDoor | AtLocker(locker: Text)
Is one of a fixed list of names, with no data A sum of variants without fields: kind Zone = Local | National | Abroad
Is another type, under a name that says what it holds An alias: kind Sku = Text
Is a yes-or-no flag that may grow a third case A sum from the start, not a Bool
Is a status written as a text A sum: the checker then knows every status

A record and a sum combine. A variant's field can be a record, and a record's field can be a sum, as Parcel has a zone in the day-to-day program.

4.2.7 Check yourself: sums

main ends with three more values:

steps/06-sums/src/carriers.unauna
  let later = AtStore(store: "Harbour Road", opens: 10)
  @console.print("{Abroad > National} {store == later} {needs_code(store)}")

store is AtStore(store: "Harbour Road", opens: 9). Predict the three words the last line prints.

Show the answer
Output
true false false

Abroad > National is true: Abroad is declared after National. store == later is false: the same variant and the same store, but the opening hours differ, and == compares every field. needs_code(store) is false: store is not an AtLocker.

Next:4.3 Taking a sum apart: when