【发布时间】:2017-05-25 15:36:18
【问题描述】:
我有以下类型:
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)])
我的实现没有考虑同一个键的多次出现。我不太确定如何解决这个问题,所以我得到了想要的功能?
【问题讨论】:
标签: f# f#-interactive