Lecture P5: Abstract Data Types Data Type

Total Page:16

File Type:pdf, Size:1020Kb

Lecture P5: Abstract Data Types Data Type Review Lecture P5: Abstract Data Types Data type: ■ Set of values and collection of operations on those values. Example: int ■ Set of values: between -32,767 and 32,767 (minimum limits). ■ Operations: +, -, *, /, %, printf("%d"), sqrt ■ How is an int represented? multiply ! 16 bits? ! negative integers? ! shouldn't care! add int print . 2 Overview "Non ADT’s" Is Complex data type an ABSTRACT data type? Separate implementation from specification. ! No: Representation in interface. ■ INTERFACE: specify the allowed operations. ! Client can directly manipulate the data type: a.re = 5.0; ■ IMPLEMENTATION: provide code for operations. ■ CLIENT: code that uses operations. client.c Abstract data type (ADT): #include "COMPLEX.h" ■ Data type whose representation is HIDDEN. int main(void) { ■ Don’t want client to directly manipulate data type. Complex a = COMPLEXinit(1.0, 2.0); ■ Operations ONLY permitted through interface. a.re = 5.0; legal C, but very bad software design Principle of least privilege. COMPLEXshow(a); return 0; } Violates "principle of least privilege." 3 6 ADT's for Stacks and Queues Stack Interface Fundamental data type. Stack operations. ■ Set of operations (insert, delete) on generic data. ■ STACKinit(): initialize empty stack ■ STACKisempty(): return 1 if stack is empty; 0 otherwise Stack ("last in first out" or LIFO). ■ STACKpush(int): insert new item ■ push: add info to the data structure ■ STACKpop(): delete and return item most recently added ■ pop: remove the info MOST recently added ■ initialize, test if empty STACK.h Queue ("first in first out" or FIFO). void STACKinit(void); ■ put: add info to the data structure int STACKisempty(void); ■ get: remove the info LEAST recently added void STACKpush(int); ■ initialize, test if empty int STACKpop(void); Could use EITHER array or "linked list" to implement EITHER stack or queue. 7 9 Stack Implementation with Arrays Stack Client: Balanced Parentheses stackarray.c Push and pop at the end of array. par.c #include "STACK.h" big #include <stdio.h> Demo: #define MAX_SIZE 1000 enough? #include "STACK.h" static int s[MAX_SIZE]; Drawback: static int N; int main(void) { int c, balanced = 1; ! Have to reserve void STACKinit(void) { STACKinit(); space for max size. N = 0; } . /* MAIN CODE HERE */ int STACKisempty(void) { if (balanced) return N == 0; printf("Balanced.\n"); } else printf("NOT Balanced.\n"); void STACKpush(int item) { s[N++] = item; return 0; } } int STACKpop(void) { Good: ( ( ( ) ( ) ) ) return s[--N]; Bad: ( ( ) ) ) ( ( ) } 11 12 Stack Client: Balanced Parentheses Stack Client: Balanced Parentheses par.c (cont) Check if your C program has unbalanced parentheses. stop loop if unbalanced Read character from stdin Unix % gcc par.c stackarray.c while (balanced && (c = getchar()) != EOF) { % a.out < myprog.c if ( c == '(' ) balanced STACKpush(c); push left parentheses else if ( c == ')' ) { % a.out < someprogram.c if (STACKisempty()) check for matching unbalanced balanced = 0; left parenthesis else How could valid C program have STACKpop(); unbalanced parentheses? } } if (!STACKisempty()) balanced if empty stack balanced = 0; when no more input Exercise: extend to handle square and curly braces. ■ Good: { ( [ ( [ ] ) ( ) ] ) } Good: ( ( ( ) ( ) ) ) ■ Bad: ( ( [ ) ] ) Bad: ( ( ) ) ) ( ( ) 13 14 Stack Client: Postfix Evaluation Stack Client: Postfix Evaluation Practical example of use of stack abstraction. Practical example of use of stack abstraction. Put operator after operands in expression. Put operator after operands in expression. ■ Use stack to evaluate. ■ Use stack to evaluate. – operand: push it onto stack. – operand: push it onto stack. – operator: pop operands, push result. – operator: pop operands, push result. ■ Systematic way to save intermediate results. ■ Systematic way to save intermediate results. Example 1. Example 2a: convert 27531 from octal to decimal. ■ 1 2 3 4 5 * + 6 * * 7 8 9 + + * + ■ 2 8 8 8 8 * * * * 7 8 8 8 * * * 5 8 8 * * 3 8 * 1 + + + + Example 2b: convert 27531 from octal to decimal. ■ 2 8 * 7 + 8 * 5 + 8 * 3 + 8 * 1 + ■ Stack never has more than two numbers on it! ■ Horner’s method (see lecture A3). 15 17 Stack Client: Postfix Evaluation Stack Client: Postfix Evaluation posfix.c Program has some flaws. Unix #include <stdio.h> ! #include <ctype.h> 2 + 5 % gcc postfix.c stackarray.c #include "STACK.h" ! 16 12 + % a.out 2 4 + int main(void) { top of stack = 6 int c; STACKinit(); % a.out while ((c = getchar()) != EOF) { 1 2 3 4 5 * + 6 * * 7 8 9 + + * if ('+' == c) top of stack = 6624 pop 2 elements STACKpush(STACKpop() + STACKpop()); and push sum else if ('*' == c) % a.out STACKpush(STACKpop() * STACKpop()); 5 9 8 + 4 6 * * 7 + * else if (isdigit(c)) convert char to top of stack = 2075 STACKpush(c - '0'); integer and push } % a.out 2 8 * 7 + 8 * 5 + 8 * 3 + 8 * 1 + printf("top of stack = %d\n", STACKpop()); top of stack = 12121 return 0; } 18 19 Stack Client: Infix to Postfix ADT Review Unix infix2postfix.c Client can access data type ONLY through interface. % gcc infix2postfix.c ... #include <stdio.h> ■ Example: STACK. % a.out #include <ctype.h> (2 + ((3 + 4) * (5 * 6))) #include "STACK.h" Representation is HIDDEN in the implementation. 2 3 4 + 5 6 * * + int main(void) { ■ Provides security. int c; Infix to postfix algorithm: STACKinit(); Convenient way to organize large problems. while ((c = getchar()) != EOF) { ■ Left paren: ignore. if (c == ')') ■ Decompose into smaller problems. ■ Right paren: pop and print. printf("%c ", STACKpop()); ■ Substitute alternate solutions (time / space tradeoffs). ■ Operator: push. else if (c == '+' || c == '*') ■ Separation compilation. ■ STACKpush(c); Digit: print. ■ Build libraries. else if (isdigit(c)) ■ Different clients can share the same ADT. printf("%c ", c); } printf("\n"); Powerful mechanism for building layers of abstraction. return 0; ■ Client works at a higher level of abstraction. } 20 21 First Class ADT First Class ADT Client: Infix infix.c So far, only 1 stack per program. STACKinit(); #include <stdio.h> . #include <ctype.h> First Class ADT: STACKpush(a); #include "STACK.h" . int main(void) { ■ ADT that is just like a built-in C type. Stack s1 = STACKinit(); s1 = stack of operatorsUnix b = STACKpop(); Stack s2 = STACKinit(); ■ Can declare multiple instances of s2 =% stack gcc ofinfix.c integers ... int c, op; them. % a.out while ((c = getchar()) != EOF) { (2 + ((3 + 4) * (5 * 6))) ■ Pass specific instances of them to if (c == ')') { interface as inputs. Stack s1, s2; op = STACKpop(s1); 212 if (op == '+') ■ Details omitted in COS 126. STACKpush(s2, STACKpop(s2) + STACKpop(s2)); (See Sedgewick 4.8 or COS 226.) s1 = STACKinit(); else if (op == '*') s2 = STACKinit(); STACKpush(s2, STACKpop(s2) * STACKpop(s2)); . } else if (c == '+' || c == '*') STACKpush(s1, a); STACKpush(s1, c); STACKpush(s2, b); else if (isdigit(c)) . STACKpush(s2, c - '0'); c = STACKpop(s2); } printf("Result = %d\n", STACKpop(s2)); return 0; } 22 23 PostScript: Abstract Stack Machine PostScript: Abstract Stack Machine Language of most printers nowadays. Some commands: ■ Postfix language. ■ Coordinate system: rotate, translate, scale, ... ■ Abstract stack machine. ■ Turtle commands: moveto, lineto, rmoveto, rlineto, ... ■ Graphics commands: stroke, fill, ... Ex: convert 27531 from octal to decimal. ■ Arithmetic: add, sub, mul, div, ... ■ 2 8 mul 7 add 8 mul 5 add 8 mul 3 add 8 mul 1 add ■ Stack commands: copy, exch, dup, currentpoint, ... ■ Control constructs: if, ifelse, while, for, ... Stack uses: ■ Define functions: /XX { ... } def ■ Operands for operators. ■ Arguments for functions. Everyone’s first PostScript program (draw a box). ■ Return value(s) for functions. %! 50 50 translate 0 0 moveto 0 512 rlineto 512 0 rlineto 0 -512 rlineto -512 0 rlineto stroke showpage 24 25 Overview Data type. ■ Set of values and collection of operations on those values. Lecture P5: Supplemental Notes ABSTRACT data type (ADT). ■ Data type whose representation is completely HIDDEN from client. Stacks and queues. ■ Fundamental ADT's. – calculators – printers and PostScript language – compiler uses to implement functions (see next lecture) 26 "Non ADT’s" Queue Interface Is Complex data type an ABSTRACT data type? Queue operations. ■ NO: Representation in interface. ■ QUEUEinit(): initialize empty queue. ■ QUEUEisempty(): return 1 if queue is empty; 0 otherwise Are C built-in types like int ADT’s? QUEUEput(int): insert new item at end of list. ■ ALMOST: we generally ignore representation. ■ QUEUEget(): return and remove item at beginning of list. ■ NO: set of values depends on representation. – might use (x & 0) to test if even QUEUE.h – works only if they’re stored as "two’s complement integers" ■ CONSEQUENCE: strive to write programs that function properly void QUEUEinit(void); independent of representation. int QUEUEisempty(void); – (x % 2 == 0) is more portable way to test if even void QUEUEput(int); – also, use <limits.h> for machine-specific ranges of int, long int QUEUEget(void); 28 29 Queue Implementation Queue Client: Josephus Problem queuearray.c queuearray.c Flavius Josephus. (first century) ■ Band of 41 Jewish rebels trapped in cave by Romans. #include "QUEUE.h" int QUEUEisempty(void) { #define MAX_SIZE 1000 return front % N == back; ■ Preferring suicide to capture, rebels formed a circled and killed } every 3rd remaining person until no one was left. static int q[MAX_SIZE]; void QUEUEput(int item) { ■ Where should you stand to be among last two survivors? static front, back; q[back++] = item; ! 31 and and 16 back = back % N; void QUEUEinit(void) { } front = N; int QUEUEget(void) { back = 0; front = front % N; } return q[front++]; } front Variable q[0] q[1] q[2] q[3] q[4] q[5] MAX_SIZE = 6 Value M D T E X A back 30 31 Queue Client: Josephus Problem josephus.c N = 8, M = 3 #include <stdio.h> #include "QUEUE.h" #define N 41 1 2 3 4 5 6 7 8 #define M 3 2 3 4 5 6 7 8 1 int main(void) { 3 4 5 6 7 8 1 2 int i; QUEUEinit(); for (i = 1; i <= N; i++) 4 5 6 7 8 1 2 QUEUEput(i); 5 6 7 8 1 2 4 while (!QUEUEisempty()) { for (i = 0; i < M - 1; i++) 6 7 8 1 2 4 5 QUEUEput(QUEUEget()); printf("%d\n", QUEUEget()); 7 8 1 2 4 5 } .
Recommended publications
  • Encapsulation and Data Abstraction
    Data abstraction l Data abstraction is the main organizing principle for building complex software systems l Without data abstraction, computing technology would stop dead in its tracks l We will study what data abstraction is and how it is supported by the programming language l The first step toward data abstraction is called encapsulation l Data abstraction is supported by language concepts such as higher-order programming, static scoping, and explicit state Encapsulation l The first step toward data abstraction, which is the basic organizing principle for large programs, is encapsulation l Assume your television set is not enclosed in a box l All the interior circuitry is exposed to the outside l It’s lighter and takes up less space, so it’s good, right? NO! l It’s dangerous for you: if you touch the circuitry, you can get an electric shock l It’s bad for the television set: if you spill a cup of coffee inside it, you can provoke a short-circuit l If you like electronics, you may be tempted to tweak the insides, to “improve” the television’s performance l So it can be a good idea to put the television in an enclosing box l A box that protects the television against damage and that only authorizes proper interaction (on/off, channel selection, volume) Encapsulation in a program l Assume your program uses a stack with the following implementation: fun {NewStack} nil end fun {Push S X} X|S end fun {Pop S X} X=S.1 S.2 end fun {IsEmpty S} S==nil end l This implementation is not encapsulated! l It has the same problems as a television set
    [Show full text]
  • 9. Abstract Data Types
    COMPUTER SCIENCE COMPUTER SCIENCE SEDGEWICK/WAYNE SEDGEWICK/WAYNE 9. Abstract Data Types •Overview 9. Abstract Data Types •Color •Image processing •String processing Section 3.1 http://introcs.cs.princeton.edu http://introcs.cs.princeton.edu Abstract data types Object-oriented programming (OOP) A data type is a set of values and a set of operations on those values. Object-oriented programming (OOP). • Create your own data types (sets of values and ops on them). An object holds a data type value. Primitive types • Use them in your programs (manipulate objects). Variable names refer to objects. • values immediately map to machine representations data type set of values examples of operations • operations immediately map to Color three 8-bit integers get red component, brighten machine instructions. Picture 2D array of colors get/set color of pixel (i, j) String sequence of characters length, substring, compare We want to write programs that process other types of data. • Colors, pictures, strings, An abstract data type is a data type whose representation is hidden from the user. • Complex numbers, vectors, matrices, • ... Impact: We can use ADTs without knowing implementation details. • This lecture: how to write client programs for several useful ADTs • Next lecture: how to implement your own ADTs An abstract data type is a data type whose representation is hidden from the user. 3 4 Sound Strings We have already been using ADTs! We have already been using ADTs! A String is a sequence of Unicode characters. defined in terms of its ADT values (typical) Java's String ADT allows us to write Java programs that manipulate strings.
    [Show full text]
  • Abstract Data Types
    Chapter 2 Abstract Data Types The second idea at the core of computer science, along with algorithms, is data. In a modern computer, data consists fundamentally of binary bits, but meaningful data is organized into primitive data types such as integer, real, and boolean and into more complex data structures such as arrays and binary trees. These data types and data structures always come along with associated operations that can be done on the data. For example, the 32-bit int data type is defined both by the fact that a value of type int consists of 32 binary bits but also by the fact that two int values can be added, subtracted, multiplied, compared, and so on. An array is defined both by the fact that it is a sequence of data items of the same basic type, but also by the fact that it is possible to directly access each of the positions in the list based on its numerical index. So the idea of a data type includes a specification of the possible values of that type together with the operations that can be performed on those values. An algorithm is an abstract idea, and a program is an implementation of an algorithm. Similarly, it is useful to be able to work with the abstract idea behind a data type or data structure, without getting bogged down in the implementation details. The abstraction in this case is called an \abstract data type." An abstract data type specifies the values of the type, but not how those values are represented as collections of bits, and it specifies operations on those values in terms of their inputs, outputs, and effects rather than as particular algorithms or program code.
    [Show full text]
  • Abstract Data Types (Adts)
    Data abstraction: Abstract Data Types (ADTs) CSE 331 University of Washington Michael Ernst Outline 1. What is an abstract data type (ADT)? 2. How to specify an ADT – immutable – mutable 3. The ADT design methodology Procedural and data abstraction Recall procedural abstraction Abstracts from the details of procedures A specification mechanism Reasoning connects implementation to specification Data abstraction (Abstract Data Type, or ADT): Abstracts from the details of data representation A specification mechanism + a way of thinking about programs and designs Next lecture: ADT implementations Representation invariants (RI), abstraction functions (AF) Why we need Abstract Data Types Organizing and manipulating data is pervasive Inventing and describing algorithms is rare Start your design by designing data structures Write code to access and manipulate data Potential problems with choosing a data structure: Decisions about data structures are made too early Duplication of effort in creating derived data Very hard to change key data structures An ADT is a set of operations ADT abstracts from the organization to meaning of data ADT abstracts from structure to use Representation does not matter; this choice is irrelevant: class RightTriangle { class RightTriangle { float base, altitude; float base, hypot, angle; } } Instead, think of a type as a set of operations create, getBase, getAltitude, getBottomAngle, ... Force clients (users) to call operations to access data Are these classes the same or different? class Point { class Point { public float x; public float r; public float y; public float theta; }} Different: can't replace one with the other Same: both classes implement the concept "2-d point" Goal of ADT methodology is to express the sameness Clients depend only on the concept "2-d point" Good because: Delay decisions Fix bugs Change algorithms (e.g., performance optimizations) Concept of 2-d point, as an ADT class Point { // A 2-d point exists somewhere in the plane, ..
    [Show full text]
  • Csci 658-01: Software Language Engineering Python 3 Reflexive
    CSci 658-01: Software Language Engineering Python 3 Reflexive Metaprogramming Chapter 3 H. Conrad Cunningham 4 May 2018 Contents 3 Decorators and Metaclasses 2 3.1 Basic Function-Level Debugging . .2 3.1.1 Motivating example . .2 3.1.2 Abstraction Principle, staying DRY . .3 3.1.3 Function decorators . .3 3.1.4 Constructing a debug decorator . .4 3.1.5 Using the debug decorator . .6 3.1.6 Case study review . .7 3.1.7 Variations . .7 3.1.7.1 Logging . .7 3.1.7.2 Optional disable . .8 3.2 Extended Function-Level Debugging . .8 3.2.1 Motivating example . .8 3.2.2 Decorators with arguments . .9 3.2.3 Prefix decorator . .9 3.2.4 Reformulated prefix decorator . 10 3.3 Class-Level Debugging . 12 3.3.1 Motivating example . 12 3.3.2 Class-level debugger . 12 3.3.3 Variation: Attribute access debugging . 14 3.4 Class Hierarchy Debugging . 16 3.4.1 Motivating example . 16 3.4.2 Review of objects and types . 17 3.4.3 Class definition process . 18 3.4.4 Changing the metaclass . 20 3.4.5 Debugging using a metaclass . 21 3.4.6 Why metaclasses? . 22 3.5 Chapter Summary . 23 1 3.6 Exercises . 23 3.7 Acknowledgements . 23 3.8 References . 24 3.9 Terms and Concepts . 24 Copyright (C) 2018, H. Conrad Cunningham Professor of Computer and Information Science University of Mississippi 211 Weir Hall P.O. Box 1848 University, MS 38677 (662) 915-5358 Note: This chapter adapts David Beazley’s debugly example presentation from his Python 3 Metaprogramming tutorial at PyCon’2013 [Beazley 2013a].
    [Show full text]
  • Metaclasses: Generative C++
    Metaclasses: Generative C++ Document Number: P0707 R3 Date: 2018-02-11 Reply-to: Herb Sutter ([email protected]) Audience: SG7, EWG Contents 1 Overview .............................................................................................................................................................2 2 Language: Metaclasses .......................................................................................................................................7 3 Library: Example metaclasses .......................................................................................................................... 18 4 Applying metaclasses: Qt moc and C++/WinRT .............................................................................................. 35 5 Alternatives for sourcedefinition transform syntax .................................................................................... 41 6 Alternatives for applying the transform .......................................................................................................... 43 7 FAQs ................................................................................................................................................................. 46 8 Revision history ............................................................................................................................................... 51 Major changes in R3: Switched to function-style declaration syntax per SG7 direction in Albuquerque (old: $class M new: constexpr void M(meta::type target,
    [Show full text]
  • Generic Programming
    Generic Programming July 21, 1998 A Dagstuhl Seminar on the topic of Generic Programming was held April 27– May 1, 1998, with forty seven participants from ten countries. During the meeting there were thirty seven lectures, a panel session, and several problem sessions. The outcomes of the meeting include • A collection of abstracts of the lectures, made publicly available via this booklet and a web site at http://www-ca.informatik.uni-tuebingen.de/dagstuhl/gpdag.html. • Plans for a proceedings volume of papers submitted after the seminar that present (possibly extended) discussions of the topics covered in the lectures, problem sessions, and the panel session. • A list of generic programming projects and open problems, which will be maintained publicly on the World Wide Web at http://www-ca.informatik.uni-tuebingen.de/people/musser/gp/pop/index.html http://www.cs.rpi.edu/˜musser/gp/pop/index.html. 1 Contents 1 Motivation 3 2 Standards Panel 4 3 Lectures 4 3.1 Foundations and Methodology Comparisons ........ 4 Fundamentals of Generic Programming.................. 4 Jim Dehnert and Alex Stepanov Automatic Program Specialization by Partial Evaluation........ 4 Robert Gl¨uck Evaluating Generic Programming in Practice............... 6 Mehdi Jazayeri Polytypic Programming........................... 6 Johan Jeuring Recasting Algorithms As Objects: AnAlternativetoIterators . 7 Murali Sitaraman Using Genericity to Improve OO Designs................. 8 Karsten Weihe Inheritance, Genericity, and Class Hierarchies.............. 8 Wolf Zimmermann 3.2 Programming Methodology ................... 9 Hierarchical Iterators and Algorithms................... 9 Matt Austern Generic Programming in C++: Matrix Case Study........... 9 Krzysztof Czarnecki Generative Programming: Beyond Generic Programming........ 10 Ulrich Eisenecker Generic Programming Using Adaptive and Aspect-Oriented Programming .
    [Show full text]
  • Java Application Programming Interface (API) Java Application Programming Interface (API) Is a List of All Classes That Are Part of the Java Development Kit (JDK)
    Java Application Programming Interface (API) Java application programming interface (API) is a list of all classes that are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, along with their methods, fields, and constructors. These prewritten classes provide a tremendous amount of functionality to a programmer. A programmer should be aware of these classes and should know how to use them. A complete listing of all classes in Java API can be found at Oracle’s website: http://docs.oracle.com/javase/7/docs/api/. Please visit the above site and bookmark it for future reference. Please consult this site often, especially when you are using a new class and would like to know more about its methods and fields. If you browse through the list of packages in the API, you will observe that there are packages written for GUI programming, networking programming, managing input and output, database programming, and many more. Please browse the complete list of packages and their descriptions to see how they can be used. In order to use a class from Java API, one needs to include an import statement at the start of the program. For example, in order to use the Scanner class, which allows a program to accept input from the keyboard, one must include the following import statement: import java.util.Scanner; The above import statement allows the programmer to use any method listed in the Scanner class. Another choice for including the import statement is the wildcard option shown below: import java.util.*; This version of the import statement imports all the classes in the API’s java.util package and makes them available to the programmer.
    [Show full text]
  • A Metaobject Protocol for Fault-Tolerant CORBA Applications
    A Metaobject Protocol for Fault-Tolerant CORBA Applications Marc-Olivier Killijian*, Jean-Charles Fabre*, Juan-Carlos Ruiz-Garcia*, Shigeru Chiba** *LAAS-CNRS, 7 Avenue du Colonel Roche **Institute of Information Science and 31077 Toulouse cedex, France Electronics, University of Tsukuba, Tennodai, Tsukuba, Ibaraki 305-8573, Japan Abstract The corner stone of a fault-tolerant reflective The use of metalevel architectures for the architecture is the MOP. We thus propose a special implementation of fault-tolerant systems is today very purpose MOP to address the problems of general-purpose appealing. Nevertheless, all such fault-tolerant systems ones. We show that compile-time reflection is a good have used a general-purpose metaobject protocol (MOP) approach for developing a specialized runtime MOP. or are based on restricted reflective features of some The definition and the implementation of an object-oriented language. According to our past appropriate runtime metaobject protocol for implementing experience, we define in this paper a suitable metaobject fault tolerance into CORBA applications is the main protocol, called FT-MOP for building fault-tolerant contribution of the work reported in this paper. This systems. We explain how to realize a specialized runtime MOP, called FT-MOP (Fault Tolerance - MetaObject MOP using compile-time reflection. This MOP is CORBA Protocol), is sufficiently general to be used for other aims compliant: it enables the execution and the state evolution (mobility, adaptability, migration, security). FT-MOP of CORBA objects to be controlled and enables the fault provides a mean to attach dynamically fault tolerance tolerance metalevel to be developed as CORBA software. strategies to CORBA objects as CORBA metaobjects, enabling thus these strategies to be implemented as 1 .
    [Show full text]
  • Variable-Arity Generic Interfaces
    Variable-Arity Generic Interfaces T. Stephen Strickland, Richard Cobbe, and Matthias Felleisen College of Computer and Information Science Northeastern University Boston, MA 02115 [email protected] Abstract. Many programming languages provide variable-arity func- tions. Such functions consume a fixed number of required arguments plus an unspecified number of \rest arguments." The C++ standardiza- tion committee has recently lifted this flexibility from terms to types with the adoption of a proposal for variable-arity templates. In this paper we propose an extension of Java with variable-arity interfaces. We present some programming examples that can benefit from variable-arity generic interfaces in Java; a type-safe model of such a language; and a reduction to the core language. 1 Introduction In April of 2007 the C++ standardization committee adopted Gregor and J¨arvi's proposal [1] for variable-length type arguments in class templates, which pre- sented the idea and its implementation but did not include a formal model or soundness proof. As a result, the relevant constructs will appear in the upcom- ing C++09 draft. Demand for this feature is not limited to C++, however. David Hall submitted a request for variable-arity type parameters for classes to Sun in 2005 [2]. For an illustration of the idea, consider the remarks on first-class functions in Scala [3] from the language's homepage. There it says that \every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying." To achieve this integration of objects and closures, Scala's standard library pre-defines ten interfaces (traits) for function types, which we show here in Java-like syntax: interface Function0<Result> { Result apply(); } interface Function1<Arg1,Result> { Result apply(Arg1 a1); } interface Function2<Arg1,Arg2,Result> { Result apply(Arg1 a1, Arg2 a2); } ..
    [Show full text]
  • On the Interaction of Object-Oriented Design Patterns and Programming
    On the Interaction of Object-Oriented Design Patterns and Programming Languages Gerald Baumgartner∗ Konstantin L¨aufer∗∗ Vincent F. Russo∗∗∗ ∗ Department of Computer and Information Science The Ohio State University 395 Dreese Lab., 2015 Neil Ave. Columbus, OH 43210–1277, USA [email protected] ∗∗ Department of Mathematical and Computer Sciences Loyola University Chicago 6525 N. Sheridan Rd. Chicago, IL 60626, USA [email protected] ∗∗∗ Lycos, Inc. 400–2 Totten Pond Rd. Waltham, MA 02154, USA [email protected] February 29, 1996 Abstract Design patterns are distilled from many real systems to catalog common programming practice. However, some object-oriented design patterns are distorted or overly complicated because of the lack of supporting programming language constructs or mechanisms. For this paper, we have analyzed several published design patterns looking for idiomatic ways of working around constraints of the implemen- tation language. From this analysis, we lay a groundwork of general-purpose language constructs and mechanisms that, if provided by a statically typed, object-oriented language, would better support the arXiv:1905.13674v1 [cs.PL] 31 May 2019 implementation of design patterns and, transitively, benefit the construction of many real systems. In particular, our catalog of language constructs includes subtyping separate from inheritance, lexically scoped closure objects independent of classes, and multimethod dispatch. The proposed constructs and mechanisms are not radically new, but rather are adopted from a variety of languages and programming language research and combined in a new, orthogonal manner. We argue that by describing design pat- terns in terms of the proposed constructs and mechanisms, pattern descriptions become simpler and, therefore, accessible to a larger number of language communities.
    [Show full text]
  • Software II: Principles of Programming Languages
    Software II: Principles of Programming Languages Lecture 6 – Data Types Some Basic Definitions • A data type defines a collection of data objects and a set of predefined operations on those objects • A descriptor is the collection of the attributes of a variable • An object represents an instance of a user- defined (abstract data) type • One design issue for all data types: What operations are defined and how are they specified? Primitive Data Types • Almost all programming languages provide a set of primitive data types • Primitive data types: Those not defined in terms of other data types • Some primitive data types are merely reflections of the hardware • Others require only a little non-hardware support for their implementation The Integer Data Type • Almost always an exact reflection of the hardware so the mapping is trivial • There may be as many as eight different integer types in a language • Java’s signed integer sizes: byte , short , int , long The Floating Point Data Type • Model real numbers, but only as approximations • Languages for scientific use support at least two floating-point types (e.g., float and double ; sometimes more • Usually exactly like the hardware, but not always • IEEE Floating-Point Standard 754 Complex Data Type • Some languages support a complex type, e.g., C99, Fortran, and Python • Each value consists of two floats, the real part and the imaginary part • Literal form real component – (in Fortran: (7, 3) imaginary – (in Python): (7 + 3j) component The Decimal Data Type • For business applications (money)
    [Show full text]