问题描述
我是 Ocaml 和函数式编程的新手,我正在尝试实现一些尊重某些组件接口的数据结构。目前我遇到以下错误
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.
我正在尝试实现以下接口
type dec
val begin_block : dec -> dec
使用以下实现
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 }
我认为我的 Java 知识是这里的限制,我的问题是如何使强制转换为类型 dec 选项?将表设置为父级?
解决方法
OCaml 中的 option
是一个 variant,它可以容纳两件事之一:
- 表示存在内容的值以及该值是什么,注明
Some(value)
- 表示没有内容的值,注明
None
所以 dec option
是一种类型,它是一个可以保存 dec
值的选项。要么它有一个使用 Some
的值,要么它没有一个值,使用 None
。
要回答您的问题,您需要将 parent=table
替换为 parent=Some(table)
。
如果您想表示没有父母,您将拥有 parent=None
。
我强烈建议您阅读 OCaml 中的变体和 Option
,因为它们是该语言非常有用的强大功能。
对于此 thread here 中的 Option
有更多解释