AlexB
AlexB

Reputation: 3548

OCaml : filter map and put the values into a list

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

Upvotes: 2

Views: 4717

Answers (2)

AlexB
AlexB

Reputation: 3548

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

Upvotes: 1

Reimer Behrends
Reimer Behrends

Reputation: 8740

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

Upvotes: 1

Related Questions