Table of contents
Collapse the table of content
Expand the table of content

List.countBy<'T,'Key> Function (F#)

liboz|Last Updated: 8/18/2017

Applies a key-generating function to each element of a list and returns a list yielding unique keys and their number of occurrences in the original list.

Namespace/Module Path: Microsoft.FSharp.Collections.List

Assembly: FSharp.Core (in FSharp.Core.dll)


// Signature:
List.countBy : ('T -> 'Key) -> 'T list -> ('Key * int) list ('Key requires equality)

// Usage:
List.countBy projection source


projection Type: 'T -> 'Key

A function transforming each item of input list into a key to be compared against the others.

source Type: 'Tlist

The input list.


ArgumentNullExceptionThrown when the input list is null

Return Value

A list of unique keys and their number of occurrences in the original list.


Note that this function returns a list that traverses the whole initial list. As a result this function should not be used with large lists. The function makes no assumption on the ordering of the original list.

This function is named CountBy in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.


The following example demonstrates the use of List.countBy to determine the number of elements in a list that are odd or even.

let list1 = [ 1 .. 100 ]
let printList alist = 
    |> List.iter (printf "%A ")
    printfn ""
let listResult = List.countBy (fun elem ->
    if (elem % 2 = 0) then 0 else 1) list1

printList listResult


(1, 50) (0, 50)


Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Version Information

F# Core Library Versions

Supported in: 4.0, Portable

See Also

Collections.List Module (F#)

Microsoft.FSharp.Collections Namespace (F#)

© 2020 Microsoft