fold and reduce in F#
Thread state through a list; the accumulator can be anything.
// fold threads state through a list; reduce seeds from the head.
let weights = [28.4; 31.0; 19.7; 35.2]
let total = weights |> List.fold (fun acc w -> acc + w) 0.0
printfn "Total: %.1f kg" total
// The accumulator can be anything -- here a running maximum with count.
let heaviest, inspected =
weights |> List.fold (fun (best, n) w -> (max best w, n + 1)) (0.0, 0)
printfn "Heaviest of %d: %.1f kg" inspected heaviest
let product = [1; 2; 3; 4] |> List.reduce (*)
printfn "Reduce with (*): %d" product
How it works
List.foldtakes the seed explicitly;reduceseeds from the head.- A tuple accumulator tracks max and count in one pass.
List.reduce (*)multiplies the whole list down to one value.
Keywords and builtins used here
funlet
The run, in numbers
- Lines
- 13
- Characters to type
- 505
- Tokens
- 116
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 107 seconds.
Step 3 of 3 in Lists, step 12 of 27 in Language basics.