【问题标题】:OCaml pattern matchOCaml 模式匹配
【发布时间】:2016-04-11 16:15:46
【问题描述】:

在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?

【问题讨论】:

  • TLr 持有fieldsrec,而不是列表。也许将模式更改为| TLr { fields=f }
  • 我试过了,你是对的

标签: ocaml


【解决方案1】:

您似乎对fieldsrec = { fields : field list } 类型感到困惑。您应该听从 Jeffrey 的建议,改用 | Fields of field list

fieldsrec不是列表,是包含列表的记录,所以

print_fieldsrec fmt = function f :: fe -> ...

没有它的名字所暗示的类型。

您还忘记了递归 print_fieldsrec 的基本情况。

【讨论】: