You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OZ/Mozart算术表达式求值:实现Eval函数需求问询

Implementing an Eval Function for OZ Arithmetic Expressions

No problem at all—this is a classic use case for OZ's strong pattern matching capabilities, which makes handling tree-structured expressions straightforward. Let's break down how to build this Eval function step by step.

Core Approach

We'll use a recursive function that matches against the three possible expression types:

  • Base case: When we hit an int(N) tuple, we just return the integer N directly.
  • Recursive cases: For add(X Y) and mul(X Y), we recursively evaluate the sub-expressions X and Y, then apply the corresponding arithmetic operation to their results.

The Code

Here's the complete implementation:

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

How It Works

Let's walk through each part:

  • {Eval Exp} defines the function that takes your expression tuple as input.
  • The case statement checks the structure of Exp:
    • When matching int(N), we immediately return N—this stops the recursion and gives us a concrete value.
    • For add(X Y), we first evaluate X and Y by calling {Eval X} and {Eval Y}, then add the two results together.
    • For mul(X Y), we do the same recursive evaluation of X and Y, then multiply their results.

Testing the Example

Let's run your sample expression to verify:

{Browse {Eval add(int(1) mul(int(3) int(4)))} }

This will output 13, just as expected. The function first evaluates mul(int(3) int(4)) to get 12, then adds 1 to that result.

内容的提问来源于stack exchange,提问作者Alma A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:25:09