简体   繁体   English

Ocaml 抽象语法树

[英]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".我有工作表达式,但是当我尝试使用当前的评估函数评估我的表达式时,我收到以下错误 - “错误:此模式匹配类型为 'a * 'b 的值,但预期模式匹配类型为 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.正如您所声明的那样,像Plus这样的构造函数接受带括号的参数。 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 .但是您的expr定义中没有记录类型。

Here is a valid value of type expr :这是expr类型的有效值:

Plus (Const 3, Const 8)

Your eval function doesn't handle the evaluation of variables (the Var constructor).您的eval函数不处理变量的计算( Var构造函数)。 This is only a warning, not an error, but it will cause a runtime exception if you try to evaluate something like Var "abc" .这只是一个警告,而不是错误,但如果您尝试评估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.正如 Discussion.ocaml.org 上的 @CraigFe 指出的那样,您在expr的定义和测试用例之间存在不匹配。 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 .您可以重写expr的定义,以便测试用例工作,或者您可以重写测试用例,使其适用于您当前的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.但是,在 OCaml 中不能有以大写字母开头的字段名称。 This means that Arg1 and Arg2 need to be arg1 and arg2 .这意味着Arg1Arg2需要是arg1arg2 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.一般来说,我会说你最大的困难在于问题陈述,而不是你的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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