OCaml:过滤地图并将值放入列表中

OCaml : filter map and put the values into a list

我可以按键过滤我的 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

谢谢

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

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 接受一个带有两个参数的函数(此处忽略第二个参数)。

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

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) 
       []