将自定义类型转换为 "option" 自定义类型
cast custom type to "option" custom type
我是 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 选项?将 table 设置为父对象?
OCaml 中的 option
是一个 variant 可以容纳以下两个事物之一:
- 要么是表示有内容的值,要么是值,注意
Some(value)
- 表示没有内容的值,注释
None
所以 dec option
是一种类型,它是一个可以容纳 dec
值的选项。它要么使用 Some
有值,要么没有值,使用 None
.
要回答您的问题,您需要将 parent=table
替换为 parent=Some(table)
。
如果你想表示没有 parent 你会 parent=None
.
我强烈建议您去阅读 OCaml 中的变体和 Option
,因为它们是该语言极其有用的强大功能。
Option
在这个 thread here
中有更多解释
我是 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 选项?将 table 设置为父对象?
OCaml 中的 option
是一个 variant 可以容纳以下两个事物之一:
- 要么是表示有内容的值,要么是值,注意
Some(value)
- 表示没有内容的值,注释
None
所以 dec option
是一种类型,它是一个可以容纳 dec
值的选项。它要么使用 Some
有值,要么没有值,使用 None
.
要回答您的问题,您需要将 parent=table
替换为 parent=Some(table)
。
如果你想表示没有 parent 你会 parent=None
.
我强烈建议您去阅读 OCaml 中的变体和 Option
,因为它们是该语言极其有用的强大功能。
Option
在这个 thread here