Home / Learn / 16 Memory

Release v0.4.0Edition 0.2

16.2 Passing a value in and out: edit

Page 3 of 10

16.2.1 What an edit parameter is

You hand a clerk your shopping list and ask them to add what is missing. They write on it and hand it back. If they cannot finish, they hand back your list exactly as you gave it. An edit parameter works the same way.

A parameter declared edit is passed in and out: the function receives the caller's value, works on it as on a let edit binding, and when it returns, the caller's binding receives the final value. The caller writes edit at the call too, so the change is visible where it happens. When the function fails (chapter 7, Results and failures), the caller's binding keeps the value it had before the call.

16.2.2 Why a function needs to change its caller's value

Without edit, a function that "changes" a shelf returns a new shelf, and the caller must remember to keep it. Here the caller keeps the result under a new name, and prints the old one:

steps/04-no-edit/src/reserve.unacheckrununa
module reserve

--- A shelf of the store: its SKU, the units on it, and the units set aside for orders.
kind Shelf
  sku: Text
  units: Int
  reserved: Int

--- The shelf with `units` more set aside for an order: a new value, which the caller must keep.
reserved(shelf: Shelf, units: Int) -> Shelf = Shelf(sku: shelf.sku, units: shelf.units, reserved: shelf.reserved + units)

pub main() -> Unit
  uses @console: Console[print]
=
  let edit lamps = Shelf(sku: "LAMP-01", units: 5, reserved: 0)
  let updated = reserved(lamps, units: 2)
  @console.print("{lamps.reserved} of {lamps.units} reserved")

una run . prints:

Output
0 of 5 reserved

Nothing was reserved. The reservation went into updated, which nothing reads, and the program printed lamps, which no line changed. The checker cannot know which binding the caller meant to update. And to give back a second result as well, such as a line for a report, the function would have to return a record of both, which every caller unpacks by hand.

An edit parameter removes both problems: the call names the binding it updates, and the function's result is free for something else.

16.2.3 How to write an edit parameter

This step moves stock between the shelves of a SKU. Its kinds:

steps/05-edit-forms/src/transfer.unathe kindsuna
--- A shelf of the store: the SKU it holds and how many units are on it.
kind Shelf
  sku: Text
  units: Int

--- The two shelves of a SKU: the one customers see, and the one in the stockroom.
kind Spot
  front: Shelf
  back: Shelf

kind PickError = | Short(sku: Text, wanted: Int, left: Int)

16.2.3.1 The edit parameter and the call

steps/05-edit-forms/src/transfer.unauna
--- Adds a delivery to a shelf, and gives back how many units it held before.
receive(edit shelf: Shelf, units: Int) -> Int
  ensures shelf.units == old(shelf).units + units
=
  let before = shelf.units
  shelf.units = shelf.units + units
  before
  1. edit shelf: Shelf. The word edit before the parameter's name. In the body, shelf is editable: shelf.units = … changes it.
  2. -> Int. The function still has a result of its own: here, the units the shelf held before. A function that has nothing else to give back returns Unit.
  3. ensures shelf.units == old(shelf).units + units. A promise about what the call did to shelf, which the next part explains.

The call writes edit before the argument: let before = receive(edit front, units: 4). The argument must be an editable binding, here a let edit. When the call returns, front holds the shelf with 4 more units, and before holds the result.

16.2.3.2 Naming the value on entry: old

An ensures clause (section 5.2) states what is true when the function returns. For a plain parameter that is simple, since the parameter never changes. An edit parameter has two values: the one the caller passed in, and the one the function hands back. So inside ensures, the parameter's name means its final value, and old(name) means its value on entry:

old has three rules. It is allowed only in an ensures clause; in the body, the parameter is simply its current value, and a binding made at the start, such as let before = shelf.units, keeps the entry value. It applies only to an edit parameter, since a plain parameter has one value (on a plain parameter, U2012 says "old applies only to an edit parameter, as in old(xs)"). And a requires clause reads the values on entry already, so old is not allowed there. Anywhere else, old(…) is U2012, which old outside ensures shows.

