简体   繁体   English

如何在 f# 中创建地图的副本?

[英]How to create a copy of a map in f#?

   let students =
    Map.empty.
          Add("ABC", "97").
          Add("Jill", "98");;
    printfn "Map - students: %A" students

This I know will create a map named students.我知道这将创建一个名为学生的地图。 I was thinking a way to create a copy of this map, with same key and value.我在想一种方法来创建此地图的副本,具有相同的键和值。 I checked the documentation for f#, and didn't find any methods that clone/create a copy of map.我检查了 f# 的文档,并没有找到任何克隆/创建地图副本的方法。

F# maps are immutable. F# 映射是不可变的。 This means that "changing" a map actually means creating a copy with some slight changes.这意味着“更改”地图实际上意味着创建一个带有一些细微更改的副本。 The copy process uses tricks to make it much faster than a full copy.复制过程使用技巧使其比完整复制快得多。 The new version can actually point back to the old version for most of the data.对于大部分数据,新版本实际上可以指向旧版本。 This is safe to do because the maps are immutable: they can never change.这是安全的,因为映射是不可变的:它们永远不会改变。

This means that there is no possible reason to copy a map, except to warm up your CPU 😆这意味着没有可能的理由复制地图,除了预热你的 CPU 😆

The same applies to List and Set in F#, as they are also immutable.这同样适用于 F# 中的ListSet ,因为它们也是不可变的。 It takes a while to get used to working with immutable data structures but life gets easier once you do.习惯使用不可变的数据结构需要一段时间,但一旦你习惯了,生活就会变得更轻松。


By the way you can create the map with less code like this:顺便说一句,您可以使用较少的代码创建地图,如下所示:

let students =
    [ "ABC", "97"
      "Jill", "98" ]
    |> Map

Here's one way to do it.这是一种方法。

let copy =
    students
    |> Seq.map (fun pair -> pair.Key, pair.Value)
    |> Map

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

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