Programming Methodology

Slides:



Advertisements
Similar presentations
Road Map Introduction to object oriented programming. Classes
Advertisements

Access to Names Namespaces, Scopes, Access privileges.
Loops – While, Do, For Repetition Statements Introduction to Arrays
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
Understanding class definitions Looking inside classes.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
David Stotts Computer Science Department UNC Chapel Hill.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
CMSC 330: Organization of Programming Languages Functional Programming with OCaml.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Arrays and Loops. Learning Objectives By the end of this lecture, you should be able to: – Understand what a loop is – Appreciate the need for loops and.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
Variable Scope. When you declare a variable, that name and value is only “alive” for some parts of the program  We must declare variables before we use.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
CSC 211 Java I for loops and arrays.
Chapter 7: User-Defined Functions II
CSE 374 Programming Concepts & Tools
CHAPTER 4 CLIENT SIDE SCRIPTING PART 3 OF 3
Bill Tucker Austin Community College COSC 1315
Lecture 5: Some more Java!
Variables, Environments and Closures
Object Oriented Programming
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
CMPT 201 Functions.
Student Book An Introduction
Methods and Parameters
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Winter 2013.
Lesson 16: Functions with Return Values
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Spring 2013.
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Spring 2016.
Dr. Bhargavi Dept of CS CHRIST
CS5220 Advanced Topics in Web Programming JavaScript Basics
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Autumn 2018.
Namespaces, Scopes, Access privileges
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Zach Tatlock Winter 2018.
EECE.2160 ECE Application Programming
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Autumn 2017.
Brent M. Dingle Texas A&M University Chapter 5 – Section 2-3
CS3220 Web and Internet Programming JavaScript Basics
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Spring 2019.
ITM 352 Functions.
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
C++ Object Oriented 1.
Parameters and Arguments
Programming Methodology
Reasoning with Types.
Presentation transcript:

Programming Methodology COMPSCI 220 Programming Methodology

First-Class Functions Some of the concepts in this section are very hard, and won’t really make sense until we get to the next section, where we introduce the idea of closures. We recommend revisiting the examples in this section after you learn about closures. First-Class Functions We introduce the idea that functions are values, code is data, etc.

Recap: a function can be an argument to another function // map<S,T>(f: (x : S) => T, a: S[]): T[] function map(f, a) { let b = []; for (let i = 0; i < a.length; ++i) { b.push(f(a[i])); } return b; } // double(x: number): number function double(x) { return 2 * x; } // doubleAll(a: number[]): number[] function doubleAll(a) { return map(double, a);

Simpler Example // app<S,T>(f: (x : S) => T, x: S): T function app(f, x) { Return f(x); } // double(x: number): number function double(x) { return 2 * x; } app(double, 10);

Nested Functions // map<S,T>(f: (x : S) => T, a: S[]): T[] function map(f, a) { let b = []; for (let i = 0; i < a.length; ++i) { b.push(f(a[i])); } return b; } // doubleAll(a: number[]): number[] function doubleAll(a) { // double(x: number): number function double(x) { return 2 * x; } return map(double, a); The double function is a helper. Nesting it inside doubleAll makes that clear. We cannot call double from doubleAll.

More Nested Functions // foo(x: number): number function foo(x) { // bar(y: number): number function bar(y) { return y + 2; } return bar(x); assert(foo(10) === 12); // A(x: number): number function A(x) { // B(y: number): number function B(y) { return x + y; } return B(20); assert(foo(10) === 30); B is nested within A, and has a reference to the variable x that is declared outside B.

A function can return another function // B(x: number): number function B(x: number) { return x + 1; } // A(): (x: number) => number function A(x) { return B; let f = A(); assert(f(10) === 11); // makeAdder(x: number): (y: number) => number function makeAdder(x) { function f(y) { return x + y; } return f; let f1 = makeAdder(10); assert(f1(1) === 11); let f2 = makeAdder(20); assert(f2(1) === 21); assert(f1(2) === 12); Several concepts (1) f is nested within makeAdder, (2) f references x which is declared outside, (3) makeAdder returns the functions f, and (4) the value of x is different for each f.

Functions do not have to be named // makeAdder(x: number): (y: number) => number function makeAdder(x) { // (y: number) => number return function(y) { return x + y; } assert(makeAdder(20)(2) === 22); assert((function(x) { return x + 10 })(1) === 11); let f = function(x) { return x + 1 }; function f(x) { Return x + 1; Instead of naming the nested function, we just return it. We can apply a function without ever naming it. These two are identical.

Functions can be stored in data structures let a = [ function(x) { return x + 1; }, function(y) { return y * 2; } ]; assert(a[0](a[1](10)) === 21); assert(a[1](a[0](10)) === 22);

Functions are Values “Functions are values” or “functions are first-class” means that functions can be used in the same contexts as other values (e.g., numbers, strings, and objects). You can: Use a function as an argument to another function Return a function as the result of a function Functions do not have to be named Functions can be stored in data structures (i.e., functions are data and code). You can substitute the word function with number, string, or object in the statements above.

Function calls vs declarations The following examples should be straightforward. The only wrinkle is that we are going to return functions and nest functions. Function calls vs declarations

