Unformatted text preview: 45+5/7 as data?
How do we find 45 + 5 / and 7 in an input string?
How do we make sure that 45+5/7 means 45+(5/7) rather than (45+5)/7?
Should we allow floating-point numbers (sure!)
Can we have variables? v=7; m=9; v*m (later)
Stroustrup/Programming 8 A simple calculator
simple Wait! We are just about to reinvent the wheel!
Read Chapter 6 for more examples of dead-end approaches What would the experts do? Computers have been evaluating expressions for 50+ years
There has to be a solution!
What did the experts do?
What did Reading is good for you
Asking more experienced friends/colleagues can be far more
effective, pleasant, and time-effective than slogging along on your
Stroustrup/Programming 9 Expression Grammar
Expression This is what the experts usually do – write a grammar:
grammar Expression :
Expression ‘+’ Term
Expression ‘-’ Term
Term ‘*’ Primary
Term ‘/’ Primary
Term ‘%’ Primary e.g., 1+2, (1-2)+3, 2*3+1
e.g. 1+2 e.g., 1*2, (1-2)*3.5
e.g. 1*2 (1-2)*3.5 Primary :
‘(‘ Expression ‘)’ e.g., 1, 3.5
(1+2*3) Number :
floating-point literal e.g., 3.14, 0.274e1, or 42 – as defined for C++
3.14 0.274e1 or
as A program is built out of Tokens (e.g., numbers and operators).
Stroustrup/Programming 10 A side trip: Grammars
side What’s a grammar?
What’s grammar A set of (syntax) rules for expressions.
The rules say how to analyze (“parse”) an expression.
Some seem hard-wired into our brains
Example, you know what this means: You know that this is wrong: 2*3+4/2
birds fly but fish swim
2 * + 3 4/2
fly birds fish but swim Why is it right/wrong?
How do we know?
How can we teach what we know to a computer?
Stroustrup/Programming 11 Grammars – “English”
Grammars Stroustrup/Programming 12 Grammars - expression
Grammars Stroustrup/Programming 13 Grammars - expression
Grammars Stroustrup/Programming 14 Grammars - expression
Grammars Stroustrup/Programming 15 Functions for parsing
We need functions to match the grammar rules
get() // read characters and compose tokens
// calls cin for input
cin expression() // deal with + and –
// calls term() and get()
term () // deal with *, /, and %
// calls primary() and get()
and primary() // deal with numbers and parentheses
// calls expression() and get()
and Note: each function deals with a specific part of an expression and leaves
everything else to other functions – this radically simplifies each function.
Analogy: a group of people can deal with a complex problem...
View Full Document
- Fall '09
- Walter Daugherity
- Val, Parsing expression grammar, Bjarne Stroustrup