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 -> boolThe 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 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2
Version Information
F# Runtime
Supported in: 2.0, 4.0
Silverlight
Supported in: 3