Home / Learn / 10 Collections
10.2 Functions as values, and lambdas
Page 3 of 11
10.2.1 What a function value is
So far, a function was something you call. In Una, a function is also a value, like a number or a text: you can pass it to another function as an argument, name it with let, and get it back as a result. Think of a recipe card. You can follow it yourself, but you can also hand the card to someone else and let them follow it when the time comes. Passing a function is handing over the card.
Two new terms name the parts:
- A function type is the type of a function value.
fn(Int) -> Intis the type of every function that takes oneIntand gives back anInt, whatever its name. - A lambda is a function written in place, without a name, where a value goes:
fn(cents) -> cents - 500. The name comes from mathematics; other books call it an anonymous function.
10.2.2 Why pass a function
A store keeps changing its promotions. Here are three, each written as its own function:
module rules
--- The price after the clearance rule, 500 cents off, kept between 0 and the price.
clearance_price(cents: Int) -> Int = max(0, b: min(cents - 500, b: cents))
--- The price after the rule "ends in 99", kept between 0 and the price.
ends_in_99_price(cents: Int) -> Int = max(0, b: min((cents + 1) / 100 * 100 - 1, b: cents))
--- The price after the members' rule, 20 percent off, kept between 0 and the price.
members_price(cents: Int) -> Int = max(0, b: min(cents * 80 / 100, b: cents))
--- Prints a price under three rules.
pub main() -> Unit
uses @console: Console[print]
=
@console.print("{clearance_price(2_050)} {ends_in_99_price(2_050)} {members_price(2_050)}")
@console.print("{clearance_price(300)} {ends_in_99_price(300)} {members_price(300)}")una run . prints:
1550 1999 1640
0 299 240Each function does two things: it applies its rule, and it keeps the result between 0 and the price, with max and min from the prelude (min gives the smaller of its two arguments, as max gives the larger). The second part is the same in all three, copied. A fourth promotion means a fourth copy, and a change to that part, such as a minimum price, must be made in every copy.
What differs between the three is only the rule. If the rule could be a parameter, the part that keeps the price in bounds would be written once, and each promotion would be just its rule. A function type makes that possible.
10.2.3 How to write function values
10.2.3.1 A function type: fn(Int) -> Int
Write fn, the parameter types in parentheses, ->, and the result type. A parameter of a function type is declared like any other parameter, and called like any function:
--- A price after a pricing rule: a function from a price in cents to a price in cents.
pub priced(cents: Int, rule: fn(Int) -> Int) -> Int = rule(cents)rule is a parameter whose value is a function. rule(cents) calls whatever function the caller passed.
10.2.3.2 Passing a named function
Pass a declared function by its name, without parentheses: priced(2_050, rule: ends_in_99). With parentheses, ends_in_99(2_050) would call it, and pass its result, a number. Without them, the function itself is passed, to be called later by priced. The function's type must match the parameter's: ends_in_99 takes an Int and gives back an Int, so it fits fn(Int) -> Int.
10.2.3.3 A lambda
fn(parameters) -> expression writes a function in place:
@console.print("{priced(2_050, rule: fn(cents) -> cents - 500)}")fn(cents) -> cents - 500 takes cents and gives cents - 500. Its parameter's type, Int, comes from the type of rule, so you need not write it. Its body is one expression, after ->.
10.2.3.4 A lambda with its types written
Where nothing says what a lambda's parameters are, write their types, as in a header. A lambda named with let needs them:
let clearance = fn(cents: Int) -> cents - 500
@console.print("clearance: {clearance(2_000)}")clearance: 1500clearance is now a name for a function, called like one: clearance(2_000).
10.2.3.5 Several parameters
A function type may take several parameters, fn(Int, Int) -> Int, and a lambda then names each one. A function value is called with its arguments in order, with no labels, since its type gives its parameters no names:
--- The price of a line under a rule for whole lines: a function of two parameters.
line_price(unit_cents: Int, units: Int, rule: fn(Int, Int) -> Int) -> Int = rule(unit_cents, units) @console.print("3 for 2: {line_price(1_990, units: 3, rule: fn(cents, units) -> cents * (units - units / 3))}")3 for 2: 3980The lambda prices "3 for 2": of 3 units, one is free, so the line pays 1990 × 2 = 3980.
10.2.3.6 A function that gives back a function
The result type can be a function type too. Such a function builds functions:
--- A promotion that takes `percent` percent off: a function that returns a function.
percent_off(percent: Int) -> fn(Int) -> Int = fn(cents) -> cents * (100 - percent) / 100 let ten_off = percent_off(10)
let quarter_off = percent_off(25)
@console.print("10 off: {ten_off(2_000)}, 25 off: {quarter_off(2_000)}")10 off: 1800, 25 off: 1500percent_off(10) gives back a lambda that takes 10 percent off, and percent_off(25) one that takes 25. The lambda uses percent, a parameter of the function that made it, and keeps its value after percent_off has returned.
10.2.4 Pricing rules passed as values
The module pricing passes a named function and two lambdas to the same parameter:
module pricing
--- A price after a pricing rule: a function from a price in cents to a price in cents.
pub priced(cents: Int, rule: fn(Int) -> Int) -> Int = rule(cents)
--- A rule: the price rounded down to the next price that ends in 99 cents.
pub ends_in_99(cents: Int) -> Int = (cents + 1) / 100 * 100 - 1
--- Prints a price under three rules.
pub main() -> Unit
uses @console: Console[print]
=
@console.print("{priced(2_050, rule: ends_in_99)}")
@console.print("{priced(2_050, rule: fn(cents) -> cents - 500)}")
let markup = 120
@console.print("{priced(2_050, rule: fn(cents) -> cents * markup / 100)}")priced(cents: Int, rule: fn(Int) -> Int) -> Int = rule(cents). A parameter of a function type, called like any function.priced(2_050, rule: ends_in_99). A named function passed as a value: no parentheses after its name, since it is not called here.fn(cents) -> cents - 500. A lambda. Its parameter's type comes from the type ofrule.fn(cents) -> cents * markup / 100. A lambda that usesmarkup, a name from around it.
una run . prints:
1999
1550
2460priced knows nothing about promotions: it applies whatever rule it is given. A new rule is a new function or a new lambda, and priced never changes.
10.2.5 Functions that may fail
Section 7.2 showed fails of p, the header line that says a function fails when, and only when, its function parameter p fails. With function values in hand, here are the ways a function you pass may fail. The step of this part prices a cart with several price functions:
--- Why a price list has no price for a SKU.
kind PriceError = | NoPrice(sku: Text)
--- The store's price list. It knows two SKUs, and fails for any other.
listed(sku: Text) -> Int
fails PriceError
=
if sku == "LAMP-01"
1990
else if sku == "DESK-02"
15900
else
fail NoPrice(sku)
--- The total of a cart, each SKU priced by `price`. It fails when, and only when, `price`
--- fails, and with the same error kind.
pub total_with(skus: List[Text], price: fn(Text) -> Int) -> Int
fails of price
=
let edit total = 0
for sku in skus
let cents = price(sku)
if error pass
total = total + cents
total
--- The total of a cart, each SKU priced by `price`, whose type says that it may fail.
pub strict_total(skus: List[Text], price: fn(Text) -> Int fails PriceError) -> Int
fails PriceError
=
let edit total = 0
for sku in skus
let cents = price(sku)
if error pass
total = total + cents
total let cart = ["LAMP-01", "GIFT-50"]
let flat = total_with(cart, price: fn(sku) -> 500)
let no_gifts = total_with(cart, price: fn(sku) -> if sku.starts_with(prefix: "GIFT-") then fail NoPrice(sku) else 500)
if error use -1
let known = total_with(["LAMP-01", "DESK-02"], price: listed)
if error use -1
@console.print("{flat} {no_gifts} {known}")
let strict = strict_total(["LAMP-01"], price: fn(sku) -> 500)
if error use -1
@console.print("strict: {strict}")1000 -1 17890
strict: 50010.2.5.1 A lambda that fails, for a fails of parameter
total_with declares fails of price. So a lambda passed for price may fail, as its body says: fn(sku) -> if sku.starts_with(prefix: "GIFT-") then fail NoPrice(sku) else 500 refuses gift cards with fail, and prices every other SKU at 500. The call then fails as the lambda does, and takes a clause, here if error use -1. The cart holds GIFT-50, so this call gives -1. A lambda that cannot fail, such as fn(sku) -> 500, needs no clause, and its call gives 1000.
A lambda's body is one line, so it cannot hold a clause under a call. A lambda whose body calls a function that can fail, such as listed, does not check; pass listed by its name instead, as the third call does.
10.2.5.2 fails in a function type
A function type may also say that the function fails: fn(Text) -> Int fails PriceError. strict_total takes such a parameter. Every call of price in its body may then fail, so strict_total declares fails PriceError itself, and every call of strict_total takes a clause, even with a function that never fails, as fn(sku) -> 500. That is why fails of exists: with it, a caller who passes a function that cannot fail writes no clause.
10.2.5.3 A failing lambda is passed, never kept
A lambda that can fail exists only as an argument: it can be passed, but not named with let, given back as a result or stored in a record. Name the gift-card rule with let before passing it:
--- a/src/prices.una
+++ b/src/prices.una
@@ -45,3 +45,4 @@
let flat = total_with(cart, price: fn(sku) -> 500)
- let no_gifts = total_with(cart, price: fn(sku) -> if sku.starts_with(prefix: "GIFT-") then fail NoPrice(sku) else 500)
+ let no_gifts_rule = fn(sku: Text) -> if sku.starts_with(prefix: "GIFT-") then fail NoPrice(sku) else 500
+ let no_gifts = total_with(cart, price: no_gifts_rule)
if error use -1[U3009] Error: this code declares no error kind, so it cannot fail with `NoPrice`; declare `fails` in its header
╭─[ src/prices.una:46:86 ]
│
46 │ let no_gifts_rule = fn(sku: Text) -> if sku.starts_with(prefix: "GIFT-") then fail NoPrice(sku) else 500
│ ───┬───
│ ╰───── this code declares no error kind, so it cannot fail with `NoPrice`; declare `fails` in its headerThe message says that the code declares no error kind: a lambda named with let has no type that lets it fail, so it is pure, and its fail is refused. Write the lambda at the call, or declare a named function with fails PriceError and pass its name.
10.2.6 A promotion that cannot overcharge
A shipping report of the store charges each order by weight and zone, then applies promotions. The promotions go through one function, promoted, which keeps every charge between 0 and the charge before the promotion:
--- A promotion: half the charge, rounded up to a whole cent.
pub half_off(charge: Int) -> Int = (charge + 1) / 2
--- The charge after a promotion. Whatever the promotion computes, the customer never pays
--- more than the charge, and never less than nothing.
pub promoted(charge: Int, promotion: fn(Int) -> Int) -> Int
requires charge >= 0
ensures result >= 0 and result <= charge
=
max(0, b: min(promotion(charge), b: charge)) let charge = quote(4_500, grams: 3_200, zone: 3)
show(1044, charge)
let weekend = promoted(charge, promotion: half_off)
show(1045, charge: weekend)
let members = promoted(lamps, promotion: fn(cents) -> cents * 80 / 100)
show(1046, charge: members)order 1044: 30.90
order 1045: 15.45
order 1046: 6.32This is the design that Why pass a function asked for. max and min are written once, in promoted, and its ensures line promises every caller a charge from 0 to charge, whatever the promotion computes. half_off is passed by its name, and the members' rule of 20 percent off as a lambda, on lamps, the 790 cents of order 1042: 790 × 80 / 100 = 632, printed as 6.32. The day-to-day program of this chapter passes lambdas in the same way, to map, fold and first_where.
10.2.7 How function values behave
10.2.7.1 Where a lambda gets its types
A lambda gets its parameter types from where it is used: the parameter it is passed to says fn(Int) -> Int, so cents is an Int. Named with let on its own line, a lambda has no such place, and the checker asks for the type, with U2010 (A lambda named with let, in Common mistakes). Write fn(cents: Int) -> …, or pass the lambda straight to the function that uses it.
10.2.7.2 A lambda captures values
A lambda may use names from around it, such as markup or percent. It captures them: it keeps a copy of the value each one has when the lambda is made. A later assignment to a let edit name does not reach a lambda made before it, and the lambda cannot assign the name itself. A lambda's parameter cannot take a name already used around it, since Una gives a name one meaning in a block (section 9.2).
10.2.7.3 A function type without uses is pure
fn(Int) -> Int has no uses, so a function of that type cannot print or touch anything outside the program. Pass a function that prints where such a type is expected, and the call does not check:
--- a/src/pricing.una
+++ b/src/pricing.una
@@ -8,2 +8,8 @@
+-- A rule that prints the price it is given. It is private, so its `uses` is inferred.
+logged(cents: Int) -> Int
+=
+ @console.print("pricing {cents}")
+ cents
+
--- Prints a price under three rules.
@@ -12,3 +18,3 @@
=
- @console.print("{priced(2_050, rule: ends_in_99)}")
+ @console.print("{priced(2_050, rule: logged)}")
@console.print("{priced(2_050, rule: fn(cents) -> cents - 500)}")[U3003] Error: this function uses `@console: ?[print]`, which the expected function type does not allow
╭─[ src/pricing.una:19:40 ]
│
19 │ @console.print("{priced(2_050, rule: logged)}")
│ ───┬──
│ ╰──── this function uses `@console: ?[print]`, which the expected function type does not allowThe mark points at logged, where it is passed: it uses @console, which fn(Int) -> Int does not allow. In @console: ?[print], the ? stands for the capability's type, Console, which the checker does not name in this message. A first diagnostic, U3001, says that no caller of logged gives it the console, since it is only passed, never called from main. So a promotion passed to priced is a pure function, whoever wrote it: its type guarantees it. A function may also accept a parameter that prints, with the header line uses of, which section 12.4 teaches.
10.2.7.4 A lambda's body is one expression
A lambda holds one expression, on one line. A rule that needs several lines, a let or a clause is a named function, passed by its name. A named function can also have its own examples, which a lambda cannot.
10.2.7.5 Functions cannot be compared
== compares two values of the same type, but not two functions: whether two functions always give the same answer is not something a program can decide. Comparing two functions with == is U2001, whose message says that the values hold functions. Compare what the functions give back instead.
10.2.8 A named function or a lambda
Which to use:
| You want… | Use |
|---|---|
| A rule used in several places, or one worth an example | A named function, passed by its name |
| A one-line rule used once, at the call | A lambda, fn(x) -> … |
| A rule that reads a value from around the call | A lambda, which captures it |
| A rule that needs several lines, or calls a function that can fail | A named function |
| A family of rules that differ by a number, such as a percentage | A function that gives back a lambda, such as percent_off |
| A parameter that may fail exactly when its argument does | fails of the parameter |
Lists use function values everywhere: map, filter and fold, in section 10.3, take a function that says what to do with each element.
10.2.9 Check yourself: function values
main in promotions builds one more rule out of ten_off:
let twice = fn(cents: Int) -> ten_off(ten_off(cents))
@console.print("10 off twice: {twice(1_000)}")Predict what it prints.
Show the answer
10 off twice: 810twice calls ten_off on the result of ten_off. 1000 less 10 percent is 900, and 900 less 10 percent is 810.
Then main makes a lambda that reads an editable name, and changes the name:
let edit markup = 120
let raised = fn(cents: Int) -> cents * markup / 100
markup = 200
@console.print("markup: {raised(1_000)}, markup now {markup}")Predict the line it prints.
Show the answer
markup: 1200, markup now 200raised captured markup when it was made, with the value 120, so it gives 1000 × 120 / 100 = 1200. The assignment of 200 changes the name, which the last part of the line shows, but not the value the lambda keeps.