Building Abstractions with Procedures (Part 2)

Preview:

DESCRIPTION

Building Abstractions with Procedures (Part 2). CS 21a: Introduction to Computing I First Semester, 2013-2014. Last Time…. Giving names to and abstracting away chunks of code that look similar, so that code becomes cleaner. Today…. Exploring combinations of procedures - PowerPoint PPT Presentation

Citation preview

Building Abstractions with Procedures (Part

2)CS 21a: Introduction to

Computing IFirst Semester, 2013-2014

Last Time…►Giving names to and abstracting away

chunks of code that look similar, so that code becomes cleaner

Today…►Exploring combinations of procedures►More detailed discussion of

procedural programming

Outline►Combinations through Procedures►The Method Stack versus the Tree of

Stack Frames►Scope versus Environment

Procedures Can Use Procedures

►Writing a procedure is like writing a new smaller program embedded in a larger one.►The larger algorithm delegates part of

the problem, or a sub-problem to the procedure.

►And this can go on recursively.►Sub-problems can have further sub-

problems.►Procedures can use procedures.

Combination through Procedures

static int square(int x){

return x*x;}

static int sum_of_squares(int x, int y){

return square(x) + square(y);}

Procedure Definitions Can Have Procedure Calls

►A procedure definition can serve to expand the “primitives” that a higher-level programmer (possibly yourself) can use.

Procedure Definitions Can Have Procedure Calls

►The square procedure is a blackboxed “primitive” that the sum_of_squares programmer may use…► without thinking about how square works…

► In the same manner that the square programmer uses the * operator…► without thinking about how * works,

►And the sum_of_squares procedure can be used in another procedure defintion…► without thinking about how sum_of_squares works.

Remember This?►Civilization advances by extending

the number of operations that we can perform without thinking about them.►Alfred North Whitehead (1861-1947)

Practice Programming Problem: Square Hypotenuse

►Include the procedure definitions above into your program and print out the square of the hypotenuse of a given triangle. Don’t forget to test your program.

►Assume the following declarations:int a = 5;int b = 3;

Outline►Combinations through Procedures►The Method Stack versus the Tree

of Stack Frames►Scope versus Environment

Practice►Try to imagine how the method stack

evolves in an execution of a program that calls sum_of_squares.

Practice

main

Practice

main

sum_of_squares

Practice

main

sum_of_squares

square

Practice

main

sum_of_squares

Practice

main

sum_of_squares

square

Practice

main

sum_of_squares

Practice

main

Tree of Stack Frames►A computation has a method stack.►But an algorithm has a tree of stack

frames.► Like how expressions have expression trees►A computation lives out an algorithm by walking down this tree and backtrackingwhen it reaches a dead end.

main

sum_of_squares

square

square

Practice Programming Problem: Interest Once More

►If you haven’t done so already, rewrite the program you wrote for Bob so that the tree of stack frames of the algorithm is more than two levels deep.

Procedure Calls Can Be Nested

►Like expressionsprint(square(4));print(sum_of_square(2, 3) +

square(square(5)));print(square(square(3)));

Procedure Calls Can Be Nested

►But if you find yourself nesting too much, maybe you need intermediate variables.

int input = 3;

int hypercube = square(square(input));

int answer = sum_of_squares(hypercube, hypercube);

print(answer);

Or New Procedure Definitions

static int hypercube(int x) {return square(square(x));

}…public static void main(String args[]) {

int input = 3;int temp = hypercube(input);int answer = sum_of_squares(temp, temp);print(answer);

}

Practice►For each slide above, starting from 3

slides ago…►Draw the tree of stack frames of the

algorithm.►Draw the evolution of the method stack

of a computation, include environments.

►You may think of + as a procedure with two parameters, and include that too.

Outline►Combinations through Procedures►The Method Stack versus the Tree of

Stack Frames►Scope versus Environment

Parameter Names of Different Procedure Definitions Are in

Different Scopes►Note how the x of the square definition is not

the same as the x of the sum_of_squares definition.►Remember composition of functions in algebra?

►Each procedure definition has its own scope or namespace.

►The block structure is Java’s way of enforcing scope.► Each pair of curly braces creates a new scope.

Parameter Names of Different Procedure Definitions Are in

