Seq.filter

假设我们有一个整数序列,我们想要创建一个只包含偶数整数的序列。我们可以通过使用 Seq 模块的 filter 函数来获得后者。filter 函数的类型签名为 ('a -> bool) -> seq<'a> -> seq<'a>; 这表明它接受一个函数,该函数对于'a 类型的给定输入和包含'a 类型的值的序列返回 true 或 false(有时称为谓词),以产生包含'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