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

Returns the first element for which the given function returns true. Return None if no such element exists.

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

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

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

// Usage:
Array.tryFind predicate array

Parameters

  • predicate
    Type: 'T ->bool

    The function to test the input elements.

  • array
    Type: 'T[]

    The input array.

Return Value

The first element that satisfies the predicate, or None.

Remarks

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

Example

The following example demonstrates the use of Array.tryFind to attempt to locate array elements that are both perfect cubes and perfect squares.

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 lookForCubeAndSquare array1 =
    let result = Array.tryFind (fun elem -> isPerfectSquare elem && isPerfectCube elem) array1
    match result with
    | Some x -> printfn "Found an element: %d" x
    | None -> printfn "Failed to find a matching element."

lookForCubeAndSquare [| 1 .. 10 |]
lookForCubeAndSquare [| 100 .. 1000 |]
lookForCubeAndSquare [| 2 .. 50 |]
Found an element: 1
Found an element: 729
Failed to find a matching element.

Platforms

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

Version Information

F# Core Library Versions

Supported in: 2.0, 4.0, Portable

See Also

Reference

Collections.Array Module (F#)

Microsoft.FSharp.Collections Namespace (F#)