Share via


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

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

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

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

// Signature:
List.tryFind : ('T -> bool) -> 'T list -> 'T option

// Usage:
List.tryFind predicate list

Parameters

  • predicate
    Type: 'T ->bool

    The function to test the input elements.

  • list
    Type: 'Tlist

    The input list.

Return Value

The first element for which the predicate returns true, or None if every element evaluates to false.

Remarks

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

Example

The following code example illustrates the use of List.tryFind and List.tryFindIndex.

let list1d = [1; 3; 7; 9; 11; 13; 15; 19; 22; 29; 36]
let isEven x = x % 2 = 0
match List.tryFind isEven list1d with
| Some value -> printfn "The first even value is %d." value
| None -> printfn "There is no even value in the list." 

match List.tryFindIndex isEven list1d with
| Some value -> printfn "The first even value is at position %d." value
| None -> printfn "There is no even value in the list."

Output

The first even value is 22.
The first even value is at position 8.

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

Microsoft.FSharp.Collections Namespace (F#)