Home / Learn / 6 Functions and their results

Release v0.4.0Edition 0.2

6.1 Calls in depth: labels, the order of evaluation, method calls on your own kinds

Page 2 of 9

6.1.1 What a call is, part by part

A call asks a function to do its work. You have written many since chapter 1: opening_hours(), section("Hours", notice: opening_hours()). Here are the words for each part of one, all in one place:

Think of an order form at a supplier: every box on the form has a printed name, "quantity", "unit price", "deliver by", and you write a value in each. Nobody reads the form by the order of the boxes. They read the names. A label is that printed name, carried into the call.

Each example of this chapter is a package, made as chapter 2 explains, and the chapter's download, 06-functions.tar.gz, holds them all.

6.1.2 Why Una labels arguments

The module lines has a function reduced(cents: Int, off_cents: Int), which takes off_cents off a price. Both parameters are whole numbers. Called by place alone, as many languages allow, reduced(1_990, 200) and reduced(200, 1_990) look equally right, and the second one gives a negative price. Una does not accept the first form:

diff
--- a/src/lines.una
+++ b/src/lines.una
@@ -16,3 +16,3 @@
   @console.print("one argument: {half(1_990)} and {half(cents: 1_990)}")
-  @console.print("two arguments: {reduced(1_990, off_cents: 200)}")
+  @console.print("two arguments: {reduced(1_990, 200)}")
   @console.print("every argument labeled: {reduced(cents: 1_990, off_cents: 200)}")
Diagnostic
[U2004] Error: argument 2 of `reduced` needs a label; only the first argument may go without one
    ╭─[ src/lines.una:17:50 ]
    │
 17 │   @console.print("two arguments: {reduced(1_990, 200)}")
    │                                                  ─┬─
    │                                                   ╰─── argument 2 of `reduced` needs a label; only the first argument may go without one
    │
    │ Help: repair 1: label it `off_cents`; edit src/lines.una:17:50..17:53 to "off_cents: 200"
    │
    │ Note: run `una explain U2004` for an explanation
────╯
1 of 1 diagnostics have an edit that `una fix` applies (`una fix --dry-run` lists them)

The first line says which argument needs a label: argument 2 of reduced. The marks point at 200, and the Help line gives the exact repair, off_cents: 200, which una fix . can make for you. With the label, the call reads reduced(1_990, off_cents: 200): the price, then what comes off it. A swap would read reduced(200, off_cents: 1_990), which looks wrong at a glance, to you and to anyone who reviews the code.

6.1.3 How to write a call

The module lines has three functions, and its main calls them in every form a call can take:

src/lines.unacheckrununa
module lines

--- What `units` units cost at `unit_cents` cents each.
pub line_total(unit_cents: Int, units: Int) -> Int = unit_cents * units

--- A price with `off_cents` taken off.
pub reduced(cents: Int, off_cents: Int) -> Int = cents - off_cents

--- Half of an amount, rounded down.
pub half(cents: Int) -> Int = cents / 2

--- Prints one line for each form of a call.
pub main() -> Unit
  uses @console: Console[print]
=
  @console.print("one argument: {half(1_990)} and {half(cents: 1_990)}")
  @console.print("two arguments: {reduced(1_990, off_cents: 200)}")
  @console.print("every argument labeled: {reduced(cents: 1_990, off_cents: 200)}")
  @console.print("labels in any order: {reduced(off_cents: 200, cents: 1_990)}")
  let units = 3
  @console.print("punning: {line_total(4_500, units)}")
  @console.print("a call inside a call: {half(line_total(1_990, units: 2))}")

una run . prints:

Output
one argument: 995 and 995
two arguments: 1790
every argument labeled: 1790
labels in any order: 1790
punning: 13500
a call inside a call: 1990

Each line of main shows one form. The sections below name them.

6.1.3.1 One argument

A call with one argument may leave the label out, since there is nothing to confuse the argument with: half(1_990). Writing it is allowed too: half(cents: 1_990) is the same call.

6.1.3.2 The first argument, then labels

With two or more arguments, the first may go without a label, and every other argument carries one: reduced(1_990, off_cents: 200). An unlabeled first argument always fills the first parameter, here cents, whatever the value is.

6.1.3.3 Every argument labeled

The first argument may carry its label too: reduced(cents: 1_990, off_cents: 200). Write it when the first value alone does not say what it is.

6.1.3.4 Labels in any order

Labeled arguments may come in any order, since each one says which parameter it fills: reduced(off_cents: 200, cents: 1_990) is the same call as the one before it. Write them in the order that reads best.

6.1.3.5 Punning: a name that matches

When an argument is a name equal to its parameter's name, the name is its own label. main binds units with let, then calls line_total(4_500, units), which means line_total(4_500, units: units). This shorthand is called punning. It works from the second argument on: a first argument always fills the first parameter, whatever its name.

6.1.3.6 A call inside a call

An argument can be any expression, such as a sum or another call. An expression is a piece of code that gives a value: 2, cents / 2 and half(1_990) are expressions. In half(line_total(1_990, units: 2)), the inner call gives 3980, and half receives 3980.

