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