Mario
Mario

Reputation: 158

Why is F# evaluating this lazily and twice below?

I was expecting quotes in the first line below to be evaluated eagerly in F#. It is lazily evaluated twice instead. Why?

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
            }
        )

How can I have it evaluated eagerly?

Upvotes: 4

Views: 120

Answers (1)

Bartek Kobyłecki
Bartek Kobyłecki

Reputation: 2395

Seq is IEnumerable with big collection of handy functions. Each map function (and related) evaluate the sequence from the beginning.

You can convert sequence to list or array at the beginning:

let quotes = getFundsClosingPrice dbFunds |> List.ofSeq

or you can use Seq.cache

Upvotes: 7

Related Questions