OCaml maps a string to a list of strings

I am trying to create a dictionary in OCaml that maps a string to a list of strings. I referenced this tutorial for a baseline for a string map, but I need help creating a list.

Here is what I want to do in Python:

>>> food = {}
>>> food["fruit"] = ("blueberry", "strawberry", "kiwi")
>>> food["veggie"] = ("broccoli", "kale")
>>> for k in food:
...     for v in food[k]:
...         print k, "-->",v
...
fruit --> blueberry
fruit --> strawberry
fruit --> kiwi
veggie --> broccoli
veggie --> kale

Thank you in advance

+4
source share
2 answers

You can just use lists,

let food = [
  "fruit",  ["blueberry"; "strawberry"; "kiwi"];
  "veggie", ["broccoli"; "kale"]
]

and use List.assocto access it:

List.assoc "fruit" food

will be rated as

- : string list = ["blueberry"; "strawberry"; "kiwi"]

If you need real cards with a logarithmic search, you can use the module Map. In the standard library, it provides a functor Makethat creates a map for user-provided data, for example,

module Strings = Map.Make(String)

Strings, string - . :

let map = Strings.empty 
Strings.add "fruit" ["blueberry"; "strawberry"; "kiwi"] map

, , . , , python, Hashtbl.

Hashtbl:

let food = Hashtbl.create 16
Hashtbl.add food "fruit" ["blueberry"; "strawberry"; "kiwi"]
Hashtbl.add food "veggie" ["broccoli"; "kale"]
Hashtbl.find food "veggie"

- : string list = ["broccoli"; "kale"]
+4

OCaml . , ( ), ( ).

:

# module myStrings = Map.Make(String);;
module MyStrings :
sig
 . . .
end
# let m0 = MyStrings.empty;;
val m0 : 'a MyStrings.t = <abstr>
# let m1 = MyStrings.add "abc" ["def"; "ghi"] m0;;
val m1 : string list MyStrings.t = <abstr>
# MyStrings.iter
    (fun s ss -> Printf.printf "%s --> %s\n" s (String.concat " " ss))
    m1;;
abc --> def ghi
- : unit = ()
+2

Source: https://habr.com/ru/post/1626429/


All Articles