Как использовать этот словарь в файле main.ml (создать словарь, добавить элементы, удалить ....)? - PullRequest
0 голосов
/ 01 мая 2019

Я нашел толковый словарь и вашу реализацию.Я хочу создать словарь, используя эти модули ниже, но я получаю эту ошибку:

Unbound Value.

Я новичок в функциональной парадигме.Я попробовал эту книгу, но я все еще потерялся: http://dev.realworldocaml.org/maps-and-hashtables.html

И словарь и AssociateList отсюда: https://www.cs.cornell.edu/courses/cs3110/2014sp/recitations/7/functional-stacks-queues-dictionaries-fractions.html

let x = Dictionary.AssocList.create ;;

open Dictionary.AssocList
enviroment = create() 
Unbound type constructor stringAssocListAssocList

module type DICTIONARY =
  sig
    (* An 'a dict is a mapping from strings to 'a.                                                                                                                                
       We write {k1->v1, k2->v2, ...} for the dictionary which                                                                                                                    
       maps k1 to v1, k2 to v2, and so forth. *)
    type key = string
    type 'a dict

    (* make an empty dictionary carrying 'a values *)
    val make : unit -> 'a dict

    (* insert a key and value into the dictionary *)
    val insert : 'a dict -> key -> 'a -> 'a dict

    (* Return the value that a key maps to in the dictionary.                                                                                                                     
     * Raise NotFound if there is not mapping for the key. *)
    val lookup : 'a dict -> key -> 'a
    exception NotFound

    (* applies a function to all the elements of a dictionary;                                                                                                                    
       i.e., if a dictionary d maps a string s to an element a,                                                                                                                   
       then the dictionary (map f d) will map s to f(a). *)
    val map : ('a -> 'b) -> 'a dict -> 'b dict
  end

module AssocList : DICTIONARY =
  struct
    type key = string
    type 'a dict = (key * 'a) list

    (* AF: The list [(k1,v1), (k2,v2), ...] represents the dictionary                                                                                                             
     * {k1 -> v1, k2 -> v2, ...}, except that if a key occurs                                                                                                                     
     * multiple times in the list, only the earliest one matters.                                                                                                                 
     * RI: true.                                                                                                                                                                  
     *)

    let make() : 'a dict = []

    let insert (d : 'a dict) (k : key) (x : 'a) : 'a dict =
      (k, x) :: d

    exception NotFound

    let rec lookup (d : 'a dict) (k : key) : 'a =
      match d with
      | [] -> raise NotFound
      | (k', x) :: rest ->
         if k = k' then x
         else lookup rest k
    let map (f : 'a -> 'b) (d : 'a dict) =
      List.map (fun (k, a) -> (k, f a)) d
  end

1 Ответ

0 голосов
/ 05 мая 2019

Предположим, что ваша словарная реализация сохранена в файле с именем dictionary.ml. Чтобы использовать этот модуль, вы должны open его и дать AssocList более короткое имя для удобного (необязательно)

open Dictionary
module D = AssocList

Чтобы создать новый пустой словарь, вы должны:

let dict = D.make ()

Чтобы вставить элемент и сделать из этого новый дикт, вы должны сделать:

let new_dict = D.insert dict "one" 1

"one" - это ключ, а 1 - это значение.

Если вы хотите увидеть все элементы в словаре, вам нужно будет сделать новую функцию или сделать доступным тип (key * 'a) list, что-то вроде этого в вашей подписи

type 'a dict = (key * 'a) list (* This will make dict elements available *)
type 'a dict (* This will make the dict available but you can't view the elements *)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...