Generics "It is easy to study the rules of overloading and of templates without noticing that together they are one of the keys to elegant and efficient.

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Advertisements

Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Object-Oriented Programming In Lisp. Lisp vs. Scheme 1.Lisp has much more built-in functions and special forms, the Scheme language definition takes 45.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
CLOS To start off with, CLOS (pronounced “kloss” or “see- loss”) is very different from other object oriented programming languages –Multiple inheritance.
More about classes and objects Classes in Visual Basic.NET.
Alok Mehta - Programming in Lisp - Lecture Programming in Lisp Lecture 6 - Structure; Case Study: Blocks World.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
Structures Structures in LISP are analogous to that in C. To create a structure, use the following syntax: (defstruct Name Slot1 Slot2 Slot3) An example.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
מבוא מורחב - שיעור 12 1 Lecture 12 Data directed programming Message passing dotted-tail notation & apply Section 2.4, pages ,2.5.2 pages.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
How to define functions? (DEFUN function-name parameter-list commands ) Example: (DEFUN myFunction (x y) (/ x y) ) To call this function, you would then.
General pattern for selecting some elements of a list This negatives example illustrates a general pattern: If you want a function which selects some elements.
Perimeter and Area Please view this tutorial and answer the follow-up questions on loose leaf to turn in to your teacher.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
1 CLOS: Common Lisp Object System Basic principles of CLOS Classes, Instances and Slots Inheritance Generic functions Methods Multi-methods Comparison.
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.
Trees! =) Write up-add tree which behaves in this manner: 1 31 / \ / \ 3 5  21 9 / | \ \ / | \ \
Inheritance Extending Class Functionality. Polymorphism Review Earlier in the course, we examined the topic of polymorphism. Many times in coding, we.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
Polymorphism, Abstraction and Virtual Functions. In this slide, we introduce virtual functions and two complex and powerful uses for derived classes that.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
11 Speed & Debug.  Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage,
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
Session 24 Chapter 12: Polymorphism. Polymorphism polymorphism comes from the Greek root for “many forms” polymorphism is about how we can use different.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Control in LISP More on Predicates & Conditionals.
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh) reading: 9.5, 11.1, slides created by Marty Stepp
EE 422C Interfaces Day 5. 2 Announcements SVN has Project 2. –Partly due next week. –SVN update to get it in your repository. See Piazza for Grocery List.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
Area and Perimeter.
1 Variable Declarations Global and special variables – (defvar …) – (defparameter …) – (defconstant …) – (setq var2 (list 4 5)) – (setf …) Local variables.
Structures “The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by.
Fall 2008Programming Development Techniques 1 Topic 16 Assignment and Local State Section 3.1.
Session 18 Lab 9 Re-cap, Chapter 12: Polymorphism & Using Sound in Java Applications.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
C# Programming Methods.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Perimeter and Area Formulas.  Perimeter is the distance around an object. It is easily the simplest formula. Simply add up all the sides of the shape,
Week 5 Extending classes in Java. Extending classes u Using an existing classes as the basis for a new one u Defining only the differences between the.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
1 More About Derived Classes and Inheritance Chapter 9.
simplify radical expressions involving addition and subtraction.
CLOS CSC 358/
Lists in Lisp and Scheme
Understanding Inheritance
FP Foundations, Scheme In Text: Chapter 14.
two-dimensional shape.
Java – Inheritance.
Modern Programming Languages Lecture 20 Fakhar Lodhi
Peter Seibel Practical Common Lisp Peter Seibel
Common Lisp II.
Lisp.
Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in.
Presentation transcript:

Generics "It is easy to study the rules of overloading and of templates without noticing that together they are one of the keys to elegant and efficient type- safe containers.“ -Bjarne Stroustrup

Polymorphism (1) Because LISP doesn’t use type checking, we can easily write useful general functions that work for several different data types >(defun zip (xs ys) (if (and (consp xs) (consp ys)) (cons (cons (car xs) (car ys)) (zip (cdr xs) (cdr ys))) nil)) ZIP >(zip '(a b c d) '( )) ((A. 1) (B. 2) (C. 3) (D. 4))

Polymorphism (2) But what if we want a function to behave differently depending on the types of its arguments? (defstruct square (length 0)) (defstruct circle (radius 0)) (defun perimeter (shape) (cond ((square-p shape) (* 4 (square-length shape))) ((circle-p shape) (* 2 PI (circle-radius shape))) (t 0))) We have to have a case for every possible shape For any shape we add, we have to update the perimeter function

A Better Way: Generics Generics allow the same function name to be associated with several different types (a kind of overloading) (defgeneric perimeter (shape)) (defmethod perimeter ((shape square)) (* 4 (square-length shape))) (defmethod perimeter ((shape circle)) (* 2 PI (circle-radius shape))) >(perimeter (make-square :length 5)) 20 >(perimeter (make-circle :radius 2)) L0 Generics also form the basis of LISP’s Object System (OOP) Not supported in GCL yet. Try CLISP

