Title: Prefix, Infix and Postfix Notation
1Prefix, Infix and Postfix Notation
We must organize computations in such a way that
our limited powers are sufficient to guarantee
that the computation will establish the desired
effect
- Dijkstra
2Basic Expressions
- Basic expressions
- Operator , , AND, NOT
- Operands 1,2,3 etc. or, subexpressions
- 3 4 5
- Operations can be written in infix, postfix, or
prefix order - Associativity is specified in prefix and postfix
form
3Operators and Functions
- Some languages distinguish between operators
(built-in) and functions (user defined) - Typically, built-ins are specified as infix,
functions as prefix - 34 5 add(3, mul(4,5))
- Operators and functions are essentially
equivalent concepts - Why differentiate?
4Operator Overload
- Some languages allow the user to overload
built-in operators - Some require prefix or postfix expressions
- Postscript and FORTH use postfix
- LISP and Scheme use prefix (and fully
parenthesized) - Each language has rules for evaluating
expressions - Recall that compilers build parse trees, so, the
order of expression evaluation matters in order
to get the desired result
5Expression Evaluation
- Applicative order evaluation
- All operands are evaluated first then operators
are applied to them - Also called strict evaluation
- (314) 3 (82-6) 14
- 3 Mul(1add(3,4), 2sub(8,6))
- In what order are the subexpressions computed?
- Natural order is left to right
- Many languages leave this undefined
6Infix Precedence
- Issue Is the value of the expression
- 2 3 4
- (2 3) 4 20
- Or,
- 2 (3 4) 14?
- Operator precedence governs evaluation order.
- has higher precedence than , so it is applied
first, making the answer 14.
7Operator Precedence
- ( )
HIGH - (unary) , - (unary) , ! (NOT)
- , /,
- (addition), - (subtraction)
- lt, lt, gt, gt
- , !
-
-
LOW
8Associativity
- Does the expression 8 - 4 - 2
- evaluate (8 - 4) - 2 2,
- or 8 - (4 - 2) 6?
- Precedence doesnt help as it is the same
operator appearing multiple times in an
expression - Use Associativity. Since - is left-associative,
the left - is evaluated first, giving us 2. - Can you think of a right-associative expression,
meaning, right hand side is evaluated first?
- Assignment Operation
9Order of Evaluation
- Different machines may have different
requirements for function calls - Might want to make the code more efficient
- (34)(34)
- Evaluation order only matters in the presence of
side effects - If the order is unspecified, any program that
relies on a particular order could give incorrect
final result
10Expressions
- C is an expression oriented language, written in
Infix form - x (f - z) (5/9)
- Y X
- z a
- Some expressions can be evaluated without
evaluating all subexpressions - Short-circuit boolean evaluation
11Short Circuit Evaluation
- Programming languages specify evaluation of
boolean expressions - Left to right until truth value is known
- Order of evaluation is important!
- Many different ways of writing boolean operators
12Short Circuit Boolean Evaluation
exp1 exp2 . . . expn Evaluate left to
right, stop and return true when first exp is
true short circuit evaluation. if all are
false, return false. exp1 exp2 . . .
expn Evaluate left to right, stop and return
false when first exp is false short circuit
evaluation. if all are true, return true.
.
13Short Circuit Evaluation of Boolean Expressions
- Example in Java
- if ( !(obj NULL) (obj.num 0))
- obj.num obj.num 1
-
- is a binary expression, so can we just do
- Let t1 be (obj NULL)
- t2 be !t1
- t3 be (obj.num 0)
- t4 be (t2 t3)
-
- Simple isnt it? Wrong!!
- - If obj is NULL, then evaluating obj.num will
lead to Segmentation Fault.
14Expression Notations
- Arity of an operator
- unary one operand, binary two operands, etc.
- Notation infix, prefix, postfix
- constant or variable is the constant or variable
itself - the application of op to E1 and E2 op E1 E2
- more general, opk E1 EK
15Infix and Prefix Notation
- Infix notation Operator appears between
operands - 2 3 ? 5
- 3 6 ? 9
- Implied precedence 2 3 4 ? 2 (3 4 ),
- not (2 3 ) 4 See slide 7 for Order
of precedence - Prefix notation Operator precedes operands
- 2 3 ? 5
- 3 5 2 ? ( ( 3 5 ) 2) ? 2 15 ? 17
- Exercise (prefix)
- 20 30 60 ( ( 20 30) 60)
- ( 50 60)
- 3000
16Postfix Notation
- Postfix notation Operator follows operands
- 2 3 ? 5
- 5 2 3 ? (5 ( 2 3 ) ) ? 5 6 ? 11
- Called Polish postfix since few could pronounce
Polish mathematician Lukasiewicz, who invented
it. - An interesting, but unimportant mathematical
curiosity when presented in 1920s. Only became
important in 1950s when Burroughs rediscovered it
for their ALGOL compiler. - Prefix Notation is referred to as Reverse Polish
Notation
17Summary Associativity and Precedence
- Infix notation operators appear between operands
a b c - sum of a and b c? ? a (bc)
- product of a b and c ? ? (a b) c
- Precedence of operators
- and / have higher precedence than and -
- except Smalltalk
- Associativity
- usually from left to right 4 - 2 - 1 ?
- are you sure it is not 3?
- operator is left associative if subexpressions
containing multiple occurrences of the operator
are grouped left to right - Parentheses
18Summary Prefix Notation
- ltExpressiongt (ltoperatorgt ltoperandsgt)
- Example
- 3 5 ( ltgt lt3 5gt)
- 15
- 3 5 5 (lt lt 3 5gt 5gt)
- 20
- 3. / 2 3 5 6 (lt/ lt 2 3 5gt 6gt)
- (lt/ lt lt 2 3gt 5gt 6gt)
- (lt/ lt 6 5gt 6gt
- (lt/ 30 6gt)
- 5
19Prefix Notation and Scheme
Scheme uses prefix notation, where the operation
(or function) call occurs first, followed by the
data or arguments.
( ltoperationgt ltdatagt )
Examples ( 2 2) ( 3 1) (/ 10 0) ( 7 (
4 5))
Which of these would cause problems if entered
into a simple calculator?
20Exercises Prefix Notation
- Write the following expression in prefix
notation - 1) subtract 3 from 5
- 2) subtract 10 from the quantity 5 minus 8
- 3) divide 3 into 42
- 4) sum the squares of both 3 and 4
- Evaluate the following prefix expressions
- (/ ( 2 4) (/ ( 6 4) ( 12 4)))
- / 2 6 14 2
21Documentation for self-paced learning using
Dr.Scheme
http//www.htdp.org
22You will use the DrScheme program as your editor
and development environment. It is what is known
as an IDE integrated development environment.
23Definitions Window
Interactions Window
24Execute button loads the Definitions into
the Interactions window
25Saving your work
26Important
Be sure to set the language level in Dr. Scheme
to Beginning Scheme
27Recall Scheme is Functional Interpreted
- Scheme can execute a single line of code as soon
as it is typed into the interactions window - ( 2 2)
- 4
28Simple Evaluation
Lets start with something simple. Suppose we
wanted to solve the following expression 3
4 5 This looks easy, but what might go
wrong?
29Simple Evaluation
It might be that by mistake someone could read
this as 7 5 by adding before multiplying. A
clear mistake. 3 4 5 How can we be
sure we dont make this mistake? ? paranthesize
30Simple Evaluation
We can add unnecessary but helpful parentheses
around part of the expression. 3 (4
5) We all know that parenthetical expressions
are evaluated first So this will make it
totally clear.
31Simple Evaluation
We can go further, and add parentheses around the
entire expression. (3 (4 5)) This
doesnt change the meaning of our original short
notation. It makes things explicit.
32Recall the notations for writing arithmetic
expressions ?
As we saw earlier, the choice of representing
operators (, ) between the operands (numbers)
is completely arbitrary. (1 2)
Convention could be to write this as (
1 2) or even 1 2
Assuming binary operands, because of the way
postfix notation works, theres no need for a
set of parentheses
33Using DrScheme
In class activity Boot up your machines and
find Dr.Scheme and launch the application now.
34Learning Index
Desired level of learning in CS160
Actions You Will Take This Evening
Try numerous examples in DrScheme AND the
Stepper Run DrScheme, but not the
Stepper Merely read notes/slides/online
docs Blow it off until somethings due
A
B
C
D/F
35Using the Stepper
DrScheme includes a remarkable stepping tool that
lets yu see the order of evaluation. Lets
evaluate a complex expression with this tool we
did by hand earlier (/ ( 2 4) (/ ( 6 4) (
12 4))) (In class activity all students try
this on your terminal)
36Scheme Numbers
Elements
Integers, e.g. 4, -6, 0 Real Numbers, e.g.,
3.14159 Ratios, e.g., 1/2, 4/3 Symbols, e.g.,
x, y, foo, bar -- often used for the name of a
parameter, or a function name, or a variable
37Scheme
Predefined symbols. As it turns out, there are
about 100 predefined symbols in scheme, including
the arithmetic operators
addition - subtraction
multiplication / division
38Using a pre-defined function in Scheme
- Let us use the sqrt function pre-defined in
Scheme, which computes the square root of a given
number. - We are used to function call as sqrt(4)
- In Scheme, it is written as (sqrt 4)
- Try sqrt and other pre-defined functions in
Scheme after viewing the next slide.
39What is i
When we next type in (sqrt (sqrt 4)) we
see i1.4142135623730951 That looks like the
right value, but whats with the i in front?
This is schemes way of indicating an
approximation.
40Mathematical operations
- Numerous built-in functions for common
operations - (sqrt A) ? ?A
- (expt A B) ? AB
- (remainder A B) ? remainder of integer division
A/B (remember modulus operator?) - e.g. (remainder 23 8) ? 7
- (log A) ? natural log of A
- (sin A) ? sine of A radians
41In-class Exercise 30 minutes
- Try several numerical expression evaluations as
well as pre-defined functions evaluation in
DrScheme now. - Visit
- http//download.plt-scheme.org/doc/drscheme/
- Use the handout as your reference for checking
your progress. - Visit
- http//www.htdp.org/2002-09-22/Companion/drscheme-
Z-H-6.html - When satisfied with using arithmetic expressions
evaluation proceed to learn about functions
online at - http//www.htdp.org/2002-09-22/Companion/drscheme-
Z-H-7.html_chap_4 - Or, wait till we discuss it in class.
42Writing our Own Mathematical Functions
Lets start with a simple function from
mathematics f(x) x x This function
squares a number, thus f(2) 2 2
4 f(5) 5 5 25
43Functions
Recall that a function maps a set of values,
called the domain, onto a set of return
values, called the range, so that one of the
domain values is paired with one and only one of
the range values.
1
2
3
44f(X)
f(X) XX
range
X
domain
45Functional Vocabulary
Consider again
f(x) x x
46Functional Vocabulary
f(x) x x f(2)
The function body is applied to the value 2
47Observations
f(x) x x f(2) 4
Predictable, reproducible. Each time we apply
the function to the value 2, we get the same
result. Nothing changed about the parameter.
Each time we call f(2), we do not change the
value of 2. The function doesnt alter anything
in the world.
48So let's write a Scheme function!
Remember square f(x) x x We start by naming
the function (define (sq x) and continue by
adding the body (define (sq x) ( x x)) And
we test (sq 3) 9
49Remember Pythagoras?
50Pythagoras
c
b
a
c2 a2 b2 c sqrt(a2 b2)
51Pythagoras...
(sqrt ( ( 3 3) ( 4 4))) 5
c
3
4
52Note on Prefix Notation in Scheme
We use prefix notation, instead of infix ( 3
3) rather than ( 3 3) because scheme
expects the name of the function first (after the
opening paren). "" is a actually the name of a
function that multiplies numbers together
53Many Calculations of Hypotenuse
(sqrt ( ( 3 3) ( 4 4)))
(sqrt ( ( 2 2) ( 8 8)))
c
2
8
If we had many triangles to work with, typing the
same expression over and over gets tedious.
54Assignment ? Binding values
In mathematics, wed recognize the function at
play hypotenuse(a, b) sqrt ( aa bb
) Remember what that "" sign meant? It binds
the body to the function/parameter list. In
Scheme, we can do this binding by defining a
function. It begins with ( define
55Binding the name and the expression
At this point, the Scheme interpreter would
expect you to name the function you hope to
define. We need to come up with a symbol
name. The symbol/name hypotenuse is
good (define (hypotenuse side1 side2)
Here side1 and side2 are "parameters" or
"arguments basically placeholders for the side
lengths. In our pseudocode (infix) notation, this
is equivalent to Procedure hypotenuse
(side1, side 2)
56Still More
- At this point, we have
- a symbol for the name of the function, and
- the names of the parameters to the function.
(define (hypotenuse side1 side2)
The body of the function is easy
(define (hypotenuse side1 side2) (sqrt ( (
side1 side1) ( side2 side2))))
57Scheme and Pseudocode
- (define (hypotenuse side1 side2)
- (sqrt ( ( side1 side1) ( side2 side2))))
Pseudocode for the same, assuming sqrt(x) is
pre-defined procedure hypotenuse (side1, side2)
print sqrt((side1side1)
(side2side2))
58Style matters!(not to the scheme interpreter,
but)
Even though the interpreter doesnt care, as good
programming practice, we will always seek good
style! As a matter of style, we will use indents
and returns to better format the statement
(define (hypotenuse side1 side2)
(sqrt ( (
side1 side1) (
side2 side2)))) As opposed to (define
(hypotenuse side1 side2) (sqrt ( ( side1
side1) ( side2 side2))))
59Abstraction and Re-use of functions
Note we square side1 and then square side2, then
add the result and find the sqrt of the
result. We defined a square function sq earlier.
We should use it. Its better abstraction.
(define (hypotenuse side1 side2) (sqrt (
( side1 side1)
( side2 side2))))
(define (hypotenuse side1 side2) (sqrt (
(sq side1)
(sq side2))))
60In-class Exercise Functions
- Write a Scheme function for converting from
Fahrenheit to Celsius as done for Quiz 5 using
the formula - C (5/9) (F-32)
- Write a Scheme function for computing the volume
of a box as done for Quiz 5 - Write a Scheme function which when given the area
of a square, calculates the perimeter of the
square. -
61Self-paced Learning
- Bookmark the following documentation pages and
work through them on your own. - http//download.plt-scheme.org/doc/drscheme/
- TOC for self-paced learning
- http//www.htdp.org/2002-09-22/Companion/
- drscheme-Z-H-1.html_toc_start