Polymorphism C and Data Structures Baojian Hua

Slides:



Advertisements
Similar presentations
Overloading Having more than one method with the same name is known as overloading. Overloading is legal in Java as long as each version takes different.
Advertisements

A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
C and Data Structures Baojian Hua
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Modern Programming Languages, 2nd ed.
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Data Structure & Abstract Data Type
Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Recursion CS 367 – Introduction to Data Structures.
Data Structure & Abstract Data Type C and Data Structures Baojian Hua
C++ Programming Languages
Extensible Array C and Data Structures Baojian Hua
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Optimization Compiler Baojian Hua
Generic programming in Java
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Polymorphism Discrete Mathematics and Its Applications Baojian Hua
Structures C and Data Structures Baojian Hua
CS100A, Fall 1997, Lecture 241 CS100A, Fall 1997 Lecture 24, Tuesday 25 November (There were no written notes for lecture 23 on Nov. 20.) Data Structures.
Map, Set & Bit-Vector Discrete Mathematics and Its Applications Baojian Hua
Abstract Data Type C and Data Structures Baojian Hua
C and Data Structures Baojian Hua
Standard ML- Part II Compiler Baojian Hua
CS 536 Spring Code Generation II Lecture 21.
CSE 130 : Winter 2006 Programming Languages Ranjit Jhala UC San Diego Lecture 7: Polymorphism.
Pointers and Arrays C and Data Structures Baojian Hua
C and Data Structures Baojian Hua
Extensible Array C and Data Structures Baojian Hua
Linked List C and Data Structures Baojian Hua
Tree C and Data Structures Baojian Hua
Run-time Environment and Program Organization
Set, Map & Bit-Vector Discrete Mathematics and Its Applications Baojian Hua
Functional List C and Data Structures Baojian Hua
String C and Data Structures Baojian Hua
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
1.9 Methods academy.zariba.com 1. Lecture Content 1.What is a method? Why use methods? 2.Void Methods and methods with parameters 3.Methods which return.
Object-oriented Languages Compiler Baojian Hua
Set & Bit-Vector Discrete Mathematics and Its Applications Baojian Hua
Closure and Environment Compiler Baojian Hua
Memory Layout C and Data Structures Baojian Hua
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Polymorphism Discrete Mathematics and Its Applications Baojian Hua
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
Intro to Generic Programming Templates and Vectors.
Types(2). 2 Recursive Problems  One or more simple cases of the problem have a straightforward, nonrecusive solution  The other cases can be redefined.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
Computer Science Detecting Memory Access Errors via Illegal Write Monitoring Ongoing Research by Emre Can Sezer.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
CS 261 – Data Structures Introduction to C Programming.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Polymorphism Discrete Mathematics and Its Applications Baojian Hua
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
UMBC CMSC 331 Java Review of objects and variables in Java.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Closure Compiler Baojian Hua Closure An implementation technique traditionally for functional languages Lisp, Scheme, Haskell, Ocaml,
Section 11: Comparing Java and C
Computer Organization and Design Pointers, Arrays and Strings in C
Programming Languages and Paradigms
Pass by Reference.
Modern Programming Languages
Presentation transcript:

Polymorphism C and Data Structures Baojian Hua

An old dream in CS Famous slogans: “ Write code once, used everywhere! ” “ Never write same code twice! ” Polymorphism Poly + morphism Elegant and amazing combination of theory and practice in CS!

Why polymorphism? // a list of integer: struct List_t_int { int data; struct List_t_int *next; }; // “length” int length (List_t_int l) { int size=0; List_t_int temp = l->next; while (temp) { size++; temp=temp->next; } return size; } the “ data ” field?

Why polymorphism? // what about if we want a list of string? struct List_t_string { char *data; struct List_t_string *next; }; // function “length” remains the same? int length (List_t_string l) { int size=0; List_t_string temp = l->next; while (temp) { size++; temp=temp->next; } return size; }

Outline Ad-hoc poly ’ Parametric poly ’ Subtype poly ’

Ad-hoc poly ’ Functions operate on different but a limited set of data type e.g., “+” in C int * int, double * double, char * * int but not: char * * char * First introduced by Strachey in 1967 Evolve into a feature called “ overloading ” in modern OO languages

