Export (0) Print
Expand All
Expand Minimize
This topic has not yet been rated - Rate this topic

Array.find<'T> Function (F#)

Returns the first element for which the given function returns true. Raise KeyNotFoundException if no such element exists.

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

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

// Signature:
Array.find : ('T -> bool) -> 'T [] -> 'T

// Usage:
Array.find predicate array
predicate

Type: 'T -> bool

The function to test the input elements.

array

Type: 'T []

The input array.

Exception

Condition

KeyNotFoundException

Thrown if predicate does not return true for any element.

The first element for which predicate returns true.

This function is named Find 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 Array.find and Array.findIndex to identify the first integer greater than 1 that is both a square and a cube.

let arrayA = [| 2 .. 100 |]
let delta = 1.0e-10
let isPerfectSquare (x:int) =
    let y = sqrt (float x)
    abs(y - round y) < delta
let isPerfectCube (x:int) =
    let y = System.Math.Pow(float x, 1.0/3.0)
    abs(y - round y) < delta
let element = Array.find (fun elem -> isPerfectSquare elem && isPerfectCube elem) arrayA
let index = Array.findIndex (fun elem -> isPerfectSquare elem && isPerfectCube elem) arrayA
printfn "The first element that is both a square and a cube is %d and its index is %d." element index
The first element that is both a square and a cube is 64 and its index is 62.

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

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.