简体   繁体   中英

Ocaml Abstract Sytnax Tree

I have working expression however when I try to evaluate my expressions with my current evaluate function I get following error-- "Error: This pattern matches values of type 'a * 'b but a pattern was expected which matches values of type args". Could you help me how to fix it.

type expr = Const of int 
          | Var of string
          | Plus of args
          | Mult of args
          | Minus of args
          | Div of args
              
and args = {arg1:expr; arg2:expr};; 

let rec eval = function
  | Const c -> c
  | Plus (f, g) -> eval f + eval g
  | Minus(f, g) -> eval f - eval g
  | Mult(f, g) -> eval f * eval g
  | Div(f, g) -> eval f / eval g 
;;

Constructors like Plus as you have declared it take arguments that are parenthesized. You appear to be using the syntax appropriate to a record type (with curly braces and field names). But there are no record types in your definition of expr .

Here is a valid value of type expr :

Plus (Const 3, Const 8)

Your eval function doesn't handle the evaluation of variables (the Var constructor). This is only a warning, not an error, but it will cause a runtime exception if you try to evaluate something like Var "abc" .

You don't say which of these errors you're talking about, but I hope this is helpful nonetheless.

Update

As @CraigFe at discuss.ocaml.org pointed out, you have a mismatch between the definition of expr and the test case. You could rewrite your definition of expr so that the test case works, or you could rewrite the test case so it works with your current definition of expr .

To match the test case, you would want a definition like this:

type expr2 =
    | Const of int
    | Plus of { arg1 : expr2; arg2: expr2 }

Then you can have a value like this:

Plus { arg1 = Const 3; arg2 = Const 8 }

However, you can't have field names starting with a capital letter in OCaml. This means that Arg1 and Arg2 need to be arg1 and arg2 . So personally I would suspect that the test case is the part that needs revision.

I don't understand the part about the mutually recursive definitions (though I know what those are of course). Generally speaking I'd say your biggest difficulty is with the problem statement, not your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM