简体   繁体   English

在 F# 中多次更新 map

[英]Updating map multiple times in F#

Let's say I have a map M:Map<int, bool> (initially empty).假设我有一个 map M:Map<int, bool> (最初为空)。 I want to update this time.这次我想更新。 I have a list L = [1.. 100] and for each element in this list, I want to set the corresponding value in M false.我有一个列表L = [1.. 100]并且对于此列表中的每个元素,我想将M中的相应值设置为 false。 So something like, [1.. 100] |> List.map (fun x -> M.Add(x, false)) .类似于[1.. 100] |> List.map (fun x -> M.Add(x, false)) But M.Add() returns a new map every time and the updates are not reflected.但是M.Add()每次都会返回一个新的 map 并且不会反映更新。 How can I do this update in an idiomatic F# way?如何以惯用的 F# 方式进行此更新?

You can use a fold for this:您可以为此使用折叠:

let m = [1 .. 100] 
        |> List.fold( fun (acc:Map<int,bool>) x -> acc.Add(x, false)) Map.empty

A fold takes an accumulator and the current value as parameters.折叠将累加器和当前值作为参数。 You can here use the Add method to return the updated Map.您可以在此处使用 Add 方法返回更新后的 Map。

For your specific scenario you may also consider a dictionary:对于您的特定情况,您还可以考虑使用字典:

let m2 = [1 .. 100] 
         |>List.map(fun x->(x,false))
         |>dict

I think I got a working solution.我想我有一个可行的解决方案。 Instead of declaring a Map first and then updating it (which would return a new Map every time), I constructed a list first and then converted the list to a Map.我没有先声明 Map 然后更新它(每次都会返回一个新的 Map),而是先构建一个列表,然后将该列表转换为 Map。

[1 .. 100]
|> List.map
   (fun x ->
       (x, false)
   )
|> Map.ofList

I don't know if this solution is any good as I'm fairly new to F#.我不知道这个解决方案是否有用,因为我对 F# 还很陌生。 I'll be glad to know if this solution can be improved.我很高兴知道这个解决方案是否可以改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM