I am writing a small compiler in Ocaml. In ast.mli
, i have defined 2 kinds of expressions
type int_expr =
| Integer_constant of int
| Evar of string
| Ebinop of binop * int_expr * int_expr
| Ecell of int_expr * int_expr (* Sheet[ , ] *)
type bool_expr =
| Bool_constant of bool
| Bcmp of cmp * int_expr * int_expr
| Band of bool_expr * bool_expr
| Bor of bool_expr * bool_expr
| Bnot of bool_expr
In interp.ml
, i want to define a function called eval_expression
to evaluate any expression which could either be int_expr or bool_expr
let rec eval_expression env = function
| Integer_constant n -> Integer n
| Ebinop (op开发者_如何学Python, n, m) -> ...
| Evar x -> ...
| Ecell (r, c) -> ...
| Bool_constant b -> ...
| Bnot c -> ...
| Bor (c1, c2) -> ...
| Band (c1, c2) -> ...
But it returns an error while compiling:
ocamlc -c interp.ml
File "interp.ml", line 63, characters 4-19:
Error: This pattern matches values of type Ast.bool_expr
but a pattern was expected which matches values of type Ast.int_expr
make: *** [interp.cmo] Error 2
Could anyone tell me how I could change the structure of my expression types so that eval_expression
works? Thank you very much!
You will need to write another type for arbitrary-typed expressions:
type expr = Iexpr of int_expr
| Bexpr of bool_expr
and a type for final values which could be either integer or boolean
type value = Ivalue of int
| Bvalue of bool
and write a function evaluate : expr -> value
.
For what it's worth, I've never felt that statically separating the allowable expressions in this manner into int-typed and bool-typed expressions was ever really worth it in an ML-like language. You end up with a lot of duplicated syntax once you add richer types to your object language. What you really want is to kick the object language types into the type strata of your implementation language, but that ends up being pretty ugly in ML. It's slightly nicer in Haskell's richer type and kind machinery, but it still feels like a very affected programming style.
In the end, for little throwaway interpreters I usually just code up separate tp
and expr
types for the type and expressions of my object language and write the eval as expr -> tp -> value
精彩评论