0 recursion ocaml types linked-list
我想为ocaml中的链表做一个递归类型,为此我定义了链表元素的类型。我写了下面的代码
type elem=
|Nil
|Elem of {content:int;mutable next:elem};;
Run Code Online (Sandbox Code Playgroud)
但是我收到语法错误。如何纠正错误?
这种语法(“将内联记录作为数据类型构造函数的参数”)是OCaml 4.03在2016年4月引入的:http : //ocaml.org/releases/4.03.html
某些系统,例如我的Ubuntu,包括较旧版本的OCaml,不支持此功能:
$ /usr/bin/ocaml
OCaml version 4.02.3
# type elem=
|Nil
|Elem of {content:int;mutable next:elem};;
Error: Syntax error
Run Code Online (Sandbox Code Playgroud)
解决此问题的最佳方法是安装较新版本的OCaml并保持更新,最好使用OPAM:https ://opam.ocaml.org/doc/Install.html
如果不是这种选择,则可以通过使用单个相互递归的定义(type t1 = ... and t2 = ...
)同时声明代数数据类型和记录类型来解决此问题:
# type elem = Nil | Elem of elem_record
and elem_record = { content: int; mutable next: elem };;
type elem = Nil | Elem of elem_record
and elem_record = { content : int; mutable next : elem; }
Run Code Online (Sandbox Code Playgroud)