Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ocaml - Create a personal type with an Hashtbl as attribute

I'm trying to create a type like this:

type variable {
  id: string;
  tipe: int
}

type dec {
   variables: variable list;
   parent: dec option
}

During the execution of my program, I need to have a list of dec and add to runtime the variables, but with the list, I can't do that as it is an immutable data structure.

I'm trying to change the implementation and use a hash map to store the variable, for example, I need to store the variables as a hashtable with (key: string and value: int) but I have no idea how to implement a hash map with OCaml inside the type declaration.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a record type where each value of the type contains a hash table. The hash table maps from string to int:

type dec = {
    variables: (string, int) Hashtbl.t;
    parent: dec option;
}

There are many other ways to set this up. In particular, this uses the generic (polymorphic) hash table interface. If you want more control over the behavior you can use the functorial interface (which allows you to specify your own comparison and hashing functions).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...