代码之家  ›  专栏  ›  技术社区  ›  Jheel rathod

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

  •  1
  • Jheel rathod  · 技术社区  · 6 年前

    我想在ocaml中为链表创建一个递归类型,我为链表的元素定义了一个类型。我编写了以下代码

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

    但我有语法错误。如何更正错误?

    1 回复  |  直到 6 年前
        1
  •  6
  •   Isabelle Newbie    6 年前

    2016年4月,OCaml 4.03引入了这种语法(“作为数据类型构造函数参数的内联记录”): 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
    

    解决此问题的最佳方法是安装较新版本的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; }