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

Returns the index of the first element in the list that satisfies the given predicate. Raises KeyNotFoundException if no such element exists.

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

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

// Signature:
List.findIndex : ('T -> bool) -> 'T list -> int

// Usage:
List.findIndex predicate list

Parameters

  • predicate
    Type: 'T -> bool

    The function to test the input elements.

  • list
    Type: 'T list

    The input list.

Exceptions

Exception

Condition

ArgumentException

Thrown if the predicate evaluates to false for all the elements of the list.

Return Value

The index of the first element that satisfies the predicate.

Remarks

This function is named FindIndex 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 code shows how to use List.findIndex and compares its behavior to that of List.find.

let list1 = [ 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 = List.find (fun elem -> isPerfectSquare elem && isPerfectCube elem) list1
let index = List.findIndex (fun elem -> isPerfectSquare elem && isPerfectCube elem) list1
printfn "The first element that is both a square and a cube is %d and its index is %d." element index

Output

The first element that is both a square and a cube is 64 and its index is 62.

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

See Also

Reference

Collections.List Module (F#)

Microsoft.FSharp.Collections Namespace (F#)