More on Abstract Data Types Noah Mendelsohn Tufts University Web: COMP 40: Machine.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
C Language.
Abstraction, Modularity, Interfaces and Pointers Original slides by Noah Mendelsohn, including content from Mark Sheldon, Noah Daniels, Norman Ramsey COMP.
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Copyright 2014 – Noah Mendelsohn Assemblers, Macros and The UM Macro Assembler (UMASM) Noah Mendelsohn Tufts University
Copyright 2014 – Noah Mendelsohn UM Macro Assembler Functions Noah Mendelsohn Tufts University Web:
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
CS Winter 2011 Further Introduction to the C programming language.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
C and Data Structures Baojian Hua
Run time vs. Compile time
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
CS 201 Functions Debzani Deb.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Adapted from Dr. Craig Chase, The University of Texas at Austin.
C++ fundamentals.
Copyright 2013 – Noah Mendelsohn Process Memory Noah Mendelsohn Tufts University Web:
CIS Computer Programming Logic
Lists in Python.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
File ▪ File – Unit of logical storage – Aid in manipulating exact sector of file data ▪ Abstract view of secondary physical storage devices ▪ Without files.
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
CS50 Week 2. RESOURCES Office hours ( Lecture videos, slides, source code, and notes (
Property of Jack Wilson, Cerritos College1 CIS Computer Programming Logic Programming Concepts Overview prepared by Jack Wilson Cerritos College.
CS107 References and Arrays By Chris Pable Spring 2009.
COP4020 Programming Languages Names, Scopes, and Bindings Prof. Xin Yuan.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Big Endian vs. Little Endian Storage of Numeric Data Noah Mendelsohn Tufts University Web:
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Topics memory alignment and structures typedef for struct names bitwise & for viewing bits malloc and free (dynamic storage in C) new and delete (dynamic.
Copyright 2014 – Noah Mendelsohn Code Tuning Noah Mendelsohn Tufts University Web:
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
A Quick Look at C for C++ Programmers Noah Mendelsohn Tufts University Web: COMP.
CS 31 Discussion, Week 5 Faisal Alquaddoomi, Office Hours: BH 2432, MW 4:30-6:30pm, F 12:00-1:00pm (today)
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
More on Abstract Data Types Noah Mendelsohn and Mark Sheldon Tufts University Web:
The Universal Machine (UM) Implementing the UM Noah Mendelsohn Tufts University Web:
Coding – Week 2 Functions, Arrays, and Objects. Functions  Functions are not a new concept – you’ve been using them already.  void setup() {} and void.
C++ Functions A bit of review (things we’ve covered so far)
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Lecture 11: Pointers B Burlingame 13 Apr Announcements Rest of semester  Homework Remaining homework can be done in pairs, turn in one paper with.
Computer Organization and Design Pointers, Arrays and Strings in C
Lesson #6 Modular Programming and Functions.
A bit of C programming Lecture 3 Uli Raich.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Functions Inputs Output
More About Data Types & Functions
Lesson #6 Modular Programming and Functions.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

More on Abstract Data Types Noah Mendelsohn Tufts University Web: COMP 40: Machine Structure and Assembly Language Programming (Spring 2014)

© 2010 Noah Mendelsohn Last time we covered  How data and pointers are stored in the computer’s memory  Abstraction, modularity, reuse, information hiding  The special role of void * and incomplete structures  Generalizing over values and types 2 Today  Generalizing over computation  Function pointers  Iteration and mapping in a functional style  Boxed and unboxed data structures

© 2010 Noah Mendelsohn Quick Review

© 2010 Noah Mendelsohn Software structures model real world objects and concepts  Integers  Students  Bank statements  Photographic images  Sound recordings  Etc. 4 These things aren’t bits!! They don’t live in computers, but…

© 2010 Noah Mendelsohn Software structures model real world objects and concepts  Integers  Students  Bank statements  Photographic images  Sound recordings  Etc. 5 We build data structures that model them The course materials refer to these is being in the “World of Ideas”

© 2010 Noah Mendelsohn Key principles to watch for  Abstraction –Refers to the act of “pulling away from” something so that unimportant details are hidden” 1  Modularity & clean interfaces –Each module “does one thing well” 2  Information hiding –Modules keep details of their internals secret  Generalization –When practical, each module or service should be as generally useful as possible 6 1 Prof. Mark Sheldon – COMP 11 Big IdeasCOMP 11 Big Ideas 2 Ken Thompson, co-inventor of Unix – The Unix PhilosophyThe Unix Philosophy

© 2010 Noah Mendelsohn Interfaces 7 Interface Implementation Client E.g. your fgroups program E.g. implementation of Hanson Table_T E.g. methods in Hanson table.h

© 2010 Noah Mendelsohn Interfaces 8 Interface Implementation Client Many different programs can re-use the interface and the implementation! The implementation chooses a representation … NOT visible to the client

© 2010 Noah Mendelsohn Interfaces 9 Interface Implementation Client E.g. your fgroups program E.g. implementation of Hanson Table_T E.g. methods in Hanson table.h My_table = Table_new(… … …) Q. What can Table_new return? I will show you two ways of doing this A.A pointer to data you can’t look at You will use this pointer to identify the new table

© 2010 Noah Mendelsohn Client doesn’t know secret implementation 10 Interface Implementation Client my_table = Table_new(… … …) Struct Table_t { …data declartions… } struct Table_T *table_ptr; void *table_ptr;

© 2010 Noah Mendelsohn Client doesn’t know secret implementation 11 Interface Implementation Client my_table = Table_new(… … …) Struct Table_t { …data declartions… } struct Table_T *table_ptr; void *table_ptr; Note: This declaration would be in the publicly used table.h!

© 2010 Noah Mendelsohn Client doesn’t know secret implementation 12 Interface Implementation Client my_table = Table_new(… … …) Struct Table_t { …data declartions… } struct Table_T *table_ptr; void *table_ptr; Note: These declarations are in the declaration (either in a table.c, or in a tableimp.h)

© 2010 Noah Mendelsohn Hanson does this with incomplete structs 13 Interface Implementation Client my_table = Table_new(… … …) Struct Table_t { …data declartions… } struct Table_T *table_ptr; struct Table_t *table_ptr; Client has incomplete declaration of the struct

© 2010 Noah Mendelsohn By the way, this is exactly what languages like C++ do 14 class Myclass { int some_method(int a) {…}; } Myclass my_object = new Myclass(); my_object -> some_method(5); Under the covers, C++ implements this as: my_object -> some_method(my_object, 5);

© 2010 Noah Mendelsohn Generalization

© 2010 Noah Mendelsohn You’ve already seen some generalization 16 int square3() { return 3*3; } We don’t do this int square(int n) { return n*n; } We do this! Generalize over input value Can we generalize over the type of information?

© 2010 Noah Mendelsohn We need to generalize over types 17 List_of_students_new(…); List_of_cars_new(…); List_of_bank_stmts_new(…); We don’t want this List_new(…); We want this! How do we declare the input to List_push()? (after all, its type could be anything) Can we generalize over the type of information?

© 2010 Noah Mendelsohn How do we declare List_push? 18 void List_push(List_T list, void *x); Hanson’s declaration for List_push struct Car {char *brand; int weight}; typedef struct Car Car; Car mycar = {“ford”, 2000}; Car *retrieved_car; mylist = List_list(NULL); /* create empty list */ List_push(mylist, &mycar); /* put my car on the list */

© 2010 Noah Mendelsohn Void * allows us to generalize over types 19 void List_push(List_T list, void *x); Hanson’s declaration for List_push The list will remember a pointer to anything. struct Car {char *brand; int weight}; typedef struct Car Car; Car mycar = {“ford”, 2000}; Car *retrieved_car; mylist = List_list(NULL); /* create empty list */ List_push(mylist, &mycar); /* put my car on the list */ Any pointer can be passed to a void * parameter

© 2010 Noah Mendelsohn Void * allows us to generalize over types 20 void List_push(List_T list, void *x); Hanson’s declaration for List_push struct Car {char *brand; int weight}; typedef struct Car Car; Car mycar = {“ford”, 2000}; Car *retrieved_car_p; mylist = List_list(NULL); /* create empty list */ List_push(mylist, &mycar); /* put my car on the list */ List_pop(mylist, &retrieved_car_p); /* get back mycar */ This generalization is known as universal polymorphism

© 2010 Noah Mendelsohn Void * allows us to generalize over types 21 void List_push(List_T list, void *x); Hanson’s declaration for List_push struct Car {char *brand; int weight}; typedef struct Car Car; Car mycar = {“ford”, 2000}; Car *retrieved_car_p; mylist = List_list(NULL); /* create empty list */ List_push(mylist, &mycar); /* put my car on the list */ List_pop(mylist, &retrieved_car_p); /* get back mycar */ IMPORTANT: Retrieved_car_p is already a pointer. Why do we have to pass the address of retrieved_car_p?

© 2010 Noah Mendelsohn Generalizing Over Computation

© 2010 Noah Mendelsohn Why generalize over function?  We’ve already generalized types…sometimes we need different code to work on each type –Classic example: we’re building a sort routine that can sort anything… –…the rules for sorting different types of things are different  Mapping: do the same operation on each entry in a collection  Providing or overriding behavior in a common implementation –Overriding default output format –Overriding data source for some input routine –Etc. 23

© 2010 Noah Mendelsohn Function pointers in C  We know the code is living in memory  Can we take the address of code? Yes! 24 Syntax int square(int n) { return n*n; } int (*somefunc)(int n); somefunc = □ printf(“3 squared is %d\n”, (*somefunc)(3));

© 2010 Noah Mendelsohn Be sure you understand why this works! 25 int square(int n) { return n*n; } int cube(int n) { return n*n*n; } int main(int argc, char *argv[]) { int (*somefunc)(int n); somefunc = □ printf("3 squared is %d\n", (*somefunc)(3)); somefunc = &cube; printf("3 cubed is %d\n", (*somefunc)(3)); return 0; }

© 2010 Noah Mendelsohn Be sure you understand why this works! 26 int square(int n) { return n*n; } int cube(int n) { return n*n*n; } int main(int argc, char *argv[]) { int (*somefunc)(int n); somefunc = □ printf("3 squared is %d\n", (somefunc)(3)); somefunc = &cube; printf("3 cubed is %d\n", (*somefunc)(3)); return 0; } The “*” is optional… …modern versions of C provide it for you if you leave it out.

© 2010 Noah Mendelsohn Using function pointers  You’ve seen a simple example  We often pass function pointers as arguments to other functions  This allows us to generalize over function  Examples from Hanson: –cmp and hash routines for tables –apply() functions for mapping 27

© 2010 Noah Mendelsohn Computing on Collections

© 2010 Noah Mendelsohn One option: loops 29 /* NOT how Hanson usually does it */ tab= Table_new(…): …add some data here.. for (i = 0, i < Table_length(arr) { upcase(Table_getnext(arr, NEXT)); } This is pseudo-code: some details just to show the idea. Hanson doesn’t do it this way anyway.

© 2010 Noah Mendelsohn The functional (Hanson) way 30 void upcasefunction(void *key, void **value, void *cl) { …can uppercase **value here.. } tab= Table_new(…): …add some data here.. Table_map(tab, upcasefunction, ??);

© 2010 Noah Mendelsohn The functional (Hanson) way 31 void upcasefunction(void *key, void **value, void *cl) { …can uppercase **value here.. } tab= Table_new(…): …add some data here.. Table_map(tab, upcasefunction, ??); The map Table_map function loops calling upcasefunction repeatedly, once for each entry Passing pointer to function

© 2010 Noah Mendelsohn The closure: shared data for the mapping 32 void upcasefunction(void *key, void **value, void *cl) { …can uppercase **value here.. } struct cl mycl {…shared data here..}; tab= Table_new(…): …add some data here.. Table_map(tab, upcasefunction, &mycl); The data in mycl is passed in from the caller… …can be seen and updated in upcasefunction

© 2010 Noah Mendelsohn Mapping vs loops  Map advantages: –Clean, easy to reason about –Often less code to write –Automatically gets the iteration right (e.g. length)  Disadvantages –Less flexible: what if we want to iterate in unusual order? –Less obvious how to iterate multiple structures at once (there are ways) –Getting closures right can be tricky  Mapping is a classic functional programming construct 33

© 2010 Noah Mendelsohn Unboxed Data Generalizing to Collections of Objects that Aren’t Pointers

© 2010 Noah Mendelsohn Boxed and unboxed collections  The collections you’ve seen so far are boxed List_push(mylist, &data); /* list stores a pointer */  Problem: we want an array of 1 million characters –A character is 1 byte –A pointer to a character is 8 bytes –Even for bigger types, chasing pointers takes time, and allocating memory can be expensive  Unboxed collections: store the actual data, not a pointer! /* array of chars */ my_array = UArray_new( , sizeof(char)); /* set the char at offset 500 to ‘X’ */ char *mychar = UArray_at(my_array, 500); *mychar = ‘X’; 35

© 2010 Noah Mendelsohn Boxed and unboxed collections  The collections you’ve seen so far are boxed List_push(mylist, &data); /* list stores a pointer */  Problem: we want an array of 1 million characters –A character is 1 byte –A pointer to a character is 8 bytes –Even for bigger types, chasing pointers takes time, and allocating memory can be expensive  Unboxed collections: store the actual data, not a pointer! /* array of chars */ my_array = UArray_new( , sizeof(char)); /* set the char at offset 500 to ‘X’ */ char *mychar = UArray_at(my_array, 500); *mychar = ‘X’; 36 Space for characters is allocated in the Hanson array…we could use sizeof(struct SomeBigStruct) and that would work too!

© 2010 Noah Mendelsohn Boxed and unboxed collections  The collections you’ve seen so far are boxed List_push(mylist, &data); /* list stores a pointer */  Problem: we want an array of 1 million characters –A character is 1 byte –A pointer to a character is 8 bytes –Even for bigger types, chasing pointers takes time, and allocating memory can be expensive  Unboxed collections: store the actual data, not a pointer! /* array of chars */ my_array = UArray_new( , sizeof(char)); /* set the char at offset 500 to ‘X’ */ char *mychar = UArray_at(my_array, 500); *mychar = ‘X’; 37 Uarray_at returns a pointer directly into the data array that’s inside the Hanson implementation…that’s its contract.