【问题标题】:Pattern matching with a record in Oz与 Oz 中的记录匹配的模式
【发布时间】:2018-07-15 15:13:15
【问题描述】:

我在思考如何利用 Oz 中的记录元素进行模式匹配时遇到了一些麻烦。下面是我的代码

declare
fun {Eval X E}
case X
of int(N) then N
   [] var(X) then E.X
   [] mul(X Y) then X*Y
   [] add(X Y) then X+Y
   end
   end
end

{Eval add(var(a) mul(int(3) var(b))) env(a:2 b:4)}

这是我必须使用的输入,var(a) 应该从输入中的 env 记录返回 2,(而 var(b) 返回 4),我只是想不通。

【问题讨论】:

  • mul(X Y) then X*Y 中,您忘记评估XY

标签: emacs pattern-matching records oz mozart


【解决方案1】:

在您的代码中,当您没有达到数字或 var 时,您需要递归调用 Eval。试试这个:

declare
fun {Eval Node Env}
   if {IsNumber Node} then Node
   else
      case Node
      of var(X) then Env.X
      [] mul(X Y) then {Eval X Env} * {Eval Y Env}
      [] add(X Y) then {Eval X Env} + {Eval Y Env}
      end
   end
end

另外,Oz 要求函数的返回值绑定到一个变量,所以试试这样的:

declare
Ans = {Eval add(var(a) mul(3 var(b))) env(a:2 b:4)}

然后您可以使用浏览器查看 Ans 以验证代码是否正确。

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2018-01-08
    • 2013-06-14
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多