Expand Minimize

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

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

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

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

// Signature:
Seq.countBy : ('T -> 'Key) -> seq<'T> -> seq<'Key * int> (requires equality)

// Usage:
Seq.countBy projection source

projection

Type: 'T -> 'Key

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

source

Type: seq<'T>

The input sequence.

Exception

Condition

ArgumentNullException

Thrown when the input sequence is null.

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

Note that this function returns a sequence that traverses the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence.

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 Seq.countBy to determine the number of elements in a sequence that are odd or even.


let mySeq1 = seq { 1.. 100 }
let printSeq seq1 = Seq.iter (printf "%A ") seq1; printfn ""
let seqResult = Seq.countBy (fun elem ->
    if (elem % 2 = 0) then 0 else 1) mySeq1

printSeq seqResult


(1, 34) (2, 33) (0, 33) 

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

F# Runtime

Supported in: 2.0, 4.0

Silverlight

Supported in: 3

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft