在OCaml中具有选项类型条目的记录上的模式匹配

时间:2015-06-25 20:43:16

标签: pattern-matching ocaml

基本上我已经定义了这样的记录类型:

and exp = Bil_t.exp = {
  var: var option;
  binop: binop option;
  load: load option;
  store: store option;
  cast: cast option;
  inte: inte option;
  let_exp: let_exp option
}

我正在考虑使用模式匹配来处理它,如下所示:

match rexp with
    | {None;binop;None;None;None;None;None} -> trans_binop @@ strip binop
    | {var;None;None;None;None;None;None} -> BU.inte_to_string @@ strip @@ mark inte
    | _ -> failwith "undefined"

对不起上面的杂乱代码。所以基本上我编译上面的代码,我得到错误:

Error: Syntax error

有人可以给我一些帮助......我只是不知道这里有什么问题......

1 个答案:

答案 0 :(得分:3)

记录模式需要包含字段名称。

type exp = {
  var: int option;
  binop: int option;
  load: int option;
  store: int option;
  cast: int option;
  inte: int option;
  let_exp: int option
}

let f rexp =
    match rexp with
    | { var = None; binop = Some b; load = None; store = None;
        cast = None; inte = None; let_exp = None
      } -> b
    | _ -> failwith "undefined"

示例:

# let r = { var = None; binop = Some 14; load = None; store = None; 
            cast = None; inte = None; let_exp = None };;
val r : exp =
  {var = None; binop = Some 14; load = None; store = None; cast = None;
   inte = None; let_exp = None}
# f r;;
- : int = 14