Part 2. Racket Evaluation
In this part, we are going to evaluate racket code. Racket has a specific order, like PEMDAS in basic arithmetic, on how we evaluate code.
take a look at this example
(+ 2 (* 3 4) (- (+ 1 2) 3))
run this expression in dr. racket and we have 14. But how does racket evaluate?
run this expression in dr. racket and we have 14. But how does racket evaluate?
- Look at the outer parenthesis, it first look at the primitive
(+ 2 (* 3 4) (- (+ 1 2) 3))
The primitive here is the plus sign. It is called as an operator so it will see that it is an addition operator, what which values we will add to?
2. Look at the operands
(+ 2 (* 3 4) (- (+ 1 2) 3))
The colors blue, violet and orange are the operands
To evaluate a primitive call has 2 rules
1. all operands have to be reduced to values
2. apply primitive to values
So it has some recursion to it.
Now we look at each operand
the 2 operand is already a value, we need not touch it,
look at the second operand (* 3 4)This Needs to be reduced to a value.
The 2 operands are already values in that primitive call so we need not reduce them, 3 * 4 is 12, so the new racket code is.
(+ 2 12 (- (+ 1 2) 3))
now look at the third operand
(- (+ 1 2) 3)
we also need to reduce that, we have a subtraction primitive, the first operand of the primitive needs to be reduced, 1 + 2 = 3 so the reduced operand looks like this.
(- 3 3)
Now we evaluate this, 3 - 3= 0, now that we have evaluated the third operand. This is the final expression
(+ 2 12 0)
Now we can just add them as normal. 2 + 12 + 0 = 14, which is the answer.
So racket recursively evaluates when it finds a parenthesis which consists of a primitive call. until it finds no parenthesis, then it does what the primitive is tasked to do. And this is how racket evaluates code, just like the PEMDAS rule.
Mga Komento
Mag-post ng isang Komento