16.2.3.3 The method form

A call can be written as a method on its first argument (chapter 6). Then edit goes before the receiver: edit front.receive(units: 1) is the same call as receive(edit front, units: 1). That is the form of edit shelves.set(…) in section 16.1.

16.2.3.4 Several edit parameters

steps/05-edit-forms/src/transfer.unauna
--- Moves `units` from one shelf to another: two parameters passed in and out.
move(edit source: Shelf, edit target: Shelf, units: Int) -> Unit
  ensures source.units == old(source).units - units
  ensures target.units == old(target).units + units
=
  source.units = source.units - units
  target.units = target.units + units

A function may have several edit parameters, each passed in and out. The call writes edit at each: move(edit back, target: edit front, units: 3). The two arguments must be different bindings.

16.2.3.5 A field as the argument

An edit argument may be a field of an editable binding: receive(edit spot.back, units: 5) changes the back field of spot, and leaves front as it was.

16.2.3.6 The whole run

main makes two shelves and calls each form in turn:

steps/05-edit-forms/src/transfer.unamainuna
pub main() -> Unit
  uses @console: Console[print]
=
  let edit front = Shelf(sku: "LAMP-01", units: 2)
  let edit back = Shelf(sku: "LAMP-01", units: 10)
  let before = receive(edit front, units: 4)
  @console.print("front had {before}, now {front.units}")
  let earlier = edit front.receive(units: 1)
  @console.print("front had {earlier}, now {front.units}")
  move(edit back, target: edit front, units: 3)
  @console.print("front {front.units}, back {back.units}")
  let edit spot = Spot(front: front, back: back)
  let back_before = receive(edit spot.back, units: 5)
  @console.print("the stockroom had {back_before}, now {spot.back.units}")
Output
front had 2, now 6
front had 6, now 7
front 10, back 7
the stockroom had 7, now 12

Follow the front shelf: it starts at 2, receives 4 (6), receives 1 (7), and gets 3 from the back (10). The back shelf starts at 10 and gives 3 (7). The spot record then copies both shelves, and its back receives 5 (12).

16.2.4 Reserving units on a shelf

Back to the reservation of Why a function needs to change its caller's value, with edit. A reservation that asks for more units than are free fails, and the shelf must then stay as it was:

steps/06-edit/src/reserve.unacheckrununa
module reserve

--- A shelf of the store: its SKU, the units on it, and the units set aside for orders.
kind Shelf
  sku: Text
  units: Int
  reserved: Int

kind ReserveError = | NotEnough(sku: Text, wanted: Int, free: Int)

--- Sets `units` aside for an order. On failure the shelf is left as it was.
reserve(edit shelf: Shelf, units: Int) -> Unit
  requires units > 0
  ensures shelf.reserved == old(shelf).reserved + units
  fails ReserveError
=
  let free = shelf.units - shelf.reserved
  if units > free
    fail NotEnough(sku: shelf.sku, wanted: units, free: free)
  shelf.reserved = shelf.reserved + units

pub main() -> Unit
  uses @console: Console[print]
=
  let edit lamps = Shelf(sku: "LAMP-01", units: 5, reserved: 0)
  edit lamps.reserve(units: 2)
    if error use unit
  reserve(edit lamps, units: 9)
    if error use unit
  @console.print("{lamps.reserved} of {lamps.units} reserved")
  1. reserve(edit shelf: Shelf, units: Int) -> Unit. The parameter shelf is passed in and out. The function returns Unit: what it gives back is the changed shelf.
  2. ensures shelf.reserved == old(shelf).reserved + units. The verifier proves the promise on every path that returns.
  3. fail NotEnough(…). A fail inside an if without else ends the function there (section 7.2 covers fail).
  4. edit lamps.reserve(units: 2). The method form. Two units are free to reserve, and the call returns.
  5. reserve(edit lamps, units: 9) with if error use unit. Nine units are more than the three that are free, so the call fails, and the clause carries on with unit (chapter 7 covers the clauses).

