Recursion in OCaml
rec allows self-reference; accumulators keep calls in tail position.
(* rec allows self-reference; an accumulator keeps the call a tail. *)
let rec count_animals acc = function
| [] -> acc
| n :: rest -> count_animals (acc + n) rest
(* Mutual recursion joins definitions with and. *)
let rec ebbs n = if n = 0 then "slack" else flows (n - 1)
and flows n = if n = 0 then "running" else ebbs (n - 1)
let () =
Printf.printf "Survey total: %d\n" (count_animals 0 [12; 5; 31]);
Printf.printf "Tide after 6 turns: %s\n" (ebbs 6);
Printf.printf "Tide after 7 turns: %s\n" (ebbs 7)
How it works
let rec count_animals accfolds by hand, stack-safe.functionmatches the list argument directly.andjoins mutually recursive definitions.
Keywords and builtins used here
andelsefunctionifletrecthen
The run, in numbers
- Lines
- 13
- Characters to type
- 506
- Tokens
- 112
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 103 seconds.
Step 3 of 3 in Idioms, step 26 of 29 in Language basics.