typestar

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

  1. let rec countFrames acc hives folds by hand.
  2. The recursive call is the last expression — constant stack.
  3. and joins mutually recursive definitions.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Idioms, step 20 of 27 in Language basics.

← Previous Next →

Recursion in other languages