una run . prints:

Output
2 of 5 reserved

16.2.5 How an edit call behaves

16.2.5.1 A failed call changes nothing

Two units are reserved, not eleven. The failed call changed nothing: a call that fails leaves every edit argument with the value it had before the call. The function's own assignments are discarded with its failure, so a half-done update never reaches the caller. A loop whose body fails leaves the bindings it updates at their values from before the loop, for the same reason.

Important

Effects are not rolled back. If a function prints, sends a message or writes a file and then fails, those operations stay performed. Only the edit arguments go back to their old values.

16.2.5.2 The rules of an edit argument

An edit argument has three rules, each with its own code:

Rule Code
The call writes edit exactly where the parameter is declared edit, and nowhere else U2020
The argument is a place: an editable binding or a field of one, such as ledger or spot.back U2020 when it is not a place; U2019 when its binding is not editable
No other argument of the same call uses the same binding, even another field of it U2018

The third rule holds even for two different fields. Move stock between the two shelves of one spot:

src/transfer.unadiff
--- a/src/transfer.una
+++ b/src/transfer.una
@@ -59,0 +60 @@
+  move(edit spot.back, target: edit spot.front, units: 2)
Diagnostic
[U2018] Error: `spot` is passed as `edit` in this call, so the call cannot use it again
    ╭─[ src/transfer.una:60:37 ]
    │
 60 │   move(edit spot.back, target: edit spot.front, units: 2)
    │             ────┬────               ─────┬────
    │                 ╰─────────────────────────────── passed as `edit` here
    │                                          │
    │                                          ╰────── `spot` is passed as `edit` in this call, so the call cannot use it again
    │
    │ Note: run `una explain U2018` for an explanation
────╯

The first mark is the first edit argument, and the second is the other use of spot in the same call. Each edit argument is written back when the call returns, so two of them on one binding would both write it, and one change would be lost. Copy one shelf out first, or give spot a function of its own.

16.2.5.3 One call per line

A call with an edit argument, or a take argument (section 16.3), is the whole expression of its statement or let, as a call that can fail is (section 7.3). So it cannot be nested in another call or in a text, and it cannot be wrapped in attempt (U3013, Wrapping an edit call in attempt). A statement call whose result is not Unit binds its result with let, as let before = receive(…) does.

16.2.5.4 Where edit is allowed

16.2.6 Return a new value, or edit

Which to use:

You want… Use
A new value, and the caller keeps the old one A plain parameter, and return the new value
To change the caller's value, with the change visible at the call An edit parameter
To change a value and give back another result, such as a report line An edit parameter, and the other result as the function's result
To change a value only when the whole update succeeds An edit parameter and fails: a failure leaves the argument as it was

16.2.7 Check yourself: a failed call

pick takes units off a shelf, and fails when the shelf holds fewer:

steps/05-edit-forms/src/transfer.unauna
--- Takes `units` off a shelf for an order. It fails when the shelf holds fewer.
pick(edit shelf: Shelf, units: Int) -> Unit
  fails PickError
=
  if units > shelf.units
    fail Short(sku: shelf.sku, wanted: units, left: shelf.units)
  shelf.units = shelf.units - units

--- What is left on a shelf of 5 rugs after the orders ask for each number of `wanted` in turn.
after_picks(wanted: List[Int]) -> Int
=
  let edit shelf = Shelf(sku: "RUG-07", units: 5)
  for units in wanted
    pick(edit shelf, units: units)
      if error use unit
  shelf.units

What does after_picks([2, 4, 3]) return?

Show the answer
Output
rugs left: 0

The shelf starts with 5 rugs. Picking 2 leaves 3. Picking 4 fails, since 4 is more than 3, and the failed call leaves the shelf at 3: if error use unit carries on. Picking 3 leaves 0.

Next:16.3 Giving a value up: take