简体   繁体   English

如何通过F#中的键将两个地图相交?

[英]How do I intersect two Maps by their keys in F#

I want to interesct two F# Maps, which have common keys, into a Map that has the common keys and a tuple of both values as it's value. 我想将具有公共密钥的两个F#地图集成到一个Map中,该Map具有公共密钥和两个值的元组作为其值。

ie the signature is something like: 即签名是这样的:

Map<K, T1> -> Map<K, T2> -> Map<K, T1 * T2>

Any ideas of an easy functional & performant way to do it? 有任何简单实用且高效的方法吗?

I know I can intersect the sets of keys and then build out a new map, I'd just like to do something that doesn't feel so dirty... 我知道我可以将各组键交叉,然后构建一个新的地图,我只想做一些不那么脏的事情......

I had a similar problem before and finally solved it like this: 之前我遇到过类似的问题,最后解决了这个问题:

let intersect a b = Map (seq {
    for KeyValue(k, va) in a do
        match Map.tryFind k b with
        | Some vb -> yield k, (va, vb)
        | None    -> () })

One approach is to implement this in terms of Map.fold : 一种方法是根据Map.fold实现这Map.fold

module Map =
    let intersect (m1:Map<'K, 'V1>) (m2:Map<'K, 'V2>) =
        (Map.empty, m1) ||> Map.fold (fun acc k v1 ->
            (acc, Map.tryFind k m2) ||> Option.fold (fun acc v2 ->
                acc |> Map.add k (v1, v2)))

I posted this prematurely and deleted it, as I'm unsure whether this counts as just intersecting the keys... but I guess it can't hurt to undelete it, since it's fairly short: 我过早地发布了这个并删除了它,因为我不确定这是否只是交叉键...但我想它取消删除它不会有害,因为它相当短:

let intersect otherMap =
    Map.filter (fun k _ -> Map.containsKey k otherMap)
    >> Map.map (fun k v1 -> v1, otherMap.[k])

Edit Without intermediate map, via a sequence: 编辑没有中间地图,通过序列:

let intersect otherMap =
    Map.toSeq >> Seq.choose (fun (k, v) ->
        Map.tryFind k otherMap |> Option.map (fun v2 -> v, v2))
    >> Map.ofSeq

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

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