Top Banner
3/31/2016 FWP lecture 4 http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 1/35 Fundamentals of Web Programming Lecture 4: functions and abstraction Devin Balkcom [email protected] office: Sudikoff 206 http://www.cs.dartmouth.edu/~fwp
35

Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

Jun 04, 2018

Download

Documents

dinhnhan
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 1/35

Fundamentals of Web ProgrammingLecture 4: functions and abstraction

Devin Balkcom [email protected] 

office: Sudikoff 206

http://www.cs.dartmouth.edu/~fwp

Page 2: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 2/35

Review: storing dataVariables can store values for later use or to change code behavior.

Declare a variable with var keyword.  Assign (copy) a value into a variable with =.

var x = 1;var y = 2;var z = x + y;print( z );

x = 2;print( z );

1234567

Page 3: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 3/35

Review: data typesEach value has a type: boolean, number, string, array, object, function.

// simple typesvar beauty = true;var pi = 3.141592645;var greeting = "hello";

// array typevar days = ["Mon", "Tue", "Wed"];

// dictionary or object typevar colors = {red: 650, green: 510, blue: 475};

// function typevar draw_smiley = function() { circle(100, 100, 80);};

123456789

101112131415

Page 4: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 4/35

Review: arraysAn array stores a list of values, indexed by number.

Create an array with brackets and commas. Access an element using brackets and an index.

var numbers = [1, 1, 2, 3, 5, 7];numbers[5] = numbers[3] + numbers[4];print( numbers );

123

Page 5: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 5/35

Review: dictionariesA dictionary stores a set of values, indexed by name (the key).

Often, all of the value types are the same. Think of a dictionary as a

mapping from strings to values. Use brackets to index by string.

var colors = {red: 650, green: 510, blue: 475};print( colors["red"] );colors["yellow"] = 580;

123

Page 6: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 6/35

Review: objectsAn object also stores a set of values indexed by name.

Think of an object like a record in a database. Value types may bedifferent. Index using dot notation. Values can be functions (methods).

var theDonald = {};

theDonald.party = "Republican";theDonald.hairColor = "orange";theDonald.age = 69;

12345

Page 7: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 7/35

Review: expressions and operatorsOperators act on values, providing new values.

var w = 3; // assignment operatorvar h = 4;

var triangleArea = 3 * 4; // arithemetic operatorvar result = h < w; // conditional operatorvar posEven = (h % 2 === 0) && (h > 0); // boolean operator

var colors = {red: 650, green: 510, blue: 475};print( colors.red ); // dot operator

123456789

Page 8: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 8/35

Review: loopsAllow control of the program counter.Condition is tested to decide whether to iterate again.Condition must change from true to false to avoid infinite loop.Loops can be nested.Design either outer or inner loop first.Usually use a for loop for counting.

Page 9: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 9/35

ObjectsFrames

Global frame

countdown undefined

JavaScript

1 var countdown = 5;2 while (countdown > 0) {3   console.log(countdown);4   countdown -= 1;5 }

< Back   Step 1 of 17   Forward >

 line that has just executed next line to execute

Visualized using Online Python Tutor by Philip Guo

Page 10: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 10/35

Review: defining your own functionsFunctions allow packaging of small pieces of code. Abstraction!Program counter: execute the function and then return.

Page 11: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 11/35

ObjectsFrames

Global frame

sayHello undefined

JavaScript

< Back   Step 1 of 5   Forward >

 line that has just executed next line to execute

Visualized using Online Python Tutor by Philip Guo

1 var sayHello = function() {

2   console.log("Hello!");

3   console.log("My name is Inigo Montoya.");

4 };

5

6 sayHello();

Page 12: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 12/35

Functions can take parameters

The order of parameters matters.

ellipse(150, 80, 220, 90);1

Page 13: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 13/35

Defining functions that take parameters

Function header declares variables. (But no var keyword.)On function call, values are copied into variables.

// Draw a square with upper left x, y and side length svar square = function(x, y, s) { line(x, y, x + s, y); line(x + s, y, x + s, y + s); line(x + s, y + s, x, y + s); line(x, y + s, x, y);};

square(10, 20, 80);

123456789

Page 14: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 14/35

Exercise: treeGo do exercise: tree in the lecture notes (lecture 4).

