Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 628
Mario Avatar asked Mar 06 '23 10:03

Mario


1 Answers

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

like image 106
Bartek Kobyłecki Avatar answered Mar 15 '23 23:03

Bartek Kobyłecki