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

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

liboz|Last Updated: 8/18/2017

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

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

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

Syntax

// Signature:
Array.countBy : ('T -> 'Key) -> 'T [] -> ('Key * int) [] ('Key requires equality)

// Usage:
Array.countBy projection source

Parameters

projection Type: 'T -> 'Key

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

source Type: 'T[]

The input array.

Exceptions

ExceptionCondition
ArgumentNullExceptionThrown when the input array is null

Return Value

An array of unique keys and their number of occurrences in the original array.

Remarks

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

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.

Example

The following example demonstrates the use of Array.countBy to determine the number of elements in an array that are odd or even.

let array1 = [| 1 .. 100 |]
let printArray anarray = 
    anarray 
    |> Array.iter (printf "%A ")
    printfn ""
let arrayResult = Array.countBy (fun elem ->
    if (elem % 2 = 0) then 0 else 1) array1

printArray arrayResult

Output

(1, 50) (0, 50)

Platforms

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.Array Module (F#)

Microsoft.FSharp.Collections Namespace (F#)

© 2018 Microsoft