F# folding and aggregation
last modified December 4, 2026
In this article we reduce collections to single values in F#. We fold
lists with an accumulator, compute running totals, and use the
aggregation functions of the List module.
Folding is the functional replacement for a loop that updates a mutable
total. A fold walks through a collection and passes a state from
one element to the next. The state can be a number, a tuple, a record, a
list, or a map. Most aggregation functions, such as List.sum
or List.countBy, are folds with a fixed purpose. The examples
use lists; the Array and Seq modules have the
same functions.
The fold function
List.fold takes a folder function, an initial state, and a
list. It calls the folder with the current state and each element in
turn; the result becomes the new state.
let vals = [ 1; 2; 3; 4; 5 ] let total = List.fold (fun acc x -> acc + x) 0 vals printfn "sum: %d" total let product = List.fold (fun acc x -> acc * x) 1 vals printfn "product: %d" product let biggest = List.fold max 0 vals printfn "max: %d" biggest
The sum starts from 0 and the product from 1, the neutral values of
addition and multiplication. Any two-argument function with the right
types can be the folder, so the built-in max works as well.
let total = List.fold (fun acc x -> acc + x) 0 vals
The fold computes ((((0 + 1) + 2) + 3) + 4) + 5. The
parameter acc holds the state.
λ dotnet fsi fold.fsx sum: 15 product: 120 max: 5
Tracing the state
Printing inside the folder shows how the state changes. The state does not have to be of the same type as the elements.
let words = [ "falcon"; "owl"; "eagle"; "hawk" ]
let total =
words
|> List.fold (fun acc (word: string) ->
let next = acc + word.Length
printfn "%-6s acc=%2d -> %2d" word acc next
next) 0
printfn "letters: %d" total
let longest =
words |> List.fold (fun (best: string) word ->
if word.Length > best.Length then word else best) ""
printfn "longest: %s" longest
The first fold turns a list of strings into an int. The
second keeps the longest word seen so far; for words of equal length the
first one wins, because the comparison uses >.
λ dotnet fsi trace.fsx falcon acc= 0 -> 6 owl acc= 6 -> 9 eagle acc= 9 -> 14 hawk acc=14 -> 18 letters: 18 longest: falcon
Folding from the right
List.foldBack processes the list from the last element to
the first. Its arguments come in a different order: the folder takes the
element first and the state second, and the initial state follows the
list.
let vals = [ 1; 2; 3; 4 ] let fromLeft = List.fold (fun acc x -> x :: acc) [] vals printfn "fold: %A" fromLeft let fromRight = List.foldBack (fun x acc -> x :: acc) vals [] printfn "foldBack: %A" fromRight let leftText = List.fold (fun acc x -> sprintf "(%s-%d)" acc x) "0" vals let rightText = List.foldBack (fun x acc -> sprintf "(%d-%s)" x acc) vals "0" printfn "%s" leftText printfn "%s" rightText
Consing each element onto the state reverses the list with
fold and copies it with foldBack. The strings
show how the operations are grouped. With an operation such as
subtraction, which is not associative, the two folds give different
results.
λ dotnet fsi fold_back.fsx fold: [4; 3; 2; 1] foldBack: [1; 2; 3; 4] ((((0-1)-2)-3)-4) (1-(2-(3-(4-0))))
Reduce
List.reduce is a fold without an initial state. It starts
with the first element and folds the rest into it, so the state has the
type of the elements.
let temps = [ 12.5; 14.0; 9.5; 17.0; 11.0 ] let warmest = List.reduce max temps let coldest = List.reduce min temps printfn "range: %.1f to %.1f" coldest warmest let sentence = [ "a"; "hawk"; "over"; "the"; "hill" ] |> List.reduce (fun a b -> a + " " + b) printfn "%s" sentence let empty: float list = [] printfn "%.1f" (List.reduce max empty)
There is no sensible result for an empty list, so reduce
throws an ArgumentException. Use fold with an
initial state when the list may be empty.
λ dotnet fsi reduce.fsx range: 9.5 to 17.0 a hawk over the hill System.ArgumentException: The input list was empty. (Parameter 'list')
Running totals with scan
List.scan works like fold, but returns every
intermediate state, including the initial one. The result has one more
element than the input.
let deposits = [ 100; -30; -90; 250; -80 ] let balances = List.scan (+) 0 deposits printfn "%A" balances let lowest = List.min balances printfn "lowest balance: %d" lowest let steps = [ 3; 1; 4; 1; 5; 9; 2; 6 ] let records = List.scan max 0 steps |> List.tail printfn "%A" records let totals = List.scanBack (+) steps 0 printfn "%A" totals
The operator (+) in parentheses is an ordinary
two-argument function, so it can be passed to scan
directly. Scanning with max gives the highest value so far.
The lowest balance shows that the account went below zero.
List.tail drops the initial state. List.scanBack
computes the totals from the right: each element is the sum of the rest
of the list.
λ dotnet fsi scan.fsx [0; 100; 70; -20; 230; 150] lowest balance: -20 [3; 3; 4; 4; 5; 9; 9; 9] [31; 28; 27; 23; 22; 17; 8; 6; 0]
Sum, average, min and max
For common aggregates the List module has ready-made
functions. The By variants take a projection function and
work on lists of records.
type Product = { Name: string; Price: decimal; Stock: int }
let products =
[ { Name = "keyboard"; Price = 49.90m; Stock = 12 }
{ Name = "mouse"; Price = 7.50m; Stock = 40 }
{ Name = "monitor"; Price = 219.00m; Stock = 3 }
{ Name = "cable"; Price = 9.90m; Stock = 85 } ]
printfn "items in stock: %d" (List.sumBy (fun p -> p.Stock) products)
printfn "stock value: %M" (List.sumBy (fun p -> p.Price * decimal p.Stock) products)
printfn "average price: %.2f" (List.averageBy (fun p -> p.Price) products)
let cheapest = List.minBy (fun p -> p.Price) products
let largest = List.maxBy (fun p -> p.Stock) products
printfn "cheapest: %s" cheapest.Name
printfn "most stock: %s" largest.Name
printfn "%d" (List.sum [ 1; 2; 3 ])
printfn "%.1f" (List.average [ 1.0; 2.0; 4.0 ])
sumBy adds the projected values, while minBy
and maxBy return the whole element with the smallest or
largest projection. average and averageBy
need a type that supports division, such as float or
decimal; for integers, convert first. All of them except
sum and sumBy throw on an empty list.
λ dotnet fsi aggregates.fsx items in stock: 140 stock value: 2397.30 average price: 71.58 cheapest: mouse most stock: cable 6 2.3
Counting and grouping
List.countBy counts the elements for each key, and
List.groupBy collects them. Both return a list of key and
value tuples in the order in which the keys first appear.
type Order = { Customer: string; City: string; Total: decimal }
let orders =
[ { Customer = "Paul"; City = "Bratislava"; Total = 120m }
{ Customer = "Lucia"; City = "Kosice"; Total = 80m }
{ Customer = "Peter"; City = "Bratislava"; Total = 45m }
{ Customer = "Jana"; City = "Zilina"; Total = 230m }
{ Customer = "Martin"; City = "Kosice"; Total = 60m } ]
let perCity = orders |> List.countBy (fun o -> o.City)
printfn "%A" perCity
let sizes = orders |> List.countBy (fun o -> if o.Total >= 100m then "large" else "small")
printfn "%A" sizes
for city, cityOrders in List.groupBy (fun o -> o.City) orders do
let total = cityOrders |> List.sumBy (fun o -> o.Total)
let names = cityOrders |> List.map (fun o -> o.Customer)
printfn "%-10s %6M %A" city total names
The key can be any value computed from an element, not only a field.
Combining groupBy with sumBy gives a total per
group, much like GROUP BY in SQL.
λ dotnet fsi count_by.fsx
[("Bratislava", 2); ("Kosice", 2); ("Zilina", 1)]
[("large", 2); ("small", 3)]
Bratislava 165 ["Paul"; "Peter"]
Kosice 140 ["Lucia"; "Martin"]
Zilina 230 ["Jana"]
Partition and choose
List.partition splits a list in two by a predicate.
List.choose filters and transforms in one step: the
function returns an option, and only the Some values are
kept.
let scores = [ 78; 45; 91; 60; 33; 85; 52 ]
let passed, failed = List.partition (fun s -> s >= 50) scores
printfn "passed: %A" passed
printfn "failed: %A" failed
let entries = [ "width=80"; "height=24"; "#comment"; "color=on"; "broken" ]
let parse (line: string) =
match line.Split '=' with
| [| key; value |] -> Some(key, value)
| _ -> None
let settings = List.choose parse entries
printfn "%A" settings
let numbers = [ "12"; "x"; "7"; "3.5"; "40" ]
let parsed = numbers |> List.choose (fun s ->
match System.Int32.TryParse s with
| true, n -> Some n
| _ -> None)
printfn "%A, sum %d" parsed (List.sum parsed)
partition returns a tuple, which we deconstruct right in
the binding. Lines that do not have exactly one = sign
produce None and drop out; so do strings that are not whole
numbers.
λ dotnet fsi partition.fsx
passed: [78; 91; 60; 85; 52]
failed: [45; 33]
[("width", "80"); ("height", "24"); ("color", "on")]
[12; 7; 40], sum 59
Collect and zip
List.collect maps each element to a list and concatenates
the results. List.zip pairs the elements of two lists of
equal length, and List.fold2 folds over two lists at once.
type Team = { Name: string; Members: string list }
let teams =
[ { Name = "red"; Members = [ "Anna"; "Boris" ] }
{ Name = "blue"; Members = [ "Cyril" ] }
{ Name = "green"; Members = [ "Dana"; "Emil"; "Fero" ] } ]
let everyone = teams |> List.collect (fun t -> t.Members)
printfn "%A" everyone
let quantities = [ 2; 1; 5 ]
let prices = [ 3.50; 12.00; 0.80 ]
let lines = List.zip quantities prices
printfn "%A" lines
let total = List.fold2 (fun acc q p -> acc + float q * p) 0.0 quantities prices
printfn "total: %.2f" total
let sameTotal = List.map2 (fun q p -> float q * p) quantities prices |> List.sum
printfn "total: %.2f" sameTotal
zip, fold2, and map2 throw an
exception when the lists have different lengths. The last two lines
compute the same total twice; map2 followed by
sum is often easier to read than fold2.
λ dotnet fsi collect_zip.fsx ["Anna"; "Boris"; "Cyril"; "Dana"; "Emil"; "Fero"] [(2, 3.5); (1, 12.0); (5, 0.8)] total: 23.00 total: 23.00
Generating lists with unfold
List.unfold is the opposite of a fold: it starts with a
state and produces elements. The generator function returns
Some(element, nextState) to emit an element or
None to stop.
let countdown =
List.unfold (fun n -> if n = 0 then None else Some(n, n - 1)) 5
printfn "%A" countdown
let collatz start =
start
|> List.unfold (fun n ->
if n = 0 then None
elif n = 1 then Some(1, 0)
elif n % 2 = 0 then Some(n, n / 2)
else Some(n, 3 * n + 1))
printfn "%A" (collatz 6)
let fibs =
Seq.unfold (fun (a, b) -> Some(a, (b, a + b))) (0, 1)
|> Seq.takeWhile (fun x -> x < 100)
|> List.ofSeq
printfn "%A" fibs
The Collatz sequence uses 0 as a stop marker after it emits 1. The
Fibonacci generator never returns None, so it must be a
lazy sequence; Seq.takeWhile takes the numbers below 100
and List.ofSeq turns them into a list.
λ dotnet fsi unfold.fsx [5; 4; 3; 2; 1] [6; 3; 10; 5; 16; 8; 4; 2; 1] [0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89]
Folding into a tuple
A fold can compute several results in one pass if the state is a tuple. Here we compute the count, sum, minimum, and maximum of a list at once.
let readings = [ 21.5; 19.0; 23.5; 22.0; 18.5; 24.0 ]
let count, sum, low, high =
readings
|> List.fold
(fun (count, sum, low, high) x -> count + 1, sum + x, min low x, max high x)
(0, 0.0, infinity, -infinity)
printfn "count: %d" count
printfn "mean: %.2f" (sum / float count)
printfn "low: %.1f, high: %.1f" low high
let longestRun (xs: int list) =
xs
|> List.fold
(fun (prev, run, best) x ->
let run = if x = prev + 1 then run + 1 else 1
x, run, max best run)
(System.Int32.MinValue, 0, 0)
|> fun (_, _, best) -> best
printfn "longest run: %d" (longestRun [ 4; 5; 6; 1; 2; 7; 8; 9; 10 ])
The initial minimum is infinity and the initial maximum is
-infinity, so the first reading replaces both. The second
fold finds the longest run of consecutive numbers; its state remembers
the previous number, the current run, and the best run so far.
λ dotnet fsi stats.fsx count: 6 mean: 21.42 low: 18.5, high: 24.0 longest run: 4
Folding into a map
The state can also be a collection. Folding into a Map
counts or sums values by key without any mutable dictionary.
let text = "the owl and the hawk and the eagle watch the hill"
let counts =
text.Split ' '
|> Array.fold
(fun (acc: Map<string, int>) word ->
acc |> Map.change word (fun count ->
match count with
| Some n -> Some(n + 1)
| None -> Some 1))
Map.empty
for KeyValue(word, n) in counts do
printfn "%-5s %d" word n
let sameCounts = text.Split ' ' |> Array.countBy id |> Map.ofArray
printfn "same result: %b" (counts = sameCounts)
Map.change receives the current value as an option and
returns the new one. A map keeps its keys sorted, so the words are
printed in alphabetical order. For plain counting, countBy
with the identity function id does the same job, but the
fold can keep any state per key, such as a sum or a list.
λ dotnet fsi word_count.fsx and 2 eagle 1 hawk 1 hill 1 owl 1 the 4 watch 1 same result: true
A sales report
The last example combines several aggregations. It reads sales records, totals them by region, finds the best day, and shows a running total.
type Sale = { Day: int; Region: string; Amount: decimal }
let sales =
[ { Day = 1; Region = "north"; Amount = 320m }
{ Day = 1; Region = "south"; Amount = 150m }
{ Day = 2; Region = "north"; Amount = 90m }
{ Day = 2; Region = "east"; Amount = 410m }
{ Day = 3; Region = "south"; Amount = 275m }
{ Day = 3; Region = "east"; Amount = 60m }
{ Day = 4; Region = "north"; Amount = 540m } ]
printfn "Sales by region"
sales
|> List.groupBy (fun s -> s.Region)
|> List.map (fun (region, xs) -> region, List.sumBy (fun s -> s.Amount) xs)
|> List.sortByDescending snd
|> List.iter (fun (region, total) -> printfn " %-6s %6M" region total)
let daily =
sales
|> List.groupBy (fun s -> s.Day)
|> List.map (fun (day, xs) -> day, List.sumBy (fun s -> s.Amount) xs)
let bestDay, bestTotal = List.maxBy snd daily
printfn "Best day: %d (%M)" bestDay bestTotal
printfn "Running total"
daily
|> List.map snd
|> List.scan (+) 0m
|> List.tail
|> List.iteri (fun i total -> printfn " day %d %6M" (i + 1) total)
let large, small = List.partition (fun s -> s.Amount >= 200m) sales
printfn "Large sales: %d, small sales: %d" large.Length small.Length
groupBy and sumBy produce the totals per region
and per day, maxBy snd picks the tuple with the largest
total, and scan turns the daily totals into a running
total. List.sortByDescending is covered in
F# sort.
λ dotnet fsi sales.fsx Sales by region north 950 east 470 south 425 Best day: 4 (540) Running total day 1 470 day 2 970 day 3 1305 day 4 1845 Large sales: 4, small sales: 3
Source
List module - FSharp.Core documentation
In this article we have folded collections with fold,
foldBack, and reduce, computed running totals
with scan, used the aggregation functions
sumBy, averageBy, minBy,
maxBy, countBy, and groupBy,
split and filtered lists with partition and
choose, combined lists with collect and
zip, and generated lists with unfold. See
also F# list and
F# map.
Author
List all F# tutorials.