Seq.iter<'T> 函数 (F#)
将给定函数应用于集合的每个元素。
命名空间/模块路径: Microsoft.FSharp.Collections.Seq
程序集:FSharp.Core(在 FSharp.Core.dll 中)
// Signature:
Seq.iter : ('T -> unit) -> seq<'T> -> unit
// Usage:
Seq.iter action source
参数
异常
异常 |
Condition |
---|---|
在输入序列为 null 时引发。 |
备注
此函数在编译的程序集中名为 Iterate。 如果从 F# 以外的语言中访问函数,或通过反射访问成员,请使用此名称。
示例
下面的示例阐释 Seq.iter 的用法。
printf "Seq.iter: "
Seq.iter (fun (a,b) -> printf "(%d, %d) " a b) (seq { for i in 1..5 -> (i, i*i) })
以下示例说明如何使用 Seq.iter 来操作 CSV(逗号分隔值)文件。
// Write a test file
System.IO.File.WriteAllLines(@"test.csv", [| "Desmond, Barrow, Market Place, 2";
"Molly, Singer, Band, 12" |]);
/// This function builds an IEnumerable<string list> object that enumerates the CSV-split
/// lines of the given file on-demand
let CSVFileEnumerator(fileName) =
// The function is implemented using a sequence expression
seq { use sr = System.IO.File.OpenText(fileName)
while not sr.EndOfStream do
let line = sr.ReadLine()
let words = line.Split [|',';' ';'\t'|]
yield words }
// Now test this out on our test file, iterating the entire file
let test = CSVFileEnumerator(@"test.csv")
printfn "-------Enumeration 1------";
test |> Seq.iter (string >> printfn "line %s");
// Now do it again, this time determining the numer of entries on each line.
// Note how the file is read from the start again, since each enumeration is
// independent.
printfn "-------Enumeration 2------";
test |> Seq.iter (Array.length >> printfn "line has %d entries");
// Now do it again, this time determining the numer of entries on each line.
// Note how the file is read from the start again, since each enumeration is
// independent.
printfn "-------Enumeration 3------";
test |> Seq.iter (Array.map (fun s -> s.Length) >> printfn "lengths of entries: %A")
平台
Windows 8,Windows 7,Windows server 2012中,Windows server 2008 R2
版本信息
F#核心库版本
支持:2.0,4.0,可移植