F#, lesson 6
Functions are the main building block of F# programs. You have used several already (printfn,
int); now you'll write your own.
A function is a let binding with parameters after the name:
There is no return keyword: the last expression in the body is the result. Arguments are
separated by spaces, not commas. Wrap an argument in parentheses when it is a calculation itself:
square (2 + 3). Without them, square 2 + 3 means (square 2) + 3.
A longer body goes on indented lines below the =:
$"..." is an interpolated string: expressions inside are evaluated and inserted.
2 exercises to try what you just read.
{ }F# infers a type for every function. area has the type int -> int -> int: it takes an int,
then another int, and returns an int. The last type is always the result. You can write the
types yourself to document intent:
A function with no meaningful input takes () (unit), and one that only prints returns unit:
Since a function takes its arguments one by one, you can supply only some of them. The result is a new function that waits for the rest:
This becomes very handy with List.map and friends in the next lesson.
fun x -> x * 2 is a function without a name, useful when you need a small function just once:
List.map (fun p -> p * 2) prices.
Parameters and values defined inside a function exist only in that function. Two functions can
each have a parameter called x without any clash. You can even define helper functions inside a
function, and they stay invisible outside:
In F#, a name must be defined above the place where it is used (a function can call itself only
with let rec). The order of a file therefore matters, and you always know where to look for a
definition: upwards.
A courier charges 5 for a parcel of up to 1 kg, plus 2 for every kilogram above that. Write the
function shipping weight that returns the cost for a whole number of kilograms (at least 1).
The starter reads one line of weights separated by spaces and prints the cost of each, one per
line. You only need to fill in shipping.
Sample input:
Sample output:
Write a function grade score that turns a score from 0 to 100 into a letter: 90 or more is
A, 80 or more is B, 70 or more is C, 60 or more is D, anything lower is F.
The starter reads scores, one per line, and prints each score with its letter. Fill in grade.
Sample input:
Sample output:
let square x = x * x
let area width height = width * height
printfn "%d %d" (square 7) (area 3 4) // 49 12let describeBox width height =
let volume = width * height * 10
$"A box holding {volume} litres"let average (a: float) (b: float) : float = (a + b) / 2.0let greet () = printfn "Welcome!" // unit -> unit
greet ()let add a b = a + b
let addTax = add 5 // int -> int
printfn "%d" (addTax 20) // 25let orderCost items =
let shipping = 4
let withShipping price = price + shipping
withShipping (items * 10)1 3 105
9
2395
72
4095 A
72 C
40 F