var drawTree = function(x, y) { noStroke(); fill(100, 50, 0); // brown rect(-5 + x, -50 + y, 10, 50);

stroke(0, 140, 0); fill(0, 195, 0); // green ellipse(0 + x, -50 + y, 40, 40);};

drawTree(100, 400);drawTree(130, 400);drawTree(300, 400);

123456789

10111213

Page 15: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 15/35

Each function call returns a value

The function executes, then makes its value available. A function callis an expression that is computed by running the function.

var y = Math.sqrt(25); // store the return value from sqrt in xprint(y);

print( Math.sqrt(4) ); // use sqrt return value as actual parameter

// use sqrt return value to test value of i in a for loop:print("Integer factors of 100: ");for( var i = 1; i < Math.sqrt(100); i++ ) { if (100 % i === 0 ) { print(" " + i + " " + 100 / i); }}

123456789

101112

Page 16: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 16/35

(Pseudo­)random number generatorssqrt is not the only function in the Math object.

User input, different data, and RNG: the same program might notalways follow the same execution path. Which pathways are tested?

var r = Math.random() * 255;var g = Math.random() * 255;var b = Math.random() * 255;

// coordinates of the center of the face:var x = 100; var y = 100;

// draw the outline of the facefill(r, g, b); // set fill color to yellowellipse(x, y, 100, 100);

123456789

1011

Page 17: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 17/35

Exercise: forestGo do exercise: forest in the lecture notes (lecture 4).

var drawTree = function(x, y) { noStroke(); fill(100, 50, 0); // brown rect(-5 + x, -50 + y, 10, 50);

stroke(240, 50, 0); fill(230, 105, 0); // orange ellipse(0 + x, -50 + y, 40, 40);};

// draw the grassnoStroke();fill(0, 200, 0);rect(0, 300, 400, 100);

123456789

101112131415

Page 18: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 18/35

Defining functions with return values

Executing a return­statement does two things:

1. returns the value following return (if any) to the calling code.2. immediately stops execution of the body of the function andresumes execution at the point of call.

var computeFour = function() { print("Your wish is my command! I compute four!"); return 24 / 4 - 2;};

print( computeFour() );

123456

Page 19: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 19/35

Page 20: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 20/35

Return halts execution of the function

The function returns and the program counter is set to its valuebefore the function call when the program counter gets to a returnstatement.

var getMeFour = function() { return 24 / 4 - 2; print("I computed the value!"); // this line is "dead code" and         never reached}; print( getMeFour() );

123

456

Page 21: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 21/35

Page 22: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 22/35

Exercise: primeGo do exercise: prime in the lecture notes (lecture 4).

var number = 39;var isPrime = true;for(var factor = 2; factor < Math.sqrt(number); factor++) { if(number % factor === 0) { print("not prime"); isPrime = false; }}if (isPrime) { print("prime");}

123456789

1011

Page 23: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 23/35

Exercise: primesGo do exercise: primes in the lecture notes (lecture 4).

var isPrime = function(number) { for(var factor = 2; factor < Math.sqrt(number); factor++) { if(number % factor === 0) { return false; } } return true;};

12345678

Page 24: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 24/35

Local variables and scope

Variables declared inside a function are local to that function andcannot be accessed outside that function.

var someFunction = function() { //create the variable x, and give x the value 4: var x = 4; print(x);};

someFunction();print(x); // not gonna happen. x is 'not in scope'

12345678

Page 25: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 25/35

Function framesWhen a function is called, the intepreter creates a frame for thatfunction, an area of memory where it stores its local variables.When a function returns, the frame is destroyed. The localvariables are destroyed irrevocably and are no longer in scope.

Global variables are declared outside any function, in the globalframe.

Page 26: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 26/35

Page 27: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 27/35

Thinking about functionsLocal variables are an example of the principle of least privilege.Modules should have access only to what they need to do a job.

When designing a function:

What values go in? (parameters)What temporary variables are used? (local variables)What is the single output of the function? (return)

Page 28: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 28/35

CallbacksSometimes you write a function for some other code to use.

We never called surprise in the code!

var surprise = function() { print("surprise!"); };

print("In 5 seconds, 'surprise!' will be printed.");

// tell Javascript to fun the `surprise` function after 5000 mssetTimeout(surprise, 5000);

12345678

Page 29: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 29/35

Exercise: alertFind a blank exercise window. Use the alert function and thesetTimout function to schedule an alert to be displayed at the end ofclass. (alert takes a parameter, so you might need to wrap it inanother function that does not for use with setTimout.)

1

Page 30: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 30/35

Callback chainsYou can use callbacks to execute complex behavior even after yourprogram stops.

For example, how can we set up a callback to count down from 10 to1 and print blastoff, with one count per second? I can think of at leasttwo approaches.

Page 31: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 31/35

var countdown = function() {

if(counter > 0) { print(counter); // set a new timeout callback setTimeout(countdown, 1000); counter--; } else { // we're done, don't ask for another callback print("Blast off!"); } };

print("Prepare for countdown:");// create a counter variable in the outer scope,// so that itis available to all calls of the countdown functionvar counter = 10; setTimeout(countdown, 1000);

123456789

1011121314151617181920

Page 32: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 32/35

Creating new functions with bind (bonus)►

print("Prepare for countdown:");for(var i = 10; i > 0; i--) {

// create a new function, with current value of i // bound to the function as permanent argument var printLater = print.bind(this, i);

setTimeout(printLater, 1000 * (10 - i) );}

123456789

Page 33: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 33/35

Functional programmingCallbacks are an example of functional programming: usingfunctions as parameters to change the behavior of other functions.

var compareForwards = function(num1, num2) { return num1 - num2; };var compareBackwards = function(num1, num2) { return num2 - num1; };

var numbers = [9, 11, 9, 17, 42, 2];

numbers.sort(compareForwards); // sort method of Array objectsprint(numbers);

numbers.sort(compareBackwards);print(numbers);

123456789

10

Page 34: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 34/35

Animation callbacks►

var drawFrame = function() { ellipse(x, y, 20, 20); // draw a ball // update the ball position x += vx; y += vy;};

var FRAME_DELAY = 50;

// initial position for the ball, in outer scope so// available each time:var x = 100;var y = 100;

123456789

101112131415

Page 35: Fundamentals of Web Programmingfwp/slides04/slides04db.pdf · 3/31/2016 FWP lecture 4 ... Fundamentals of Web Programming Lecture 4: ... Functional programming ...

3/31/2016 FWP lecture 4

http://www.cs.dartmouth.edu/~fwp/slides04/slides04db.html?m=all&s=0&f=0 35/35

Exercise: bouncing ballClear the window each time through the animation loop. Also, fix theball so that it bounces of the sides of the screen. Also

var drawFrame = function() { ellipse(x, y, 20, 20); // draw a ball // update the ball position x += vx; y += vy;};

var FRAME_DELAY = 50;

// initial position for the ball, in outer scope so// available each time:var x = 100;var y = 100;

123456789

101112131415