OCaml, lesson 7
One value at a time only gets you so far. OCaml's everyday collection is the list, and when you need to look values up by a key, you reach for a map.
A list holds any number of values of the same type. Elements are separated by semicolons:
Watch out: [1, 2, 3] with commas is a list with one element, a tuple. Use semicolons.
Lists are immutable. To "add" an element you build a new list: 0 :: scores puts 0 in front
(this is fast), and scores @ [99] joins two lists (this copies the first one).
The List module does the looping for you:
List.fold_left f start list is the most general one: it walks the list from left to right,
combining a running result with each element. in parentheses is the addition operator
used as an ordinary function. To find the largest element, fold with :
, where is the first element.
2 exercises to try what you just read.
( + )maxList.fold_left max (List.hd prices) pricesList.hdYou can also take a list apart with pattern matching. A list is either empty, [], or a first
element followed by the rest, head :: tail:
function is a shortcut for fun x -> match x with.
Arrays ([| 1; 2; 3 |]) have a fixed size, fast access by position with a.(i), and can be
changed in place. Lists are the default in OCaml code; use an array when you really need to jump
to the n-th item quickly.
A map stores key → value pairs and finds a key quickly. You create a map module for your key
type with Map.Make:
Like lists, maps are immutable: add returns a new map. find_opt returns an option:
Some value if the key is there, None if not. Matching on the option forces you to handle the
missing case, so there are no surprise "key not found" crashes.
StringMap.update key f map is perfect for counting. f receives the current option and returns
the new one:
StringMap.iter visits the bindings in increasing key order, so the output comes out sorted
for free.
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 = []let 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.fold_left ( + ) 0 prices (* 25 *)
let count = List.length prices (* 4 *)
let sorted = List.sort compare prices (* [3; 4; 8; 10] *)
let () = List.iter (fun p -> Printf.printf "%d\n" p) priceslet rec sum = function
| [] -> 0
| x :: rest -> x + sum restmodule StringMap = Map.Make (String)
let stock =
StringMap.empty
|> StringMap.add "apples" 12
|> StringMap.add "pears" 4
let () =
match StringMap.find_opt "apples" stock with
| Some n -> Printf.printf "%d apples\n" n
| None -> print_endline "no apples"let add_one key map =
StringMap.update key (function None -> Some 1 | Some n -> Some (n + 1)) map12 7 30 1Count: 4
Total: 50
Max: 30Mila
Theo
Mila
AvaAva 1
Mila 2
Theo 1