F#, lesson 2
Programs work with values: numbers, text, true or false. To reuse a value, give it a name
with let:
Each line is a binding: the name on the left stands for the value on the right. Underscores
inside numbers are ignored, so 522_000 is just easier to read.
You did not write any types above, but F# knows them all. The compiler infers each type from the value:
| Type | Examples | Notes |
|---|---|---|
int | 42, -7 | whole numbers (32-bit) |
float |
2 exercises to try what you just read.
3.14, 2.0 |
| numbers with a decimal point (64-bit) |
string | "hello" | text in double quotes |
char | 'a' | one character in single quotes |
bool | true, false | yes/no values |
When it helps the reader, add a type annotation after a colon:
F# never mixes number types silently. 2 + 1.5 is an error, because one side is an int and the
other a float. Convert explicitly with the function named after the target type:
A let binding cannot change. Once city is "Lyon", it stays "Lyon". This makes code easier
to follow: when you read a name, you know nothing has secretly changed it.
If you write let city = "Paris" again inside a function, you create a new binding that
hides the old one. This is called shadowing. (At the top level of a file, defining the same
name twice is an error.)
When you really need a value that changes, mark it mutable and assign with <-:
Use this sparingly. Most F# code builds new values from old ones instead of changing anything, and you'll see how in the lessons on recursion and lists.
Inside a function or block, bindings are indented and visible only there:
When the block ends, width and height are gone.
Use camelCase for values and functions: totalPrice, maxSpeed. Since every let is already
constant, a well-named top-level value is all a constant needs. (F# also has a [<Literal>]
attribute for true compile-time constants, which you'll meet when you need it in pattern
matching.)
A road trip costs fuelPerDay for each of the days, plus a one-off snacks cost. The starter
already has these bindings. Add a binding called total with the full cost and print it in this
form:
The program reads no input.
The starter reads a first name and a last name, one per line. Print the name in "last, first"
form, and on the next line the total number of letters in both names. Use + to join strings
and .Length to measure them.
Sample input:
Sample output:
let city = "Lyon"
let population = 522_000
let rainy = truelet price: float = 4.50let apples = 3
let weight = float apples * 0.2 // 0.6
let label = "Apples: " + string apples // + joins stringslet mutable score = 0
score <- score + 10let describe () =
let width = 8
let height = 5
width * heightTotal: 300Ada
LovelaceLovelace, Ada
Letters: 11