CS112_39_slides-more-expr

CS112_39_slides-more-expr - CS112 Fundamentals of...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS112 Fundamentals of Programming Abstractions Expression trees-cont. Yinglin Wang CS Dept., SJTU CS112 Fundamentals of Programming Abstractions Union types C allows us to do this. We use a union rather than a struct. When a union is created, it is as if all the fields start at offset zero, and thus overlap. How does the compiler keep track of what is actually in there? It doesn't. That is up to the programmer! value.intRep is an integer value.idRep is a string value.compoundRep is a struct The syntax for accessing the fields of a union is the same as for a struct. CS112 Fundamentals of Programming Abstractions Type tag So that we can tell what type of nodes we are dealing with, we will place the union inside a struct that contains a field that serves as a "type tag". Which type of values is stored in ? You must keep track of the value of union type an any specific time CS112 Fundamentals of Programming Abstractions expressionADT Here are some examples showing how we would access the parts of an expressionADT in the implementation code. Before we write something like exp-> value.intRep, we had better be sure that we are dealing with an integer node. We could determine that by testing the tag. Here are some examples showing how CS112 Fundamentals of Programming Abstractions Expression in memory Here is the way an expression might look in memory. There is a little unused space, but not nearly as much as there would have been without the union. In your assignment, you will be using the expressionADT extensively. CS112 Fundamentals of Programming Abstractions If we can write a parser that takes in an expression and produces an expressionADT that represents it, then it is relatively easy to write code that will calculate the value of the expression. This is just what we need for an interpreter. Only the CompoundType case has anyreal work to do. CS112 Fundamentals of Programming Abstractions Here is pseudocode for EvalCompound. It is mutually recursive with EvalExp. The complete code is in the text. CS112 Fundamentals of Programming Abstractions Parser Last time we saw how to use an expressionADT to represent an arithmetic expression as a tree....
View Full Document

Page1 / 15

CS112_39_slides-more-expr - CS112 Fundamentals of...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online