What is the output of each of these programs? function foo() { function bar() { console.log("a"); }; return bar; } let f = foo(); function foo() { function bar() { console.log("a"); }; bar(); return bar; } let f = foo(); function foo() { function bar() { console.log("a"); }; return bar; } let f = foo(); f(); We return bar. We do not apply bar. We define the function bar. We actually apply bar.

Scope and Closures

What is the output of the following programs? let i = 0; console.log(i); { let i = 1; } function foo() { let i = 2; foo(); let i = 0; console.log(i); { i = 1; } function foo() { i = 2; foo(); "let" declares new variables. The variable scope is confined to a block (braces). Variables inside a block may shadow variables outside. No new variable declaration Hence refers to variable declared in surrounding block. Do not use “var”: https://repl.it/@JoydeepBiswas/vars

Exercise: Scale 2D points Problem Statement: Write a function that consumes an array of 2D points and produces an array of 2D points, where each point is scaled by 2. Examples: scale2([[0, 1], [10, 2]]) // produces [[0, 2], [20, 4]] Type Signature: scale2(a: number[][]): number[][] Implementation: // scale2(a: number[][]): number[][] function scale2(a) { return a.map(function(p) { return [2 * p[0], 2 * p[1]]; }); } Problem Statement: Write a function that consumes an array of 2D points and produces an array of 2D points, where each point is scaled by 5. Examples: scale2([[0, 1], [10, 2]]) // produces [[0, 5], [50, 10]] Type Signature: scale5(a: number[][]): number[][] Implementation: // scale2(a: number[][]): number[][] function scale2(a) { return a.map(function(p) { return [5 * p[0], 5 * p[1]]; }); } All the functions passed to map are repeated, except for the constants 2, 5, etc. Can we somehow reuse code?

Abstraction: Take 1 This works. However: We need a global variable n let n = 2; function scaleByN(a) { return a.map(function(p) { return [n * p[0], n * p[1]]; }); } n = 2; console.log(scaleByN([[0, 1], [10, 2]])); n = 5; n = 10; console.log(points.map(scaleByN)); This works. However: We need a global variable n Each operation is actually two steps: 1) set n 2) call scaleByN Can we do better?

Abstraction: Take 2 // scaleBy(n: number): // (a: number[][]) => number[][] function scaleBy(n) { // f(a: number[][]): number[][] function f(a) { return a.map(function(p) { return [n * p[0], n * p[1]]; }); }; return f; } let scale2 = scaleByN(2); let scale5 = scaleByN(5); This raises several questions: What is the value of p in scaleBy? scaleBy returns a function. When is that function executed? How does the returned function “remember” the value of n? The variable p is not in scope in scaleBy. Trick question! In the code on the left, it is never executed. scaleBy does not return the function f. scaleBy returns a closure. A closure is a function with values for its free variables. You cannot directly write a closure. So, we will invent our own notation to talk about them. The value of scale2 is f [n → 2 ] The value of scale5 is f [n → 5 ]

CLOSURES

Another example What is the value of f and g? f === add [ x → 10] // makeAdder(x: number): (y: number) => number function makeAdder(x) { // add(y: number): number function add(y) { return x + y; } return add; let f = makeAdder(10); let g = makeAdder(100); let r = f(1); What is the value of f and g? f === add [ x → 10] g === add [ x → 100] What is the value of r? We apply the closure add [ x → 10] to the argument 1.

Closures + assignment // crazy(x: number): (y: number) => number function crazy(x) { // add(y: number): number function add(y) { let tmp = x + 1; x = x + 1; return tmp + y; } return add; let f = crazy(10); // add[x → 10] let g = crazy(10); // add[x → 10] console.log(f(100)); // Calls add[x→10] updates f to add[x→11] and returns 110; console.log(f(100)); // Calls add[x→11], updates f to add[x→12] and returns 111; console.log(g(100)); // Calls add[x→10], updates g to add[x→11] and returns 110; Closures + assignment = very confusing. You need to understand this. (We will have questions like this on the exam.) We strongly recommend you not write code like this, though it is sometimes unavoidable.

Exercise function printString(s) { function f() { console.log(s); } return f; let f1 = printString("cats"); let f2 = printString("dogs"); f1(); Q: What is the value of s? A: The question is meaningless. Q: What is value of s within f. A: The outer function, printString has not yet been applied. Q: What is the value of s within f1? A: The value of f1 is f[s→"cats"], thus the value of s is "cats".

Exercise: What do these two programs print? function rootOrNot(root) { function F(x) { if (root) { return Math.sqrt(x); } else { return x; } }; return F; let root = true; let f = rootOrNot(root); console.log([16, 25, 81].map(f)); function rootOrNot(root) { function F(x) { if (root) { return Math.sqrt(x); } else { return x; } }; return F; let root = true; let f = rootOrNot(root); root = false; console.log([16, 25, 81].map(f)); The value of f is F[root→true]. The global variable root and the argument root are two different variables. Therefore, the two programs produce the same output.

Closures: What will this program output? function rootOrNot(root) { return function(x) { if (root) { return Math.sqrt(x); } else { return x; } }; console.log([16, 25, 81].map(rootOrNot(true))); console.log([16, 25, 81].map(rootOrNot(false)));