问题描述
我可以通过以下方式过滤我的地图关键:
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 *)
在那之后,我想将这些值放入一个列表中.我怎样才能在 OCaml 中做到这一点?
After that, I want to put the values into a list.How can I do this in OCaml?
Map.Make 文档:http://caml.inria.fr/pub/docs/manual-ocaml/libref/Map.Make.html
Map.Make documentation :http://caml.inria.fr/pub/docs/manual-ocaml/libref/Map.Make.html
谢谢
推荐答案
您可以使用 bindings
来检索映射的键/值对,然后进一步处理它们以提取值.例如:
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
我们使用 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.
还要注意 filter
接受一个带有两个参数的函数(这里忽略第二个参数).
Note also that filter
takes a function with two arguments (the second of which gets ignored here).
这篇关于OCaml:过滤映射并将值放入列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!