Ad-hoc poly ’ Overloading in modern OO languages: Same printing function name with different argument types: void print (int x); void print (char *s); Compilers will dispatch function calls print (5); print (“hello”); Bad news is that C does not support overloading! We ’ d have to do some hacking. :-( Or we can write unique names, as: void Int_print (int x); void String_print (char *s);

Parametric poly Basic idea: decorating data types (data structure + functions) with type variables Polymorphic data structures Polymorphic functions we start with this

E.g. int max (int x, int y) { return x>y? x: y; } // but we’ve observed the problem: double max (double x, double y) { return x>y? x: y; } // What about factor out the type names: X max (X x, X y) { return x>y? x: y; } // but this function does not type check!

Old trick #define max(x, y) x>y? x: y // So we can write: int m = max(3, 4); // or double n = max (3.14, 2.71); // but this is very good! Why? // We can do better by hoisting “X” further: #define max_X(X) \ X max (X x, X y) \ { \ return x>y? x: y; \ } size

Client code #define max_X(X) \ X max (X x, X y) \ { \ return x>y? x: y; \ } max_X(int) int main () { max (3, 4); } Questions: 1: what about we write this? max_X (double) does this program still type check? 2: what about we write max_X (char *) is char * comparable? is this algorithm correct?

Client code #define max_X(X) \ X max (X x, X y, int (*m)(X, X)) \ { \ if (1==m(x, y)) \ return x; \ return y; \ } max_X(int) int int_compare (int x, int y) {…} int main () { max (3, 4, int_compare); }

List revisit #define List_X(X) struct List_t { X data; struct List_t *next; }; // “length” int length (List_t l) { int size=0; List_t temp = l->next; while (temp) { size++; temp=temp->next; } return size; } the “ data ” field?

Client code // we want a list of integer: List_X(int) // we want a list of double: List_X(double)

Summary so far Parametric poly: data structures and functions take extra type parameters (hence the name) instation at compile-time Monomorphinization: code eventually becomes monomorphic faithfully models the feature of template in C++

Summary so far Pros: very powerful and elegant no runtime overhead (code is eventually mono) of course, require some C hack Cons: code explosion (due to monomorphinization) but seldom observed in practical code the poly code itself is not type checked compilation may be slow

Subtype poly struct List_t { X data; struct List_t *next; }; // Key idea: what if we can invent a most general // type “X”, such that any value is compatible // with “X”. // In C, this type is “void *”.

List revisit struct List_t { void *data; struct List_t *next; }; // Leave it an exercise to write function “length”

Client code int main () { // we want a list of integer: for (int i=0; i<10; i++) { int *p = malloc (sizeof (*p)); *p = i; List_insertHead (l, p); } // we want a list of double: for (int i=0; i<10; i++) { double *p = malloc (sizeof (*p)); *p = i; List_insertHead (l, p); }

Subtype poly All pointer types can be treated as a subtype of void * so we ’ d have to heap-allocate all objects to accompany this type Java or C# go even further: all objects are heap-allocated the most general type is Object this models Java generic honestly

Subtype poly Pros: single piece of code no compilation overhead Cons: Safety issue ugly type cast, and must be veryyyyyyyyyyyyyy careful efficiency issue allocation and garbage collection complexity issue

Think abstractly struct List_t { int data; struct List_t *next; }; // Is it a good idea to write this function? int exists (List_t l, int x); // Or this function? int sum (List_t l, int init); // Or this one? void print (List_t l);

Think abstractly void print (List_t l) { List_t temp = l->next; while (temp) { printf (“%d, ”, temp->data) temp = temp->next; } return; }

Think abstractly // But what if we make it parametric poly? #define List_X(X) struct List_t { X data; struct List_t *next; }; void print (List_t l);

1st try void print (List_t l) { List_t temp = l->next; while (temp) { printf (“%???”, temp->data); temp = temp->next; } return; }

Think abstractly // To make it parametric poly: #define List_X(X) struct List_t { X data; struct List_t *next; }; // so we’d have to make “print” more abstract! void print (List_t l, void (*p)(X));

2nd try void print (List_t l, void (*p)(X)) { List_t temp = l->next; while (temp) { p (temp->data); temp = temp->next; } return; }

Client code // instantiate an “int” list: List_X(int) void f (int x) { printf (“%d, ”, x); } int main () { List_t list = …; // cook a list of int List_print (list, f); }