Seq.delay<'T> 函数 (F#)
返回一个序列,该序列是根据序列的给定延迟规范生成的。
命名空间/模块路径:Microsoft.FSharp.Collections.Seq
程序集:FSharp.Core(在 FSharp.Core.dll 中)
// Signature:
Seq.delay : (unit -> seq<'T>) -> seq<'T>
// Usage:
Seq.delay generator
参数
返回值
结果序列。
备注
每次请求序列的 IEnumerator 时,都计算输入函数。
此函数在编译的程序集中名为 Delay。 如果从 F# 以外的语言中访问函数,或通过反射访问成员,请使用此名称。
示例
以下代码演示如何使用 Seq.delay 来延迟一个由通常立即计算的集合创建而成的序列的计算。
// Normally sequences are evaluated lazily. In this case,
// the sequence is created from a list, which is not evaluated
// lazily. Therefore, without Seq.delay, the elements would be
// evaluated at the time of the call to makeSequence.
let makeSequence function1 maxNumber = Seq.delay (fun () ->
let rec loop n acc =
printfn "Evaluating %d." n
match n with
| 0 -> acc
| n -> (function1 n) :: loop (n - 1) acc
loop maxNumber []
|> Seq.ofList)
printfn "Calling makeSequence."
let seqSquares = makeSequence (fun x -> x * x) 4
let seqCubes = makeSequence (fun x -> x * x * x) 4
printfn "Printing sequences."
printfn "Squares:"
seqSquares |> Seq.iter (fun x -> printf "%d " x)
printfn "\nCubes:"
seqCubes |> Seq.iter (fun x -> printf "%d " x)
Output
以下代码示例等同于之前的示例,区别是它不使用 Seq.delay。 请注意输出的差异。
// Compare the output of this example with that of the previous.
// Notice that Seq.delay delays the
// execution of the loop until the sequence is used.
let makeSequence function1 maxNumber =
let rec loop n acc =
printfn "Evaluating %d." n
match n with
| 0 -> acc
| n -> (function1 n) :: loop (n - 1) acc
loop maxNumber []
|> Seq.ofList
printfn "Calling makeSequence."
let seqSquares = makeSequence (fun x -> x * x) 4
let seqCubes = makeSequence (fun x -> x * x * x) 4
printfn "Printing sequences."
printfn "Squares:"
seqSquares |> Seq.iter (fun x -> printf "%d " x)
printfn "\nCubes:"
seqCubes |> Seq.iter (fun x -> printf "%d " x)
Output
平台
Windows 8,Windows 7,Windows server 2012中,Windows server 2008 R2
版本信息
F#核心库版本
支持:2.0,4.0,可移植