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
977 views
in Technique[技术] by (71.8m points)

ocaml - cast custom type to "option" custom type

I'm new with Ocaml and functional programming, and I'm trying to implement some data structures that respect some component interfaces. At the moment I'm the problem with the following error

File "src/symbol_table.ml", line 24, characters 39-45:
24 |   { variables=Hashtbl.create 0; parent=Option(table) }
                                            ^^^^^^
Error: This variant expression is expected to have type dec option
       The constructor Option does not belong to type option
Command exited with code 2.

And I'm trying to implement the following interface

type dec

val begin_block : dec -> dec

With the following implementation

type dec = {
  variables: (Ast.identifier, Ast.typ) Hashtbl.t;
  parent: dec option
}

let begin_block (table: dec) =
  logger#debug "Starting scope";
  { variables=Hashtbl.create 0; parent=table }

I think that my Java knowledge is the limit here, and my question is how I can make the cast to type dec option? to set the table as a parent?

question from:https://stackoverflow.com/questions/65644425/cast-custom-type-to-option-custom-type

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

1 Reply

0 votes
by (71.8m points)

An option in OCaml is a variant that can hold one of two things :

  • either a value that signifies there is content and what the value is, noted Some(value)
  • either a value that signifies there is no content, noted None

So a dec option is a type that is an option that can hold dec values. Either it has a value using Some or it doesn't have a value, using None.

To answer your question, you need to replace parent=table with parent=Some(table).

If you wanted to signify that there was no parent you would have parent=None.

I highly recommend you go and read up on variants and Option in OCaml, as they are extremely useful power features of the language.

There's some more explanations of what Option is in this thread here


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

...