OCaml : filter map and put the values into a list

天涯浪子 提交于 2021-02-11 04:53:35

问题


I can filter my map by key :

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 *)

After that, I want to put the values into a list. How can I do this in OCaml?

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

Thanks


回答1:


You can use bindings to retrieve the key/value pairs of a map and then further process them to extract the values. For example:

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

We use List.split to convert a list of pairs into a pair of lists (one containing the keys, one the values) and then snd to extract the list of values.

Note also that filter takes a function with two arguments (the second of which gets ignored here).




回答2:


Here is how I did it. I called fold after 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) 
       [] 


来源:https://stackoverflow.com/questions/37512794/ocaml-filter-map-and-put-the-values-into-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!