Pattern match on records with option type entries in OCaml

和自甴很熟 提交于 2019-12-11 09:38:34

问题


basically I have defined a record type like this:

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
}

And I am thinking to use a pattern match to process it, something like this:

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"

Sorry for the messy code above. So basically I compile the above code, and I get the error:

Error: Syntax error

Could anyone give me some help on this.. I just don't know what is wrong here...


回答1:


Record patterns need to include the field names.

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"

Example:

# 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


来源:https://stackoverflow.com/questions/31060425/pattern-match-on-records-with-option-type-entries-in-ocaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!