6.1.4 Method calls on your own kinds

A call can also be written with its first argument in front, followed by a dot. Section 3.2 showed this method syntax on texts, as in raw.trim. It works the same way on the kinds you declare yourself (chapter 4): lamp.rate() is rate(lamp). The module parcels declares the record kind Parcel, and four functions that take a parcel as their first parameter:

src/parcels.unacheckrununa
module parcels

--- A parcel ready to ship.
kind Parcel
  sku: Text
  grams: Int

--- The rate of a parcel, in cents: 790 up to 2 kg, and 1290 above.
pub rate(parcel: Parcel) -> Int = if parcel.grams <= 2_000 then 790 else 1_290

--- The rate of a parcel with a handling fee added.
pub with_fee(parcel: Parcel, fee: Int) -> Int = parcel.rate + fee

--- The line printed on a parcel's label.
pub label(parcel: Parcel) -> Text = "{parcel.sku}, {parcel.grams} g"

--- The SKU as the warehouse writes it. Its name is also the name of a field of `Parcel`.
pub sku(parcel: Parcel) -> Text = "SKU {parcel.sku}"

--- Prints one line for each form of a method call.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = Parcel(sku: "LAMP-01", grams: 1_200)
  @console.print("a call: {rate(lamp)}, the same as a method: {lamp.rate()}")
  @console.print("without parentheses: {lamp.rate}")
  @console.print("more arguments: {lamp.with_fee(fee: 50)}")
  @console.print("a chain: {lamp.label.to_upper}")
  @console.print("a field: {lamp.sku}, the function: {lamp.sku()}")

una run . prints:

Output
a call: 790, the same as a method: 790
without parentheses: 790
more arguments: 840
a chain: LAMP-01, 1200 G
a field: LAMP-01, the function: SKU LAMP-01
src/parcels.unauna
--- Prints one line for each form of a method call.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = Parcel(sku: "LAMP-01", grams: 1_200)
  @console.print("a call: {rate(lamp)}, the same as a method: {lamp.rate()}")
  @console.print("without parentheses: {lamp.rate}")
  @console.print("more arguments: {lamp.with_fee(fee: 50)}")
  @console.print("a chain: {lamp.label.to_upper}")
  @console.print("a field: {lamp.sku}, the function: {lamp.sku()}")
  1. lamp.rate(). The value before the dot becomes the first argument, without a label: rate(lamp). The checker finds rate among the functions the module can call, as for any call.
  2. lamp.rate. A call of one argument may also drop its empty parentheses.
  3. lamp.with_fee(fee: 50). The other arguments go in the parentheses, with their labels, as in a plain call: with_fee(lamp, fee: 50). The body of with_fee uses method syntax too: parcel.rate + fee.
  4. lamp.label.to_upper. Calls chain from left to right: label(lamp) gives a text, and to_upper, the prelude's function from section 3.2 that writes a text in capital letters, works on that text.
  5. lamp.sku and lamp.sku(). Parcel has a field sku, and the module also has a function sku. Without parentheses, the dot reads the field. With parentheses, it calls the function.

Method syntax changes how a call is written, not what it does: the checker treats lamp.rate and rate(lamp) as the same call, with the same labels and the same types. It reads well where a value goes through steps, order.parcel.rate, and where a function answers a question about one value, parcel.rate.

6.1.5 The order of evaluation

To evaluate an expression is to work out its value. A call evaluates its arguments first, then runs the function's body. Una evaluates them in a fixed order, so that the same program always does the same thing:

Diagnostic
[U7001] Error: line 24 is not in canonical form
    ╭─[ src/parcels.una:24:1 ]
    │
 24 │   let lamp = Parcel(grams: 1_200, sku: "LAMP-01")
    │ ────────────────────────┬────────────────────────
    │                         ╰────────────────────────── line 24 is not in canonical form
    │
    │ Help: repair 1: rewrite in canonical form, as `una fmt` does; edit src/parcels.una:24:1..25:1 to "  let lamp = Parcel(sku: \"LAMP-01\", grams: 1_200)\n"

6.1.5.1 A call that prints stands on its own line

A call of a function that prints may not be an argument. It must be a line of its own, or the value after let. Here pack prints a line and gives back the SKU it packed:

src/packing.unacheckrununa
module packing

--- Prints that a parcel is being packed, and gives back its SKU.
pack(sku: Text) -> Text
  uses @console: Console[print]
=
  @console.print("packing {sku}")
  sku

--- Packs two parcels, then says which went first.
pub main() -> Unit
  uses @console: Console[print]
=
  let first = pack("LAMP-01")
  let second = pack("RUG-07")
  @console.print("{first}, then {second}")
Output
packing LAMP-01
packing RUG-07
LAMP-01, then RUG-07

Each call of pack stands after a let, so the lines it prints come in the order of the lines of main. Put a call of pack inside print, and una check . refuses it:

Diagnostic
[U3013] Error: `pack` has effects or can fail, so it must be the whole expression of a statement or `let`; bind its result with `let` first
    ╭─[ src/packing.una:15:18 ]
    │
 15 │   @console.print(pack("LAMP-01"))
    │                  ───────┬───────
    │                         ╰───────── `pack` has effects or can fail, so it must be the whole expression of a statement or `let`; bind its result with `let` first

The message says what to do: bind the result with let first, then print it. With this rule, every line that does something outside the program is a line of its own, in the order it runs, and a reader never has to work out which of two effects inside one expression comes first. The same rule holds for a call that can fail, which chapter 7 covers.

6.1.6 How a call behaves

6.1.6.1 The checker matches every argument

Before a program runs, una check . matches each argument of each call with one parameter. It reports four kinds of mismatch, each with its own code:

Diagnostic
[U2005] Error: `reduced` has no parameter `discount`
    ╭─[ src/lines.una:17:50 ]
    │
 17 │   @console.print("two arguments: {reduced(1_990, discount: 200)}")
    │                                                  ────┬───
    │                                                      ╰───── `reduced` has no parameter `discount`
    │
    │ Help: repair 1: the parameters that no other argument gives are `off_cents`
Diagnostic
[U2006] Error: parameter `cents` of `reduced` is given twice
Diagnostic
[U2001] Error: `half` takes 1 argument, but 2 are given

6.1.6.2 A parameter holds the argument's value

Inside the body, a parameter is a plain name, like one bound with let (section 2.1): it holds the argument's value for the whole call. A call gives back its result, and that is all it gives back: the caller's own names keep their values. (Section 16.2 shows the one kind of parameter, declared edit, that hands a value back to the caller. Every parameter in this chapter is a plain one.)

6.1.6.3 A function may call itself

A body may call the function it belongs to. This is recursion: the function does one small part of the work, and calls itself for the rest. marked_down takes 10 percent off a price once a week, with the one-line if of section 3.4:

src/markdowns.unauna
--- The price after `weeks` weekly markdowns of 10 percent, each rounded down. The function
--- calls itself, with one week fewer, until no week is left.
pub marked_down(cents: Int, weeks: Int) -> Int = if weeks <= 0 then cents else marked_down(cents * 90 / 100, weeks: weeks - 1)
Output
after 3 weeks: 7290

Follow the calls. marked_down(10_000, weeks: 3) has weeks left, so it calls marked_down(9_000, weeks: 2), which calls marked_down(8_100, weeks: 1), which calls marked_down(7_290, weeks: 0). That call has no week left, so it gives back 7290, and each call before it gives back that value. Every call has one week fewer, so the calls end. A function that never reaches its stopping case calls itself until the run reaches its limit on the depth of calls, and stops with U6003 (section 16.4).

6.1.7 When to label, pun or use a method call

Which to use:

You want to… Write
Call a function of one argument half(1_990): the label is optional
Pass several values the first without a label, the others labeled: reduced(1_990, off_cents: 200)
Make the first value clear too a label on it as well: reduced(cents: 1_990, off_cents: 200)
Pass a name that matches the parameter the name alone, from the second argument on: line_total(4_500, units)
Ask a question about one value, or chain steps on it method syntax: lamp.rate, lamp.label.to_upper
Use the result of a call that prints let it first, then use the name

Name parameters for what they mean to a caller: off_cents reads well at the call, where amount2 would not. A good name and a label together make a call explain itself.

6.1.8 Check yourself: calls

The module shelves asks what to order for one shelf:

src/shelves.unauna
module shelves

--- A shelf of the store: the SKU it holds, and how many units are on it.
kind Shelf
  sku: Text
  on_hand: Int

--- How many units to order so that the shelf holds `target` units again.
pub to_order(shelf: Shelf, target: Int) -> Int = if shelf.on_hand >= target then 0 else target - shelf.on_hand

--- Prints what to order for one shelf, for three targets.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamps = Shelf(sku: "LAMP-01", on_hand: 6)
  let target = 10
  @console.print("{lamps.to_order(target: 4)}")
  @console.print("{to_order(lamps, target)}")
  @console.print("{lamps.to_order(target: target + 5)}")

What does una run . print?

Show the answer
Output
0
4
9

The shelf holds 6 units. lamps.to_order(target: 4) is to_order(lamps, target: 4): the shelf already holds 4 or more, so 0. to_order(lamps, target) puns target, which holds 10: 10 - 6 is 4. lamps.to_order(target: target + 5) evaluates its argument first, 15, and 15 - 6 is 9.

reduced is declared reduced(cents: Int, off_cents: Int). Which of these calls check: reduced(off_cents: 5, cents: 300), reduced(300, 5), reduced(300, off: 5)?

Show the answer

Only the first. Its arguments are both labeled, so their order does not matter. reduced(300, 5) has a second argument without a label, U2004. reduced(300, off: 5) names a parameter reduced does not have, U2005.

Next:6.2 The result of a function: return types, the last line, unused values