F# Sequence Seq.filter

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Suppose that we have a sequence of integers and we want to create a sequence that contains only the even integers. We can obtain the latter by using the filter function of the Seq module. The filter function has the type signature ('a -> bool) -> seq<'a> -> seq<'a>; this indicates that it accepts a function that returns true or false (sometimes called a predicate) for a given input of type 'a and a sequence that comprises values of type 'a to yield a sequence that comprises values of type 'a.

// Function that tests if an integer is even
let isEven x = (x % 2) = 0

// Generates an infinite sequence that contains the natural numbers
let naturals = Seq.unfold (fun state -> Some(state, state + 1)) 0
 
// Can be used to filter the naturals sequence to get only the even numbers
let evens = Seq.filter isEven naturals 


Got any F# Question?