【问题标题】:OCaml : filter map and put the values into a listOCaml:过滤映射并将值放入列表
【发布时间】:2016-09-27 12:34:17
【问题描述】:

我可以按键过滤我的map

module PairKeys =
struct
  type t = string * string
  let compare (x0,y0) (x1,y1) =
    match String.compare x0 x1 with
    | 0 -> String.compare y0 y1
    | c -> c
end

module StringMap = Map.Make(PairKeys);;
....

let put_key_values_into_a_list (key_searched : string) = 
    StringMap.filter (fun key -> key = key_searched)
(* should return a list of the values in the filtered map *)

之后,我想将这些值放入一个列表中。 我怎样才能在 OCaml 中做到这一点?

Map.Make 文档: http://caml.inria.fr/pub/docs/manual-ocaml/libref/Map.Make.html

谢谢

【问题讨论】:

  • 您使用的映射不能为同一个键保存多个值,即它不是 multimap。除非您更改过滤谓词,否则您想要的代码大致相当于MyMap.find key_searched m 或更准确地说是[MyMap.find key_searched m](并且列表将始终是单例)
  • 也许将这些信息包含在帖子中是个好主意,这样人们就不会尝试“优化”代码:)
  • @Anton Trunov 好的,谢谢!我改进了我的问题。
  • 仍然,key 匹配整个对,而不是它的第一个或第二个组件。你想要的可能类似于StringMap.filter (fun (key, _) _ -> key = key_searched)

标签: ocaml


【解决方案1】:

您可以使用bindings 检索映射的键/值对,然后进一步处理它们以提取值。例如:

let put_key_values_into_a_list key_searched map =
    MyMap.filter (fun key _ -> key = key_searched) map
    |> MyMap.bindings |> List.split |> snd

我们使用List.split 将一对列表转换为一对列表(一个包含键,一个包含值),然后使用snd 提取值列表。

另请注意,filter 接受一个带有两个参数的函数(第二个在此处被忽略)。

【讨论】:

  • 你觉得我的回答怎么样?
  • @AlexB 它具有相同的功能,分配的临时值更少,但结果相反(这可能或可能不重要)。
【解决方案2】:

这就是我的做法。我在过滤器后调用折叠:

let put_key_values_into_a_list key_searched map =
    MyMap.fold (fun _ i acc -> i::acc) 
       (MyMap.filter (fun (x,_) _ -> x = key_searched) map) 
       [] 

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多