(Mis) understanding of Seq.cache

I have the following code (inside a larger function, but that doesn't matter):

let ordersForTask = Dictionary<_, _>() let getOrdersForTask task = match ordersForTask.TryGetValue task with | true, orders -> orders | false, _ -> let orders = scenario.Orders |> Seq.filter (fun (order : Order) -> order.Tasks.Contains(task)) |> Seq.cache ordersForTask.Add(task, orders) orders 

From what I understand, this should cause order.Tasks.Contains() called exactly once for each pair of order and task values, no matter how often getOrdersForTask is called with the same task value, because the input the sequence only repeats (no more) once. However, this does not seem to be the case; if I call the function n times for all the task values ​​that I have, profiling shows n * number of orders * number of tasks calls Contains() .

Replacing Seq.cache with Seq.toList has the effect that I expected, but I want to avoid the cost of Seq.toList .

What I do not understand about Seq.cache or am mistaken in its use?

+6
source share

Source: https://habr.com/ru/post/986697/


All Articles