为什么F#懒洋洋地评估这个,下面两次?

Mar*_*rio 4 f# lazy-evaluation

我期待下面第一行中的引号在F#中急切地评估.它被懒惰地评估了两次.为什么?

let quotes = getFundsClosingPrice dbFunds // httpGet the closing prices
quotes
|> fun quotes ->
    let maxDate =
        quotes // <- quotes evaluated 1st time
        |> Seq.maxBy (
            fun (quote) -> 
                quote.TradedOn)
        |> fun q -> 
            q.TradedOn
    quotes
    |> Seq.map 
        (fun (quote) -> // <- quotes evaluated 2nd time. Why??
            { 
                Symbol = quote.Symbol; 
                ClosingPrice = quote.ClosingPrice; 
                TradedOn = maxDate
            }
        )
Run Code Online (Sandbox Code Playgroud)

我如何热切地评估它?

Bar*_*cki 7

Seq是IEnumerable,拥有大量方便的功能.每个映射函数(和相关的)从一开始就评估序列.

您可以在开头将序列转换为列表或数组:

let quotes = getFundsClosingPrice dbFunds |> List.ofSeq
Run Code Online (Sandbox Code Playgroud)

或者您可以使用Seq.cache

  • 谢谢!Seq.cache也是个不错的选择. (2认同)