Functional programming 在OCaml中,我在AST文件中定义了stmt可以是stmt或stmt List,但在函数中使用时,它会报告错误
我在AST文件中定义了stmt=|stmt | stmt List。那么我有一个参数类型为stmt的函数,我不能使用stmt List吗?有人能告诉我怎么做吗 编译时的错误是:Functional programming 在OCaml中,我在AST文件中定义了stmt可以是stmt或stmt List,但在函数中使用时,它会报告错误,functional-programming,ocaml,Functional Programming,Ocaml,我在AST文件中定义了stmt=|stmt | stmt List。那么我有一个参数类型为stmt的函数,我不能使用stmt List吗?有人能告诉我怎么做吗 编译时的错误是: Error: This expression has type Ast.stmt list but an expression was expected of type Ast.stmt 下面是我的函数代码: let rec eval_stmt (stmt:stmt) (ps:proc_state) (e
Error: This expression has type Ast.stmt list
but an expression was expected of type Ast.stmt
下面是我的函数代码:
let rec eval_stmt (stmt:stmt) (ps:proc_state) (env:environment) (store:store) : (stmtEvalRes*proc_state*store) = match stmt with
| PrintInt e ->
let r = eval_expr e ps env store in
print_int r; (Next, ps, store)
| PrintStr s ->
print_string (Str.global_replace (Str.regexp "\\\\n") "\n" s);
(* Escaping characters here because it's not done in the parser *)
(Next, ps, store)
| List (stmt1::stmts) -> eval_stmt stmt1 ps env store;
eval_stmt stmts ps env store;(Next,ps,store)
下面是我的AST文件:
type stmt = (* Statements in C-flat language *)
Empty
| VarAss of expr * expr
(* Expressions can be statements in themselves. This is most useful when
the expression is a function call. Calls to built-in functions are
just special cases of calls. *)
| Expr of expr
| PrintStr of string (* string is only static! *)
| PrintInt of expr (* expr should be int *)
(* Control Flow *)
| IfThen of cond * stmt
| IfThenElse of cond * stmt * stmt
| Switch of expr * (int * stmt list) list * stmt list
(* Switch (cond, cases, default) *)
| While of cond * stmt
| For of stmt * cond * stmt * stmt
| Break (* used in switch, while and for *)
| Continue (* used in while and for *)
(* nested statements *)
| List of stmt list
;;
您可以将
stmt
定义为变体类型,即有限的备选方案集合。备选方案之一是List
,它确实包含stmtlist
。但这并不意味着stmt列表
与stmt
的类型相同。这意味着一个值列表…
(里面有一个语句列表)的类型是stmt
,您可能希望代码的格式稍微好一点;现在很难读。只需将其缩进4个空格就足够了。