Different Scopesstatic int square(int x){

return x * x;}

static int sum_of_squares(int x, int y){

return square(x) + square(y);}

These refer to different abstract entities, to different variables.

block structure

Scope Versus EnvironmentScope► Procedure definitions

have scope.► The x in square is

different from the x in sum_of_squares.

► The x in the (written) call square(x) in sum_of_squares is different from the x in square.

Environment► (Running) procedure

calls have environment.► Each (running) call to square within sum_of_squares is independent of each other. The parameter x of square can possibly take on different values with each (running) call.

Scope Versus EnvironmentScope► Same scope: The

identifiers of the parameters of a procedure definition always refer to the same variables (parameters), even if they may have different values at different calls.

Environment► Different environments:

The set of arguments have different values different with each (running) procedure call.

► Each (written) procedure call in any given procedure definition will yield a new (running) procedure call with a new environment.

Scope Versus EnvironmentScope► Different scope: The

identifiers of the parameters of different procedure definitions refer to different variables, even if they look the same symbolically.

Environment► Different environments:

Obviously, (written) calls for different procedure definitions will produce different environments at run-time.

Two Kinds of Contexts►Scopes are contexts for names.

► Scopes exist in programs (the written algorithm).► Environments are contexts for variables.

► Environments exist in computations (the running program).

►Algorithms have neither scope nor environment.► Variables have no names until algorithms are

written.► Variables have no values until programs are run.

Recall!►The name/identifier is not the variable!►The name/identifier is a symbol.►The variable is the abstract entity which the

symbol refers to in a program.

►The value is not the variable!►The value is data.►The value is the concrete entity which the

variable takes on in a computation.

AGAIN►Different environment means different

values for the same variables.►Different scope means different

variables for the same identifiers.

An Analogy to Clear That Up►Imagine you are both a rock star and

a computer science student.

An Analogy to Clear That Up►One day, while rehearsing with your

band, you have the following conversation:►You: “Yo Alice, could you play me those

notes again.”►Alice: “What notes?”►You: “The opening to our new song.”►Alice plays the notes A, C, D, E because

she’s memorized it.

An Analogy to Clear That Up► You: “Try to play these notes instead: A, B, D#,

E.”►Alice executes the same procedure, play, but

this time with different environment, a different part of her memory, and returns a different tune.

► You: “Then play these notes I’ve written here.”► Pass by value: While Alice is actually playing,

she doesn’t have to care where the actual notes came from, she can always think of them only as “the notes.”

An Analogy to Clear That Up►After rehearsing, you realize you have a CS

exam and rush to your friend to borrow notes:► You: “Hey Bob, could you lend me your notes?”►Bob: “What notes?”► You: “I’m especially confused about scopes and

environments.”►Bob lends you his notes, but they’re probably

not something you’re going to sing with anytime soon.

An Analogy to Clear That Up►Alice asks Bob to lend her his notes

from music class (because Bob is awesome and also majors in music), so that she can play notes better.►There should be no confusion here.

An Analogy to Clear That Up►These are (written) procedure calls.►These are parameter identifiers.►These are identifiers for variables

which are not parameters.

An Analogy to Clear That Up►These represent abstraction barriers.►These represent parameters.►These represent variables which are

not parameters.

An Analogy to Clear That Up►The abstract entities referred to by these

become (running) procedure calls.►The abstract entities referred to by these

take on arguments, which may be directly supplied by these or indirectly supplied by these.

►The abstract entities referred to by these take on values, which may be directly supplied by these or indirectly supplied by these.

By the Way►For every block, there is also a scope

for procedures.►Does not coincide with the scope for

variables

Recitation►Given that you understand the

differences between (identifiers, programs, scope); (variables, algorithms); and (values, computations, environment), answer the following question and state the reasoning behind your answers.

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int y){

return foo(x);}

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int x){

return foo(x);}

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int a){

return foo(a);}

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int a){

return food(a);}

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int a){

return foo(a, b);}

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int a){

return foo(a, a);}

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int a){

return foo(10);}

Will This Work? If Yes, What Does bar(5) Return?

static int foo(int x){

return x*x;}

static int bar(int foo){

return foo(foo);}

Do These Two Define the Same Procedure?

