Share via


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

Returns a new collection containing only the elements of the collection for which the given predicate returns true.

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

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

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

// Usage:
List.filter predicate list

Parameters

  • predicate
    Type: 'T -> bool

    The function to test the input elements.

  • list
    Type: 'T list

    The input list.

Return Value

A list containing only the elements that satisfy the predicate.

Remarks

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

Example

The following example demonstrates the use of List.filter.

let evenOnlyList = List.filter (fun x -> x % 2 = 0) [1; 2; 3; 4; 5; 6]

The resulting list is [2; 4; 6].

The following example shows another typical use for List.filter.

let data = [("Cats",4);
            ("Dogs",5);
            ("Mice",3);
            ("Elephants",2)]
let res = data |> List.filter (fun (nm,x) -> nm.Length <= 4)
printfn "Animals with short names: %A" res
Animals with short names: [("Cats", 4); ("Dogs", 5); ("Mice", 3)]

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#)