Adding Methods Now it is easy to expand the functionality of the perimeter method. If we add a new shape… (defstruct rectangle (width 0) (height 0)) We simply add a new method (defmethod perimeter ((shape rectangle)) (+ (* 2 (rectangle-width shape)) (* 2 (rectangle-height shape))) )

Extra Parameters The type declarations following the variable name is called a specializer Methods can take more than one parameter, optionally specializing on any of them (a method that doesn’t specialize on any parameter is basically a function) type-of and typep are useful for determining type (be aware of supertypes) >(typep 5 'number) T > (type-of 5) (INTEGER )

Extra Parameters Example (defgeneric combine (a b)) (defmethod combine ((a number) (b number)) (+ a b)) (defmethod combine ((a character) (b character)) (code-char (+ (char-code a) (char-code b)))) (defmethod combine (a (b cons)) (cons a b)) >(combine 5 6) 11 >(combine #\A #\B) #\U0083 >(combine 'A '(5 B S 30)) (A 5 B S 30) >(combine 3 'A) Error

Benefits Finally, some well structured type safety! – Methods throw an error if no definition fits the types Extra expressive power: allows for polymorphism even when the underlying algorithms are different for different data types Takes advantage of inheritance (as we’ll see in a moment. But first…)

While We’re Talking About Types Structures can also require that their slots have particular types, providing even more type safety >(defstruct rectangle (width 0 :type number) (height 0 :type number)) RECTANGLE >(make-rectangle :width 5.6 :height 3) #S(RECTANGLE :WIDTH 5.6 :HEIGHT 3) >(make-rectangle :width 'A :height '(3 4 5)) Error Now, on to dealing with inheritance…

Call-Next-Method If we want a method to be mostly the same for all members of a class, but slightly specialized for certain subclasses, then we can split up the code across different methods Done with call-next-method. It calls the next method that fits the arguments in decreasing order of specificity Similar to calling methods of a super class in Java

Call-Next-Method Example (1) Suppose we want to have several types of bank accounts For all accounts, a withdraw consists of checking for available funds and removing them if possible Savings accounts are only allowed 3 withdraws per month, or else there is an additional service charge of $3 for each withdraw Checking accounts are sometimes linked to a savings account to provide overdraft protection. If a withdraw exceeds available funds in a checking account, then the difference is taken from the backup savings account First design the structures (defstruct account (balance 0)) (defstruct (savings (:include account)) (withdraws 0)) (defstruct (checking (:include account)) (backup nil))

Call-Next-Method Example (2) Now design the methods (defgeneric withdraw (source amount)) (defmethod withdraw ((source account) (amount number)) (let ((b (account-balance source))) (if (> amount b) (error "Insufficient funds") (progn (setf (account-balance source) (- b amount)) source)))) (defmethod withdraw ((source savings) (amount number)) (setf (savings-withdraws source) (1+ (savings-withdraws source))) (when (> (savings-withdraws source) 3) (setf amount (+ 3 amount)) ) (call-next-method source amount)) (defmethod withdraw ((source checking) (amount number)) (let ((overdraft (- amount (account-balance source)))) (when (and (plusp overdraft) (checking-backup source)) (withdraw (checking-backup source) overdraft) (setf (account-balance source) (+ (account-balance source) overdraft))) (call-next-method)))

Call-Next-Method Example (3) >(defvar s (make-savings :balance 1000 :withdraws 3)) S >(withdraw s 500) #S(SAVINGS :BALANCE 497 :WITHDRAWS 4) >(defvar c (make-checking :balance 10 :backup s)) C >(withdraw c 20) #S(CHECKING :BALANCE 0 :BACKUP #S(SAVINGS :BALANCE 484 :WITHDRAWS 5)) > (withdraw c 500) Insufficient funds error

Another Specializer Methods can also be specialized based on equality with a specific value (defvar exception (make-savings :balance 1000 :WITHDRAWS 5)) (defmethod withdraw ((source (eql exception)) (amount number)) (setf (savings-withdraws source) 0) (call-next-method)) >(withdraw exception 200) #S(SAVINGS :BALANCE 800 :WITHDRAWS 1)

What Else Can Generics Do? Although we’ve been using generics with structures, they were actually designed to work with the Common LISP Object System (CLOS) LISP has types called classes which are defined with defclass Classes aren’t too different from structures, though they are created ( make-instance ) and accessed ( slot-value ) differently Perhaps the most interesting feature of classes is that they allow for multiple inheritance, which is not so scary in LISP since methods are defined separately from the classes can provide more information for those interested