for序列表达被设计为看起来与其更著名的表亲一样,即命令式for循环。它通过一个序列“循环”,并将每次迭代的主体评估为它正在生成的序列。就像所有与序列相关的东西一样,它不是可变的。
> let oneToTen = seq { for x in 1..10 -> x } val oneToTen: seq<int> = seq [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] // 或者,等效地: > let oneToTen = seq { for x in 1..10 do yield x } val oneToTen: seq<int> = seq [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] // 就像Seq.map:将映射功能应用于序列中的每个项目以构建新序列 > let map mapping seq1 = seq { for x in seq1 do yield mapping x } > map (fun x -> x * x) [1..10] val map: ('a -> 'b) -> seq<'a> -> seq<'b> val it: seq<int> = seq [1; 4; 9; 16; 25; 36; 49; 64; 81; 100] // 从0开始的连续整数的无限序列 > let naturals = let numbersFrom n = seq { yield n; yield! numbersFrom (n + 1) } numbersFrom 0 // 就像Seq.filter:返回一个序列,该序列仅由输入序列中满足谓词的项目组成 > let filter predicate seq1 = seq { for x in seq1 do if predicate x then yield x } > let evenNaturals = naturals |> filter (fun x -> x % 2 = 0) val naturals: seq<int> = seq [1; 2; 3; ...] val filter: ('a -> bool) -> seq<'a> -> seq<'a> val evenNaturals: seq<int> = seq [2; 4; 6; ...] // 就像Seq.concat:将一系列序列连接在一起 > let concat seqSeq = seq { for seq in seqSeq do yield! seq } > concat [[1;2;3];[10;20;30]] val concat: seq<#seq<'b>> -> seq<'b> val it: seq<int> = seq [1; 2; 3; 10; 20; 30]