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