F#, lesson 7
Real programs handle many values at once: all the prices on a receipt, every vote in an election. F#'s everyday collection is the immutable list, and for lookups by key there is the immutable Map.
A list holds any number of values of the same type. Elements are separated by semicolons (or put on separate lines):
Lists never change. To "add" an element you create a new list: 0 :: scores puts 0 in front
(fast), and scores @ [99] joins two lists (copies the first).
Instead of writing loops by hand, you hand a function to the List module and it does the work:
These read even better with the pipe operator, one step per line:
List.fold is the general tool behind many of these: it walks the list from left to right,
combining a running result with each element. List.fold (fun acc p -> acc + p) 0 prices is
another way to write the sum.
2 exercises to try what you just read.
You can also take a list apart with pattern matching. A list is either empty, [], or a first
element followed by the rest, head :: tail:
Arrays ([| 1; 2; 3 |]) have a fixed size and fast access by position with arr[i]. .NET methods
such as String.Split return arrays. The Array module has the same functions as List
(Array.map, Array.sum, ...), and List.ofArray converts one into the other.
A Map stores key → value pairs, sorted by key:
Map.tryFind returns an option: Some value when the key exists, None when it doesn't.
Matching on it forces you to handle the missing case, so you never crash on an unknown key.
To count things, Map.change updates one key using a function that receives the current option:
function is a shortcut for fun x -> match x with. Looping over a map with
for KeyValue(name, count) in votes do ... visits the keys in sorted order.
Read one line of whole numbers separated by spaces (there is at least one). Print how many there are, their total and the largest one.
Sample input:
Sample output:
Each line of input is one vote: the name of a candidate. Count the votes and print each candidate with their number of votes, in alphabetical order, one per line.
Sample input:
Sample output:
let scores = [12; 7; 30] // int list
let names = ["Ana"; "Bo"] // string list
let empty: int list = []
let firstTen = [1 .. 10] // a range makes a list toolet prices = [4; 10; 3; 8]
let doubled = List.map (fun p -> p * 2) prices // [8; 20; 6; 16]
let cheap = List.filter (fun p -> p < 5) prices // [4; 3]
let total = List.sum prices // 25
let count = List.length prices // 4
let highest = List.max prices // 10
let sorted = List.sort prices // [3; 4; 8; 10]prices
|> List.filter (fun p -> p > 3)
|> List.map (fun p -> p * 2)
|> List.iter (printfn "%d")let rec sum list =
match list with
| [] -> 0
| x :: rest -> x + sum restlet stock = Map [ "apples", 12; "pears", 4 ]
let more = stock |> Map.add "plums" 9 // a new map; stock is unchanged
match Map.tryFind "apples" more with
| Some n -> printfn "%d apples" n
| None -> printfn "no apples"let addVote name votes =
votes |> Map.change name (function
| Some n -> Some (n + 1)
| None -> Some 1)12 7 30 1Count: 4
Total: 50
Max: 30Mila
Theo
Mila
AvaAva 1
Mila 2
Theo 1