---
title: "8.5 Day-to-day: shipment tracking"
url: https://una-lang.org/en/learn/choices/day-to-day-shipment-tracking/
release: v0.4.0
edition: "0.2"
---

# 8.5 Day-to-day: shipment tracking

## 8.5.1 What the program must do

The store ships parcels by post or by courier. Each parcel has a price for its zone and its weight. Carriers report events: a pickup, a delivery, a parcel that came back. The tracker keeps each shipment's history of events, works out its status from that history, ignores an event that does not fit, such as a pickup scan sent twice, and says how much of a returned parcel's price the store pays back.

The program uses every part of the chapter: `when` with one arm per variant and with range arms, `if` inside arms, a guard that keeps a refund from going below 0, and a recursive kind for the history. Its package is one module, `tracking`, the entry of its `una.toml`, which grants the console.

## 8.5.2 The kinds

The design starts from the kinds. Everything a function does follows from them.

```una include="day-to-day/src/tracking.una#Zone..Change" title="day-to-day/src/tracking.una" caption="the kinds"
--- How far a parcel travels.
pub kind Zone = Local | National | Abroad

--- A parcel ready to ship. `order` is the number on the customer's receipt.
pub kind Parcel
  order: Text
  grams: Int
  zone: Zone

--- An amount of money in cents. It is never negative.
pub kind Cents = Int where it >= 0

--- Who carries a parcel.
pub kind Carrier = Post | Courier

--- Why a parcel came back.
pub kind ReturnReason = Damaged | WrongItem | Refused

--- Where a shipment is. Each state carries what is known in that state, and nothing else.
pub kind Status = Packed | InTransit(carrier: Carrier, tracking: Text) | Delivered(day: Int) | Returned(reason: ReturnReason, day: Int)

--- What a carrier or the warehouse reports about a shipment.
pub kind Event = PickedUp(carrier: Carrier, tracking: Text) | DeliveredOn(day: Int) | CameBack(reason: ReturnReason, day: Int)

--- Every event of a shipment, the latest first. `Start` is the history before any event.
pub kind History = Start | After(event: Event, earlier: History)

--- A value before and after something happened.
pub kind Change[T]
  before: T
  after: T
```

Read them in order:

