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
參數
例外狀況
例外狀況 |
條件 |
---|---|
當輸入序列為 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,可攜式執行檔 (PE)。