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 integerNdirectly. - Recursive cases: For
add(X Y)andmul(X Y), we recursively evaluate the sub-expressionsXandY, 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
casestatement checks the structure ofExp:- When matching
int(N), we immediately returnN—this stops the recursion and gives us a concrete value. - For
add(X Y), we first evaluateXandYby calling{Eval X}and{Eval Y}, then add the two results together. - For
mul(X Y), we do the same recursive evaluation ofXandY, then multiply their results.
- When matching
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
相关产品推荐
相关产品推荐

