确保您已阅读该函数的 docs。
merge 采用三个函数和两个映射。这两个映射具有相同的键类型,但不同的值类型。映射结果表单merge 当然必须有一个单一的值类型,所以我们必须告诉merge 如果发生了什么
- 仅存在第一个提供的映射中的值
- 仅存在第二个提供的映射中的值
- 两个值都存在
例如,假设我们有一个要合并的地图Map Int Text 和一个地图Map Int Bool,我们只是说生成的地图应该表明我们属于上述三种情况中的哪一种。我们可以为此定义一个类型:
data EitherOrBoth a b
= EOBLeft a
| EOBRight b
| EOBBoth (a, b)
deriving (Eq, Show)
现在我们可以在合并中定义函数来表示“在左侧添加一个值”、“在右侧添加一个值”和“在一个元组中添加两个值”:
mergeWithBoth : (MapKey k) => Map k a -> Map k b -> Map k (EitherOrBoth a b)
mergeWithBoth = merge (\k x -> Some (EOBLeft x)) (\k y -> Some (EOBRight y)) (\k x y -> Some (EOBBoth (x, y)))
使用脚本尝试整个过程:
import Daml.Script
import DA.Next.Map (Map, MapKey, merge, fromList)
data EitherOrBoth a b
= EOBLeft a
| EOBRight b
| EOBBoth (a, b)
deriving (Eq, Show)
mergeWithBoth : (MapKey k) => Map k a -> Map k b -> Map k (EitherOrBoth a b)
mergeWithBoth = merge (\k x -> Some (EOBLeft x)) (\k y -> Some (EOBRight y)) (\k x y -> Some (EOBBoth (x, y)))
testMerge = script do
let
mapIntText : Map Int Text = fromList[(1, "Hello"), (2, "World")]
mapIntDec : Map Int Bool = fromList[(2, True), (3, False)]
assert (mergeWithBoth mapIntText mapIntDec
== fromList [(1, EOBLeft "Hello"),(2, EOBBoth ("World", True)), EOBRight False)])
return (mergeWithBoth mapIntText mapIntDec)