static int square(int x){

return x*x;}

static int square(int y){

return y*y;}

How About These?static int cost(int quantity, int unit_price){

return quantity * unit_price;}

static int force(int mass, int acceleration){

return mass * acceleration;}

It’s Possible to Declare Local Variables in Procedure Definitions, But Will This Work?

static int foo(int x) {int y = 3;return x*y;

}

How About This?static int foo(int x) {

int y = 3;return x*x;

}

How About This?static int foo(int x) {

return x*y;int y = 3;

}

How About This?static int foo(int x) {

int d = y*x;int y = 3;return d;

}

How About This?static int foo(int x) {

int x = 1;return x*x;

}

How About This? If Yes, What Does bar(5) Return?

static int foo(int y) {int x = 1;return x*x;

}

static int bar(int x) {return foo(x);

}

How About This? If Yes, What Does bar(5) Return?

static int foo(int x) {return x*x;

}

static int bar(int a) {int x = 1;return foo(x);

}

How About This? If Yes, What Does bar(5) Return?

static int foo(int x) {return x*x;

}

static int bar(int a) {int x = 1;return foo(a);

}

How About This?static int foo(int x) {

int a = 1;int b = 2;return x*x;

}

How About This? If Yes, What Does bar(5) Return?

static int foo(int x) {int a = 1;return x*x;

}

static int bar(int x) {int a = 1;return x*x;

}

Why the Trouble With Scopes?

►Different people might be assigned to write different procedure definitions.► It’s inconvenient to have to know what

names someone else already used.►No running out of meaningful names for

new procedure definitions

Practice Programming Problem: Modern Art

►Assume you have a special kind of variable:

img original = ;

Practice Programming Problem:Modern Art

►Assume you have the following procedures:► static img scale(img a, double dx, double dy)

►Returns a version of a that has been scaled to dx times the width of a, and dy times the height of a. a remains unchanged.

► static img rotate(img x, int times)

►Returns a version of x that has been rotated 90 degrees clockwise times times. x remains unchanged.

► static img flip(img x)

►Returns a version of x that has been flipped with respect to the vertical axis. x remains unchanged.

Practice Programming Problem:Modern Art

►Assume you have the following procedures:► static img horizontal_join(img left, img right)

►Creates a new img of left put side by side with right. The width of the new image will be the sum of the widths of left and right. The height will be the greater of the heights of left and right. The input img with the smaller height will be vertically-centered on the resulting img. left and right remain unchanged.

Practice Programming Problem:Modern Art

►Assume you have the following procedures:► static img vertical_join(img top, img bottom)

►Creates a new img of top put on top of bottom. The height of the new image will be the sum of the heights of top and bottom. The width will be the greater of the widths of top and bottom. The input img with the smaller width will be horizontally-centered on the resulting img. top and bottom remain unchanged.

Practice Programming Problem:Modern Art

►Assume you have the following procedures:►static void print(img x)

►Displays x. x remains unchanged.

Practice Programming Problem:Modern Art

►Write a program that displays the following (with the same dimensions as the original):

Practice Programming Problem:Modern Art

►Don’t care that it doesn’t really run yet. It’s not your responsibility anymore to express the data types and algorithms used above in terms of simpler primitives.

►Now that you can’t test your program, try to convince yourself that your program is correct with a proof, rather than with test cases.►Doesn’t need to be too formal at this point

Practice Programming Problem:Modern Art

►Hints:► You may work in small groups of 2-3 members.►Notice how two of the three figures in the

output must be flipped with respect to the horizontal axis, while you only have procedures to rotate and flip with respect to the vertical axis.

► Passing the original image to a procedure call doesn’t change the original image.

► In what order should you perform the joins?

Summary►Procedures can be use procedures.►Procedure definitions can have

procedure calls.►Procedure calls can be nested,

recursively.

Summary►Names refer to the same variables,

but with possibly different values, in different environments.

►Names refer to different variables in different scopes.

SummaryThought Word ActionAlgorithm Program ComputationVariable Identifier ValueProcedure Procedure Definition (Running) Procedure

CallParameter Identifier ArgumentTree of Stack Frames Block Structure Method Stack

Scope Environment

Next Time…Thought Word ActionObject Class Instance

Recommended