这是 Seq.cache 在 F# 中的一个很好的用法吗
is this a good use of Seq.cache, in F#
我正在通过一个可变的 ConcurrentDictionary 来删除旧条目。
let private cache = ConcurrentDictionary<Instrument * DateTimeOffset, SmallSet>()
并且因为我无法在遍历键时删除条目,所以我想知道这是否适合 Seq.cache:
let old = DateTimeOffset.UtcNow.AddHours(-1.)
cache.Keys
|> Seq.filter (fun x -> snd x <= old)
|> Seq.cache
|> Seq.iter (fun x -> cache.TryRemove x |> ignore)
我从未使用过 Seq.cache,我认为它在两个循环之间创建了一个分隔。我理解它是如何正确工作的吗?
在您描述的场景中,我看不出有任何理由需要多次迭代集合。您可以查看字典中的 KeyValuePairs 并分析每个 KeyValuePair 是否符合您的条件。
所以,像这样的东西应该可以完成工作:
cache |> Seq.iter(function
| x when snd x.Key <= old -> cache.TryRemove(x.Key) |> ignore
| _ -> ())
我正在通过一个可变的 ConcurrentDictionary 来删除旧条目。
let private cache = ConcurrentDictionary<Instrument * DateTimeOffset, SmallSet>()
并且因为我无法在遍历键时删除条目,所以我想知道这是否适合 Seq.cache:
let old = DateTimeOffset.UtcNow.AddHours(-1.)
cache.Keys
|> Seq.filter (fun x -> snd x <= old)
|> Seq.cache
|> Seq.iter (fun x -> cache.TryRemove x |> ignore)
我从未使用过 Seq.cache,我认为它在两个循环之间创建了一个分隔。我理解它是如何正确工作的吗?
在您描述的场景中,我看不出有任何理由需要多次迭代集合。您可以查看字典中的 KeyValuePairs 并分析每个 KeyValuePair 是否符合您的条件。 所以,像这样的东西应该可以完成工作:
cache |> Seq.iter(function
| x when snd x.Key <= old -> cache.TryRemove(x.Key) |> ignore
| _ -> ())