2.1 Values, types and names: let
Page 2 of 9
2.1.1 What a value is
A value is one piece of data that a program works with: the number 18, the text "LAMP-01". A program computes new values from old ones, as 18 - 9 gives 9, and prints some of them.
Every value has a type, which says what kind of value it is, and so what you can do with it. You can multiply two numbers, but not two product names. Think of the boxes of a paper form: one box takes a date, another a phone number, and a clerk refuses a form with a name in the date box. Types are those boxes, and una check is the clerk.
The types of this chapter:
| Type | Its values | Written as |
|---|---|---|
Int |
whole numbers: positive, zero or negative | 18, 1_990, -500 |
Text |
a sequence of characters, as in chapter 1 | "Desk lamp, brass" |
Unit |
one value only, which carries no information; main gives it back |
unit |
A value written out in the code, such as 18 or "LAMP-01", is a literal. Section 2.3 adds the fixed-width integers, and chapter 3 adds Bool, the type of yes-or-no answers.
2.1.2 Why every value has a type
print takes a text. Here is a program that prints when the store closes, and a version that gives print the number 18 instead:
--- a/src/closing.una
+++ b/src/closing.una
@@ -4,4 +4,4 @@
pub main() -> Unit
uses @console: Console[print]
=
- @console.print("The store closes at 18:00")
+ @console.print(18)[U2001] Error: argument `line` of operation `Console.print` must be `Text`, found `Int`
╭─[ src/closing.una:7:18 ]
│
7 │ @console.print(18)
│ ─┬
│ ╰── argument `line` of operation `Console.print` must be `Text`, found `Int`
│
│ Note: run `una explain U2001` for an explanation
───╯The message says that the argument of print, which is called line, must be a Text, and that the value given is an Int. Some languages would turn the number into a text without a word, and some would fail only when the line runs. Una refuses before the program runs, and it never turns a value of one type into another unless the code says so. Saying so takes two braces, as Putting values into a text shows.
2.1.3 How to write values and names
2.1.3.1 Literals
- An
Intliteral is written in decimal digits:18,1990. An_may group the digits, so1_990is 1990, easier to read. For a negative number, write a minus sign in front:-500. Section 2.2 gives every rule. - A
Textliteral is written between double quotes, on one line, as in chapter 1:"Desk lamp, brass". Chapter 3 covers texts in full. - The one
Unitvalue is writtenunit. You rarely write it: a function whose result type isUnit, such asmain, gives it back on its own.
2.1.3.2 Naming a value: let
let gives a name to a value, so that the steps after it can use the value by its name:
let lamps = 2names the value2aslamps. The type,Int, comes from the value.let lamp_cents: Int = 1_990writes the type too, after:. It is optional, and it tells a reader what the name holds. When it is written,una checkholds the value to it.
A let is a step of a body, on a line of its own, like a call of print. Such a name is also called a binding: it binds a word to a value. A name of a value follows the rules of a function's name: small letters, digits and _, starting with a letter, with no __ and no _ at the end: lamps, lamp_cents, sku2.
2.1.3.3 Putting values into a text
A name or a computation in braces, inside a text, puts its value into the text: "{lamps} x {sku}" is the value of lamps, then x, then the value of sku. This is an interpolation. An Int goes in as plain decimal digits, with a minus sign when it is negative, and with no _. A computation may stand in the braces too: "{lamps * lamp_cents} cents".
That is how a program prints a number: it puts the number into a text, and prints the text. Chapter 3 shows the rest of what braces can hold.
2.1.4 Each step is a package
Each example of this chapter, and of every chapter after it, is a package of its own, made as in chapter 1, Making the package: a directory with una.toml, verification.lock and the module under src/. The book calls these packages the chapter's steps. Each one has a name such as steps/03-values: the number orders the steps in the download.
You can type each step, or take it whole from the chapter's download, 02-numbers.tar.gz, which holds every package of this chapter. To make a step by hand next to the package of chapter 1, start in your home directory. A new terminal starts there already; if your terminal is still in hello, go up to your home directory with cd .. (.. is the path of the directory above). Then make the new directory as before:
cd ..
mkdir values
cd values
mkdir srcThen write una.toml, src/values.una and verification.lock with your editor. verification.lock is the same in every package of this book. The manifest names the package and the module that una run . starts, here values, and grants the console, as in chapter 1.
2.1.5 Values in a store
This program names four values, two texts and two numbers, and prints them and what it computes from them:
module values
--- Prints a few values of two types, named with `let`, and what is computed from them.
pub main() -> Unit
uses @console: Console[print]
=
let sku = "LAMP-01"
let name: Text = "Desk lamp, brass"
let lamps = 2
let lamp_cents: Int = 1_990
@console.print(sku)
@console.print(name)
@console.print("{lamps}")
@console.print("{lamps} x {sku}")
@console.print("{lamps * lamp_cents} cents for {lamps} lamps")
let total = lamps * lamp_cents
@console.print("Total: {total} cents")let sku = "LAMP-01". A name for aText. A SKU, a stock keeping unit, is the code a store gives each product.let name: Text = "Desk lamp, brass". ATextwith its type written out.let lamps = 2. A name for anInt.let lamp_cents: Int = 1_990. AnIntwith its type written out. Money is kept in cents, whole numbers, so that nothing ever rounds by accident; section 2.2 says why.@console.print(sku). A name of aTextcan go toprintas it is.@console.print("{lamps}"). A number goes into a text first: the text holds only the number."{lamps * lamp_cents} cents for {lamps} lamps". A computation and a name inside one text.let total = lamps * lamp_cents. A name for a computed value. The computation runs once, at this line, andtotalholds its result.
una run . prints:
LAMP-01
Desk lamp, brass
2
2 x LAMP-01
3980 cents for 2 lamps
Total: 3980 cents2.1.6 Opening hours
Names make a computation read like the sentence it stands for. This program prints the store's hours from two numbers:
module opening
--- Prints today's opening hours, and what follows from them.
pub main() -> Unit
uses @console: Console[print]
=
let opens = 9
let closes = 18
@console.print("Open today from {opens}:00 to {closes}:00")
let hours = closes - opens
@console.print("That is {hours} hours of trading")
let cutoff = closes - 1
@console.print("Orders placed before {cutoff}:00 ship today")let opens = 9andlet closes = 18. The two hours that everything else comes from."Open today from {opens}:00 to {closes}:00". A text with two interpolations. The:00after each brace is plain text.let hours = closes - opens. A computed value, 9, named for what it means.let cutoff = closes - 1. The last hour at which an order ships the same day.
Its manifest names the package and its module opening:
[package]
name = "opening"
version = "0.1.0"
edition = "0.2"
[run]
entry = "opening"
grants = ["console"]una run . prints:
Open today from 9:00 to 18:00
That is 9 hours of trading
Orders placed before 17:00 ship todayWhen the store changes its closing time, one line changes, let closes = 18, and the three printed lines follow it.
2.1.7 How values and names behave
2.1.7.1 A value keeps its type
No value turns into another type on its own. An Int becomes part of a text only where the code puts it in braces, and a text never turns into a number on its own. A name with a written type holds the value to that type. Write the price as a text, let lamp_cents: Int = "1990", and una check . reports:
[U2001] Error: `lamp_cents` is declared as `Int`, found `Text`
╭─[ src/values.una:10:25 ]
│
10 │ let lamp_cents: Int = "1990"
│ ───┬──
│ ╰──── `lamp_cents` is declared as `Int`, found `Text`The quotes make "1990" a Text, four characters, not the number. The message names the binding, the type it was given, and the type it got.
2.1.7.2 A name exists from its line on
The steps of a body run in order, from the top, and a name exists only from the let that makes it. Move let hours of opening one line down, under the line that prints it:
[U1001] Error: cannot find name `hours` in this module, its imports or the prelude
╭─[ src/opening.una:10:28 ]
│
10 │ @console.print("That is {hours} hours of trading")
│ ──┬──
│ ╰──── cannot find name `hours` in this module, its imports or the preludeAt line 10 the name hours does not exist yet, so una check . cannot find it. The repair is to make the name before the step that uses it.
2.1.7.3 A name is made once
A body makes each name once. Reuse a name for a new value, as let lamps = lamps * lamp_cents would in values, and una check . points at both lines:
[U1002] Error: `lamps` is already bound in this scope; a local cannot rebind another
╭─[ src/values.una:16:7 ]
│
9 │ let lamps = 2
│ ──┬──
│ ╰──── first defined here
│
16 │ let lamps = lamps * lamp_cents
│ ──┬──
│ ╰──── `lamps` is already bound in this scope; a local cannot rebind another
│
│ Note: run `una explain U1002` for an explanation
────╯In the message, a scope is the part of the code where a name exists, here the body of the function, and a local is a name made inside it with let. If one name could hold two values, a reader would have to know which line they stand on to know what it means. Give the new value a name of its own, such as total.
2.1.7.4 A name keeps its value
A name made with let holds its value to the end of the body: no later step can give it another. A count that changes as a program works, such as a running total, uses let edit and an assignment, which chapter 9 teaches with loops. Every name in this chapter keeps its value.
2.1.8 When to name a value
Which to use:
| You want to… | Use |
|---|---|
| Use a value in several steps of one body | let, once, then its name |
| Give a computation a name that says what it means | let hours = closes - opens |
| State what type a name holds, for the reader and the check | let lamp_cents: Int = 1_990 |
| Use the same value in several functions | a function that gives it back, as in chapter 1 |
| Print a number | an interpolation: "{lamps}" |
2.1.9 Check yourself: values and names
A program counts the places in the boxes of an order of mugs:
--- Prints the labels of a box of mugs.
pub main() -> Unit
uses @console: Console[print]
=
let mugs = 6
let per_box = 4
let boxes = 2
let places = boxes * per_box
let spare = places - mugs
@console.print("{mugs} mugs in {boxes} boxes")
@console.print("{spare} empty places")
@console.print("{places - spare} of {places} places taken")What does una run . print?
Show the answer
6 mugs in 2 boxes
2 empty places
6 of 8 places takenplaces is 2 × 4, 8, and spare is 8 − 6, 2. The last line computes places - spare inside the braces: 8 − 2 is 6.
One more, without code. With lamps an Int and sku a Text, which of these steps check?
@console.print(lamps)@console.print("{lamps}")let both = lamps * sku@console.print("{lamps} x {sku}")
Show the answer
Steps 2 and 4 check. Step 1 gives print an Int where it takes a Text: U2001, as in Why every value has a type. Step 3 multiplies a number by a text, which has no meaning, and the check reports U2001 for it too. In steps 2 and 4 the braces put the values into a text, so print gets the Text it takes.