Share via


Seq.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.Seq

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

// Signature:
Seq.filter : ('T -> bool) -> seq<'T> -> seq<'T>

// Usage:
Seq.filter predicate source

Parameters

  • predicate
    Type: 'T -> bool

    A function to test whether each item in the input sequence should be included in the output.

  • source
    Type: seq<'T>

    The input sequence.

Exceptions

Exception

Condition

ArgumentNullException

Thrown when the input sequence is null.

Return Value

The result sequence.

Remarks

The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. The sequence is lazily evaluated. Therefore, effects are delayed until it is enumerated.

This function is named Filter 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 shows the use of Seq.filter to filter an infinite sequence of random numbers to select only even numbers.

let random = new System.Random()
Seq.initInfinite (fun _ -> random.Next())
|> Seq.filter (fun x -> x % 2 = 0)
|> Seq.take 5
|> Seq.iter (fun elem -> printf "%d " elem)
printfn ""

Sample Output

2140052690 963487404 467169526 1800517368 1225141818

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

Microsoft.FSharp.Collections Namespace (F#)