简体   繁体   中英

Error in OCaml data structure type

blow is the ast.ml, all are same in ast.mli

type ident = string

type beantype =
    | Bool
    | Int
    | { fields : field list }
    | TId of ident
and field =
    (ident * beantype)

in parser.mly, i use the fields as list

typespec :
    | BOOL { Bool }
    | INT { Int }
    | LBRAK fields RBRAK { { fields = List.rev $2 } }
    | IDENT { TId $1 }

fields :
    | fields COMMA field { $3 :: $1 }

field :
    | IDENT COLON typespec { ($1, $3) }

However there is error like this:

ocamlc  -c bean_ast.mli
File "bean_ast.mli", line 6, characters 3-4:
Error: Syntax error
make: *** [bean_ast.cmi] Error 2

why there is an error?

This declaration:

type beantype =
    | Bool
    | Int
    | { fields : field list }
    | TId of ident

isn't valid in OCaml. Each of the variants needs a tag, ie, a capitalized identifier of the variant. Your third variant doesn't have one.

It's also not currently possible to declare a new record type as part of a variant type.

The following will work:

type ident = string
type beantype =
    | Bool
    | Int
    | Fields of fieldrec
    | Tid of ident
and fieldrec = { fields: field list }
and field = ident * beantype

Personally I might declare the type as follows:

type ident = string
type beantype =
    | Bool
    | Int
    | Fields of field list
    | Tid of ident
and field = ident * beantype

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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