简体   繁体   English

带构造函数的ocaml递归类型记录

[英]ocaml recursive type record with constructors

I wanted to make a recursive type for linked list in ocaml for which i defined a type for the elements of the list. 我想为ocaml中的链表做一个递归类型,为此我定义了链表元素的类型。 I wrote the following code 我写了下面的代码

  type elem=
  |Nil
  |Elem of {content:int;mutable next:elem};;

But i am getting syntax error. 但是我收到语法错误。 How to correct the error? 如何纠正错误?

This syntax ("inline records as arguments to datatype constructors") was introduced with OCaml 4.03 in April 2016: http://ocaml.org/releases/4.03.html 此语法(“将内联记录作为数据类型构造函数的参数”)于2016年4月随OCaml 4.03引入: http : //ocaml.org/releases/4.03.html

Some systems, like my Ubuntu, include older versions of OCaml, which don't support this: 某些系统,例如我的Ubuntu,包括较旧版本的OCaml,不支持此功能:

$ /usr/bin/ocaml
        OCaml version 4.02.3

# type elem=
    |Nil
    |Elem of {content:int;mutable next:elem};;  
Error: Syntax error

The best way to fix this would be to install a newer version of OCaml and to keep it updated, ideally using OPAM: https://opam.ocaml.org/doc/Install.html 解决此问题的最佳方法是安装较新版本的OCaml并保持更新,最好使用OPAM: https ://opam.ocaml.org/doc/Install.html

If that's not an option, you can work around it by declaring the algebraic data type and the record type and the same time, using a single mutually recursive definition ( type t1 = ... and t2 = ... ): 如果不是这种选择,则可以通过使用单个相互递归定义( 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM