Recursion in F#
rec allows self-reference; an accumulator keeps calls in tail position.
// rec allows self-reference; an accumulator keeps the call a tail.
let rec countFrames acc hives =
match hives with
| [] -> acc
| frames :: rest -> countFrames (acc + frames) rest
printfn "Yard total: %d frames" (countFrames 0 [8; 10; 6; 9])
// Mutual recursion needs and: two functions defined together.
let rec isEvenDay n = if n = 0 then true else isOddDay (n - 1)
and isOddDay n = if n = 0 then false else isEvenDay (n - 1)
printfn "Day 12 even? %b" (isEvenDay 12)
printfn "Day 7 even? %b" (isEvenDay 7)
How it works
let rec countFrames acc hivesfolds by hand.- The recursive call is the last expression — constant stack.
andjoins mutually recursive definitions.
Keywords and builtins used here
elsefalseifletmatchthentruewith
The run, in numbers
- Lines
- 14
- Characters to type
- 511
- Tokens
- 95
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 88 seconds.
Step 2 of 3 in Idioms, step 20 of 27 in Language basics.