gpt4 book ai didi

f# - 减去 Map<'a, int> 的两个 Map

转载 作者:行者123 更新时间:2023-12-05 01:35:32 24 4
gpt4 key购买 nike

我有以下类型:

type Multiset<'a when 'a: comparison> = MSet of Map<'a, int>

我想为此类型声明一个减去两个 MSet 的函数。

假设我有以下两个多重集:

let f = MSet (Map.ofList [("a",1);("b",2);("c",1)])
let g = MSet (Map.ofList [("a",1);("b",3);("c",1)])

我现在尝试创建这个采用两个多重集的减法函数。

let subtract fms sms =
match fms with
| MSet fs -> match sms with
| MSet ss ->
let toList ms = Map.fold (fun keys key value -> keys @ [for i = 1 to value do yield key] ) [] ms
let fromList l = match l with
| [] -> MSet(Map.ofList [])
| x::xs -> MSet(Map.ofList (x::xs |> Seq.countBy id |> Seq.toList))
let sfList = toList fs
let ssList = toList ss
fromList (List.filter (fun n -> not (List.contains n sfList)) ssList)

如果我运行:

subtract f g 

它返回:

MSet (map [])

这不是我想要的。 g 比 f 多一个 b,所以我希望它返回:

MSet(map [("b", 1)])

我的实现不考虑同一键的多次出现。我不太确定如何解决这个问题,所以我得到了想要的功能?

最佳答案

我怀疑你只是颠倒了你的论点,仅此而已。试试 subtract g f

也就是说,您的解决方案似乎比实际需要的要复杂得多。通过减去第二个 map 中的计数,然后删除非正计数来更新第一个 map 中的值怎么样?

let sub (MSet a) (MSet b) =
let bCount key = match Map.tryFind key b with | Some c -> c | None -> 0
let positiveCounts, _ =
a
|> Map.map (fun key value -> value - (bCount key))
|> Map.partition (fun _ value -> value > 0)
MSet positiveCounts

此外,您的实现中的嵌套匹配项不需要存在。如果你想匹配两个参数,你可以这样做:

match fms, sms with
| MSet fs, MSet ss -> ...

但即使是 也是矫枉过正 - 您可以只在参数声明中包含模式,就像我上面的实现一样。

至于重复键 - 在这种情况下,没有理由担心:两个参数都不能有重复键(因为它们都是 Map),算法永远不会产生任何。

关于f# - 减去 Map<'a, int> 的两个 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44184427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com