1.2 Evaluation Procedure¶
This note expresses how to evaluate more complicated expressions, such as nested expressions.
Get back to toc CS61A
Expression Evaluation¶
You can import modules in python with the import command.
import add
>>> add(2, 3)
5
You can also nest calls inside of another.
from operator import add, mul
>>> add(1, 1)
2
>>> mul(2, add(1, 1))
4
You don't have to understand the from operator... line, but just know that is how we can use add and mul as functions.
Now, we can get very complicated and ask Python do do something like add(3, 4, mul(3, add(2, 4, mul(4, mul(8, 2)))), 9).
How might we evaluate this expression? It might be easy for us to see what to do, but how would a computer look at something like this? Remember, must have a system to determine more complicated expressions like this. In fact there is one. You should get familiar with the following procedure for evaluating procedures
- Evaluate the Operator: By this, I mean making sure the operator exists and is defined.
- Evaluate the Operands: The arguments in the function must fully be evaluated first. If the argument is another operation, you have to finish this procedure fully on that subexpression before you continue on.
- Apply the Operator to the Operands: This is defined by whatever function. For
addandmul, applying the operator to the operands just means doing the arithmetic operation. For other functions that we will create, it might involve more computation.
As a quick example, let's go through this procedure with the expression
add(mul(2, 3), add(1, 2))
- Evaluate the operator: add is a function.
-
Evaluate the operands: Ok, I see that the first subexpression evaluates to something I have to apply the procedure to first,
- Evaluate the operator: mul is a function
- Evaluate the operands: 2 is 2 and 3 is 3.
- Apply the operator to the operands: mul(2, 3) is 6.
That was just the first operand, we evaluate the second operand through the procedure again 1. Evaluate the operator: add is a function 2. Evaluate the operands: 1 is 1 and 2 is 2 3. Apply the operator to the operands: add(1, 2) is 3
The second operand is fully evaluated, now we go on to the third step 3. Apply add(6, 3): this is 9, so the result of this whole expression is 9.
I think you can see how this procedure goes with more complicated expressions, but this is a very important idea of execution.
Summary¶
One thing to take away is the evaluate of call expressions. You'll see this idea alot, such as in [[5. Environment Diagrams]], where we explore the idea in detail, and then in [[14. Interpreters]], where you will actually program this procedure.
Go to next chapter: 2. Expressions, Variables, and Functions
Get back to toc CS61A