OCaml 模式匹配
OCaml pattern match
在ast.ml中,结构如下:
type beantype =
| Bool
| Int
| TLr of fieldsrec
| TId of ident
and fieldsrec = { fields : field list }
and field =
| FIe of (ident * beantype)
在printer.ml中,我像下面这样使用它:
let rec print_bean fmt = function
| Bool -> put fmt "%s" "bool"
| Int -> put fmt "%s" "int"
| TLr f -> put fmt "%s" "{"; print_fieldsrec fmt f ; put fmt "%s" "}"
| TId id -> put fmt "%s" id
and print_fieldsrec fmt = function
| f :: fe -> print_field fmt f; put fmt "%s" "," ; print_fieldsrec fmt fe
and print_field fmt = function
| FIe (id, beantype) -> put fmt "%s" id; put fmt "%s" ":"; print_bean fmt beantype
但是它说 print_fieldsrec
中的不同模式匹配
Error: This pattern matches values of type 'a list
but a pattern was expected which matches values of type
Bean_ast.fieldsrec
如何更改 printer.ml?
您似乎对 fieldsrec = { fields : field list }
类型感到困惑。您应该听从 Jeffrey 的建议,改用 | Fields of field list
。
fieldsrec
不是一个列表,它是一个包含列表的记录,所以
print_fieldsrec fmt = function f :: fe -> ...
没有其名称所暗示的类型。
你还忘记了递归的基本情况print_fieldsrec
。
在ast.ml中,结构如下:
type beantype =
| Bool
| Int
| TLr of fieldsrec
| TId of ident
and fieldsrec = { fields : field list }
and field =
| FIe of (ident * beantype)
在printer.ml中,我像下面这样使用它:
let rec print_bean fmt = function
| Bool -> put fmt "%s" "bool"
| Int -> put fmt "%s" "int"
| TLr f -> put fmt "%s" "{"; print_fieldsrec fmt f ; put fmt "%s" "}"
| TId id -> put fmt "%s" id
and print_fieldsrec fmt = function
| f :: fe -> print_field fmt f; put fmt "%s" "," ; print_fieldsrec fmt fe
and print_field fmt = function
| FIe (id, beantype) -> put fmt "%s" id; put fmt "%s" ":"; print_bean fmt beantype
但是它说 print_fieldsrec
中的不同模式匹配Error: This pattern matches values of type 'a list
but a pattern was expected which matches values of type
Bean_ast.fieldsrec
如何更改 printer.ml?
您似乎对 fieldsrec = { fields : field list }
类型感到困惑。您应该听从 Jeffrey 的建议,改用 | Fields of field list
。
fieldsrec
不是一个列表,它是一个包含列表的记录,所以
print_fieldsrec fmt = function f :: fe -> ...
没有其名称所暗示的类型。
你还忘记了递归的基本情况print_fieldsrec
。