Functions as Data Eric Roberts CS 106B March 13, 2013.

Slides:



Advertisements
Similar presentations
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Advertisements

Dynamic Allocation Eric Roberts CS 106B February 4, 2013.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 6/20/2015CS150 Introduction to Computer Science 1 Functions Chapter 6, 8.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
 Wednesday, 9/25/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/25/02  QUESTIONS??  Today: More on functions  Reading: Chapter 3 through 3.7 
Guide To UNIX Using Linux Third Edition
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Memory and C++ Eric Roberts CS 106B February 1, 2013.
Functions in C++ Eric Roberts CS 106B January 9, 2013.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Java and C++, The Difference An introduction Unit - 00.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
“In mathematics and computer programming, Index notation is used to specify the elements of an array of numbers”
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Arrays Chapter 7.
Operator Overloading Introduction
Pointers and Classes.
Motivation for Generic Programming in C++
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Templates.
Data Structure and Algorithms
Functions in C++ Eric Roberts CS 106B January 7, 2015.
CMSC202 Computer Science II for Majors Lecture 08 – Overloaded Constructors Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
CS410 – Software Engineering Lecture #11: C++ Basics IV
Chapter 5 Classes.
Pointers and Pointer-Based Strings
JavaScript: Functions.
Templates.
Object Oriented Programming COP3330 / CGS5409
Introduction to Classes
More About Data Types & Functions
CS150 Introduction to Computer Science 1
Linked Lists Chapter 4.
CS150 Introduction to Computer Science 1
CS149D Elements of Computer Science
CS150 Introduction to Computer Science 1
Pointers and Pointer-Based Strings
Arrays Arrays A few types Structures of related data items
CS150 Introduction to Computer Science 1
CS410 – Software Engineering Lecture #5: C++ Basics III
Pointers and dynamic objects
Lesson 25 Miscellaneous Topics
Templates An introduction.
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
Instructor: Dr. Michael Geiger Spring 2017 Lecture 12: Exam 1 Preview
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Using Modules.
Presentation transcript:

Functions as Data Eric Roberts CS 106B March 13, 2013

Iteration Strategies Chapter 20 of the text covers two strategies for iterating over collections: iterators and mapping functions. Dawson showed you how to use iterators in his lecture last Friday. My goal for today is to discuss mapping functions and, more generally, the entire idea of using functions as data.

The von Neumann Architecture John von Neumann and J. Robert Oppenheimer One of the foundational ideas of modern computing—traditionally attributed to John von Neumann although others can make valid claims to the idea—is that code is stored in the same memory as data. This concept is called the stored programming model. If you go on to take CS 107, you will learn more about how code is represented inside the computer. For now, the important idea is that the code for every C++ function is stored somewhere in memory and therefore has an address. 0000 0004 0008 000C 0010 0014 0018 001C 0020 0024 0028 002C FFD0 FFD4 FFD8 FFDC FFE0 FFE4 FFE8 FFEC FFF0 FFF4 FFF8 FFFC . int main() { cout << "hello"; cout << endl; return 0; }

Callback Functions The ability to determine the address of a function makes it possible to pass functions as parameters to other functions. In this example, the function main makes two calls to plot. The first call passes the address of sin, which is 0028. The second passes the address of cos, which is 0044. The plot function can call this function supplied by the caller. Such functions are known as callback functions. int main() { GWindow gw; plot(gw, sin, . . .); plot(gw, cos, . . .); return 0; } 0000 0004 0008 000C 0010 0014 0018 001C 0020 double sin(double x) { . . . code to compute sin(x) . . . } 0024 0028 002C 0030 0034 0038 003C double cos(double x) { . . . code to compute cos(x) . . . } 0040 0044 0048 004C 0050 0054 0058 005C 0060 0064

Function Pointers in C++ One of the hardest aspects of function pointers in C++ is writing the type for the function used in its declaration. The syntax for declaring function pointers is consistent with the syntax for other pointer declarations, although it takes some getting used to. Consider the following declarations: double x; Declares x as a double. double *px; Declares px as a pointer to a double. double f(); Declares f as a function returning a double. double *g(); Declares g as a function returning a pointer to a double. double (*proc)(); Declares proc as a pointer to a procedure returning a double. double (*fn)(double); Declares fn as a pointer to a function taking and returning a double.

Plotting a Function Section 20.2 defines a plot function that draws the graph of a function on the graphics window. plot(gw, cos, -2 * PI, 2 * PI, -1.0, 1.0); The arguments to plot are the graphics window, the function, and the limits in the x and y directions. For example, calling produces the following output:

Exercise: Defining the plot Function What is the prototype for the plot function? 1. void plot(GWindow & gw, double (*fn)(double), void plot(GWindow & gw, double minX, double maxX, void plot(GWindow & gw, double minY, double maxY); How would you convert values x and y in the mathematical domain into screen points sx and sy? 2. Hint: In the time that x moves from minX to maxX, sx must move from 0 to gw.getWidth(); y must move in the opposite direction from gw.getHeight() to 0. double width = gw.getWidth(); double height = gw.getHeight(); double sx = (x - minX) / (maxX - minX) * width; double sy = height - (y - minY) / (maxY - minY) * height;

Exercise: Dispatch Strategies In your implementation of BASIC, you presumably have a function that looks something like this: Statement *parseStatement(TokenScanner & scanner) { string token = toUpperCase(scanner.nextToken()); if (token == "REM") return new RemStmt(scanner); if (token == "LET") return new LetStmt(scanner); if (token == "PRINT") return new PrintStmt(scanner); if (token == "INPUT") return new InputStmt(scanner); if (token == "GOTO") return new GotoStmt(scanner); if (token == "IF") return new IfStmt(scanner); if (token == "END") return new EndStmt(scanner); error("Unrecognized statement: " + token); } This strategy would become problematic if there were more statement types or if those types could expand dynamically. How might you restructure this implementation so that the size of the code did not depend on the number of statements?

Mapping Functions The ability to work with pointers to functions offers one solution to the problem of iterating through the elements of a collection. To use this approach, the collection must export a mapping function that applies a client-specified function to every element of the collection. Most collections in the Stanford libraries export the method template <typename ValueType> void mapAll(void (*fn)(ValueType)); that calls fn on every element of the collection. As an example, you can print the elements of a Set<int> s, by calling s.mapAll(printInt) where printInt is void printInt(int n) { cout << n << endl; }

Exercise: Implement mapAll Implement the function void mapAll(void (*fn)(string)); as part of the StringMap class, for which the private section looks like this: /* Type definition for cells in the bucket chain */ struct Cell { std::string key; std::string value; Cell *link; }; /* Constant definitions */ static const int INITIAL_BUCKET_COUNT = 13; /* Instance variables */ Cell **buckets; /* Dynamic array of pointers to cells */ int nBuckets; /* The number of buckets in the array */

Passing Data to Mapping Functions The biggest problem with using mapping functions is that it is difficult to pass client information from the client back to the callback function. The C++ packages that support callback functions typically support two different strategies for achieving this goal: Passing an additional argument to the mapping function, which is then included in the set of arguments to the callback function. 1. Passing a function object to the mapping function. A function object is simply any object that overloads the function-call operator, which is designated in C++ as operator(). 2. For the last bit of today’s class, I’ll go through each of these strategies in the context of a program that writes out every word in the English lexicon that has a particular length.

The End