【发布时间】:2016-09-27 18:50:03
【问题描述】:
在这个 SO post 中,添加
inSeq
|> Seq.length
|> printfn "%d lines read"
导致 inSeq 中的惰性序列被读入。
好的,我已经扩展了该代码并想首先打印出该序列(请参阅下面的新程序)。
当 Visual Studio (2012) 调试器到达时
inSeq |> Seq.iter (fun x -> printfn "%A" x)
读取过程重新开始。当我使用调试器检查inSeq 时,inSeq 中似乎没有任何元素。
如果我首先将元素读入inSeq,我如何查看(检查)这些元素,为什么它们不会在调用Seq.iter 时打印出来?
open System
open System.Collections.Generic
open System.Text
open System.IO
#nowarn "40"
let rec readlines () =
seq {
let line = Console.ReadLine()
if not (line.Equals("")) then
yield line
yield! readlines ()
}
[<EntryPoint>]
let main argv =
let inSeq = readlines ()
inSeq
|> Seq.length
|> printfn "%d lines read"
inSeq |> Seq.iter (fun x -> printfn "%A" x)
// This will keep it alive enough to read your output
Console.ReadKey() |> ignore
0
我在某处读到延迟评估的结果没有被缓存。这就是这里发生的事情吗?如何缓存结果?
【问题讨论】:
-
我将在哪里使用它以及为什么?
-
let inSeq = readlines () |> Seq.cache -
Seq本质上是一个IEnumerable<T>。就像 C# 一样,每次迭代都会重新启动迭代器。当编译器或 Resharper 检测到IEnumerable<T>的多次迭代时,实际上会发出警告