- **`Zone`, `Carrier` and `ReturnReason`** are sums without fields: fixed lists of names.
- **`Parcel`** is a record of three fields, one of which is a `Zone`. **`Cents`** is the refined kind of [section 5.3](https://una-lang.org/en/learn/contracts/refined-kinds-and-predicates/#s5-3), for amounts that are never negative.
- **`Status`** is the heart of the program. Each variant carries what is known in that state: nothing while packed, a carrier and a tracking number while in transit, a day once delivered, a reason and a day once returned. A delivered status without a day cannot be written.
- **`Event`** is what the outside world reports, and its variants mirror the transitions.
- **`History`** is a recursive kind. `Start` is a history with no event yet. `After(event, earlier)` is the history `earlier` with one more event, the latest. So the latest event is on the outside, and `Start` is at the bottom, where every history ends.
- **`Change[T]`** is a generic record of [section 4.4](https://una-lang.org/en/learn/kinds/generic-kinds-and-constraints/#s4-4): a value before and after something happened.

## 8.5.3 Pricing a parcel

`postage` adds the price of the zone to the supplement for the weight. Each part is a `when`: one arm per zone, and weight bands with range arms and an `else`, as in [section 8.2](https://una-lang.org/en/learn/choices/when-in-full/#s8-2).

```una include="day-to-day/src/tracking.una#postage..weight_cents" title="day-to-day/src/tracking.una"
--- Postage in cents: a price for the zone, and a supplement for the weight.
pub postage(parcel: Parcel) -> Int = zone_cents(parcel.zone) + weight_cents(parcel.grams)

zone_cents(zone: Zone) -> Int
=
  when zone
    is Local -> 300
    is National -> 450
    is Abroad -> 1200

weight_cents(grams: Int) -> Int
=
  when grams
    in 0..500 -> 0
    in 501..2000 -> 150
    else -> 400
```

`zone_cents` has no `else`, so a new zone stops the program from checking until it has a price. `weight_cents` has an `else`, since weights never run out: it is what makes the bands cover every `Int`, negative weights included.

## 8.5.4 Following a history

`apply` takes a status and an event, and gives the next status: one `when` over the event, and in each arm an `if` that tests the status with `is`. An event that does not fit the current status leaves it as it is, so a second pickup scan, or a return before any delivery, changes nothing.

```una include="day-to-day/src/tracking.una#apply..changed" title="day-to-day/src/tracking.una"
--- The status after an event. An event that does not fit the status changes nothing, such
--- as a pickup scan that a carrier sends twice.
pub apply(status: Status, event: Event) -> Status
=
  when event
    is PickedUp(carrier, tracking) -> if status is Packed then InTransit(carrier, tracking) else status
    is DeliveredOn(day) -> if status is InTransit then Delivered(day) else status
    is CameBack(reason, day) -> if status is Delivered then Returned(reason, day) else status

--- The status a history leads to: every event applied, the oldest first.
pub status_of(history: History) -> Status
=
  when history
    is Start -> Packed
    is After(event, earlier) -> apply(status_of(earlier), event)

--- What the latest event of a history did: the status before it, and after it.
pub latest(history: History) -> Change[Status]
=
  when history
    is Start -> Change(before: Packed, after: Packed)
    is After(event, earlier) ->
      let before = status_of(earlier)
      Change(before, after: apply(before, event))

--- Whether something changed. Any type whose values can be compared will do.
pub changed[T: Eq](change: Change[T]) -> Bool = change.before != change.after
```

- **`status_of`** is recursive, as the functions of [section 8.4](https://una-lang.org/en/learn/choices/kinds-that-contain-themselves/#s8-4) are. A history with no event is `Packed`. A history with one more event is the status of the earlier history, with the event applied. So the oldest event is applied first.
- **`latest`** says what the latest event did. Its second arm has several lines: it names the status before the event, then builds the `Change`. `Change(before, after: …)` passes `before` without a label, since a name equal to the field's name counts as its label ([section 6.1](https://una-lang.org/en/learn/functions/calls-in-depth-labels-the-order-of-evaluation-method-calls-on-your-own-kinds/#s6-1)).
- **`changed`** compares the two statuses with `!=`, which needs the `Eq` constraint of section 4.4.

Why ignore an event that does not fit, rather than fail? Carriers resend scans, and a report that arrives late is still a report. The tracker keeps the status it trusts, and the `Change` shows that nothing happened. A function that must stop the work instead would declare a failure, as [chapter 7](https://una-lang.org/en/learn/failure/declaring-a-failure-fails-and-fail/#s7-2) shows.

## 8.5.5 Words for people, and the refund

`describe` has one arm per status and binds the fields it prints. `carrier_name` and `reason_text` turn variants without fields into words. None of them has an `else`, so a new carrier, reason or status is reported at the `when` that must say something about it.

```una include="day-to-day/src/tracking.una#describe..refund" title="day-to-day/src/tracking.una"
--- A status, for a person to read.
pub describe(status: Status) -> Text
=
  when status
    is Packed -> "packed, waiting for a carrier"
    is InTransit(carrier, tracking) -> "with {carrier_name(carrier)}, tracking {tracking}"
    is Delivered(day) -> "delivered on day {day}"
    is Returned(reason, day) -> "returned on day {day}, {reason_text(reason)}"

carrier_name(carrier: Carrier) -> Text
=
  when carrier
    is Post -> "the post"
    is Courier -> "the courier"

reason_text(reason: ReturnReason) -> Text
=
  when reason
    is Damaged -> "damaged"
    is WrongItem -> "the wrong item"
    is Refused -> "refused at the door"

--- What the store pays back for a shipment: all of `paid` for a parcel that came back by the
--- store's fault, `paid` less 600 cents of return postage for a refused one, and nothing
--- otherwise. The guard keeps the refund from going below 0.
pub refund(status: Status, paid: Cents) -> Cents
=
  when status
    is Returned(reason) ->
      if reason == Refused
        if paid > 600 then paid - 600 else 0
      else
        paid
    else -> 0
```

`refund` is the other kind of function: one case matters, and `else` covers the rest. Inside the `Returned` arm, an `if` asks about the reason. A parcel refused at the door is refunded less the 600 cents of return postage, and the inner `if paid > 600 then paid - 600 else 0` is a guard of [section 8.3](https://una-lang.org/en/learn/choices/what-a-branch-proves-guards/#s8-3): in its `then` branch, the verifier knows `paid > 600`, so `paid - 600` is at least 1, and the result is a `Cents`. Without the guard, a refused parcel of 400 cents would be owed -200.

## 8.5.6 Running it

`report` turns the latest event of a history into a line of text. `main` prices a lamp, then builds its history one event at a time: a pickup, the same pickup again, and a delivery. Then it prices a vase sent abroad, which was delivered and then refused.

```una include="day-to-day/src/tracking.una#report..main" title="day-to-day/src/tracking.una"
--- One line of the tracking report.
pub report(order: Text, history: History) -> Text
=
  let change = latest(history)
  if changed(change)
    "{order}: {describe(change.after)}"
  else
    "{order}: no change, still {describe(change.after)}"

pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = Parcel(order: "A-1001", grams: 1200, zone: National)
  @console.print("{lamp.order}: postage {postage(lamp)}")
  let picked = After(event: PickedUp(carrier: Courier, tracking: "CX-4471"), earlier: Start)
  @console.print(report(lamp.order, history: picked))
  let again = After(event: PickedUp(carrier: Courier, tracking: "CX-4471"), earlier: picked)
  @console.print(report(lamp.order, history: again))
  let arrived = After(event: DeliveredOn(day: 3), earlier: again)
  @console.print(report(lamp.order, history: arrived))
  let vase = Parcel(order: "A-1002", grams: 300, zone: Abroad)
  @console.print("{vase.order}: postage {postage(vase)}")
  let sent = After(event: DeliveredOn(day: 8), earlier: After(event: PickedUp(carrier: Post, tracking: "PO-2210"), earlier: Start))
  let back = After(event: CameBack(reason: Refused, day: 12), earlier: sent)
  @console.print("{report(vase.order, history: back)}; refund {refund(status_of(back), paid: 4500)}")
```

Each history is built on the one before it: `again` is `picked` with one more event, and `arrived` is `again` with one more. `una run .` prints the report shown in [What you'll build](https://una-lang.org/en/learn/choices/#what-youll-build). The third line is the duplicate scan: the status stayed `InTransit`, and the report says so instead of pretending something happened. The vase paid 4500 cents and was refused, so the store pays back 4500 - 600 = 3900.

## 8.5.7 The whole program

The whole file, to read in one piece or to copy:

```una include="day-to-day/src/tracking.una" title="day-to-day/src/tracking.una" caption="the whole program" verified="check, run, test"
module tracking

--- How far a parcel travels.
pub kind Zone = Local | National | Abroad

--- A parcel ready to ship. `order` is the number on the customer's receipt.
pub kind Parcel
  order: Text
  grams: Int
  zone: Zone

--- An amount of money in cents. It is never negative.
pub kind Cents = Int where it >= 0

--- Who carries a parcel.
pub kind Carrier = Post | Courier

--- Why a parcel came back.
pub kind ReturnReason = Damaged | WrongItem | Refused

--- Where a shipment is. Each state carries what is known in that state, and nothing else.
pub kind Status = Packed | InTransit(carrier: Carrier, tracking: Text) | Delivered(day: Int) | Returned(reason: ReturnReason, day: Int)

--- What a carrier or the warehouse reports about a shipment.
pub kind Event = PickedUp(carrier: Carrier, tracking: Text) | DeliveredOn(day: Int) | CameBack(reason: ReturnReason, day: Int)

--- Every event of a shipment, the latest first. `Start` is the history before any event.
pub kind History = Start | After(event: Event, earlier: History)

--- A value before and after something happened.
pub kind Change[T]
  before: T
  after: T

--- Postage in cents: a price for the zone, and a supplement for the weight.
pub postage(parcel: Parcel) -> Int = zone_cents(parcel.zone) + weight_cents(parcel.grams)

zone_cents(zone: Zone) -> Int
=
  when zone
    is Local -> 300
    is National -> 450
    is Abroad -> 1200

weight_cents(grams: Int) -> Int
=
  when grams
    in 0..500 -> 0
    in 501..2000 -> 150
    else -> 400

--- The status after an event. An event that does not fit the status changes nothing, such
--- as a pickup scan that a carrier sends twice.
pub apply(status: Status, event: Event) -> Status
=
  when event
    is PickedUp(carrier, tracking) -> if status is Packed then InTransit(carrier, tracking) else status
    is DeliveredOn(day) -> if status is InTransit then Delivered(day) else status
    is CameBack(reason, day) -> if status is Delivered then Returned(reason, day) else status

--- The status a history leads to: every event applied, the oldest first.
pub status_of(history: History) -> Status
=
  when history
    is Start -> Packed
    is After(event, earlier) -> apply(status_of(earlier), event)

--- What the latest event of a history did: the status before it, and after it.
pub latest(history: History) -> Change[Status]
=
  when history
    is Start -> Change(before: Packed, after: Packed)
    is After(event, earlier) ->
      let before = status_of(earlier)
      Change(before, after: apply(before, event))

--- Whether something changed. Any type whose values can be compared will do.
pub changed[T: Eq](change: Change[T]) -> Bool = change.before != change.after

--- A status, for a person to read.
pub describe(status: Status) -> Text
=
  when status
    is Packed -> "packed, waiting for a carrier"
    is InTransit(carrier, tracking) -> "with {carrier_name(carrier)}, tracking {tracking}"
    is Delivered(day) -> "delivered on day {day}"
    is Returned(reason, day) -> "returned on day {day}, {reason_text(reason)}"

carrier_name(carrier: Carrier) -> Text
=
  when carrier
    is Post -> "the post"
    is Courier -> "the courier"

reason_text(reason: ReturnReason) -> Text
=
  when reason
    is Damaged -> "damaged"
    is WrongItem -> "the wrong item"
    is Refused -> "refused at the door"

--- What the store pays back for a shipment: all of `paid` for a parcel that came back by the
--- store's fault, `paid` less 600 cents of return postage for a refused one, and nothing
--- otherwise. The guard keeps the refund from going below 0.
pub refund(status: Status, paid: Cents) -> Cents
=
  when status
    is Returned(reason) ->
      if reason == Refused
        if paid > 600 then paid - 600 else 0
      else
        paid
    else -> 0

--- One line of the tracking report.
pub report(order: Text, history: History) -> Text
=
  let change = latest(history)
  if changed(change)
    "{order}: {describe(change.after)}"
  else
    "{order}: no change, still {describe(change.after)}"

pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = Parcel(order: "A-1001", grams: 1200, zone: National)
  @console.print("{lamp.order}: postage {postage(lamp)}")
  let picked = After(event: PickedUp(carrier: Courier, tracking: "CX-4471"), earlier: Start)
  @console.print(report(lamp.order, history: picked))
  let again = After(event: PickedUp(carrier: Courier, tracking: "CX-4471"), earlier: picked)
  @console.print(report(lamp.order, history: again))
  let arrived = After(event: DeliveredOn(day: 3), earlier: again)
  @console.print(report(lamp.order, history: arrived))
  let vase = Parcel(order: "A-1002", grams: 300, zone: Abroad)
  @console.print("{vase.order}: postage {postage(vase)}")
  let sent = After(event: DeliveredOn(day: 8), earlier: After(event: PickedUp(carrier: Post, tracking: "PO-2210"), earlier: Start))
  let back = After(event: CameBack(reason: Refused, day: 12), earlier: sent)
  @console.print("{report(vase.order, history: back)}; refund {refund(status_of(back), paid: 4500)}")

example "a heavy parcel abroad pays the zone and the weight"
  do postage(Parcel(order: "A-1003", grams: 2500, zone: Abroad))
  expect result == 1600

example "a second pickup scan changes nothing"
  do latest(After(event: PickedUp(carrier: Post, tracking: "PO-1"), earlier: After(event: PickedUp(carrier: Post, tracking: "PO-1"), earlier: Start)))
  expect not changed(result)

example "a parcel cannot come back before it was delivered"
  do status_of(After(event: CameBack(reason: Damaged, day: 2), earlier: Start))
  expect result is Packed

example "a damaged parcel is refunded in full"
  do refund(Returned(reason: Damaged, day: 5), paid: 4500)
  expect result == 4500

example "a refused parcel is refunded less the return postage"
  do refund(Returned(reason: Refused, day: 5), paid: 601)
  expect result == 1

example "a refund never goes below 0"
  do refund(Returned(reason: Refused, day: 5), paid: 400)
  expect result == 0

example "a delivered parcel is not refunded"
  do refund(Delivered(day: 3), paid: 4500)
  expect result == 0
```
