Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism

Size: px
Start display at page:

Download "Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism"

Transcription

1 Type Joseph Spring Discussion Languages and Type Type Checking Subtypes Type and Inheritance and 7COM1023 Programming Paradigms 1 2 Type Type denotes the kind of values that programs can manipulate: Simple types» Integers, decimal numbers, characters, Boolean values Structured types» Character strings, lists, trees, hash tables More complex types» Functions, classes 3 Very few languages do not partition the collection of data values (bit patterns) into distinct types Assembler language doesn t BCPL (Basic Combined Programming Language) didn t. developed by Martin Richards Uni of Cambridge, 1966 aka the Before C Programming Language The first brace programming language BCPL, followed by B (stripped down, syntactically modified version of BCPL became the basis for C Some languages check type safety: during the compilation stage (static) others while the program is executing. (dynamic) 4 Languages like Modula 2, Ada, Pascal, C++, C# and C are statically typed languages The languages require that a single type is bound to a variable when the variable is declared, remaining bound throughout run time Hence the type of the value of an expression is determined at compile time A language is said to be: statically typed if the types of all variables are fixed when they are declared at compile time Languages like Perl, Python and Scheme are dynamically typed languages The languages allow the type of a variable to be redefined each time a new value is assigned to it at run time To facilitate this a type indicator is stored at run time with each value A language is said to be: Dynamically typed if the type of a variable can vary at run time depending on the value assigned 5 6 1

2 A programming language is said to be strongly typed if its type system allows all type errors in a program to be detected either at compile time or run time Examples include Ada and Java C and C++ are not considered strongly typed Dynamically typed languages such as Perl and Scheme are strongly typed languages Strongly typed programming generally produces more reliable programs Is seen as a virtue in programming language design Static Type Checking Type checking means that operations or functions can only be applied to arguments of an appropriate type static means consistency is checked before the program is run. To do this all expressions, arguments to functions and, for procedural languages, variables must be given a type. 7 8 Static Type Checking Example For Example: int sum(int a[]) { int sum = 0; for(int i=0; i<a.length; i++) sum=sum+a[i]; return sum; int j, k; k = sum(j); is a compile time type error. 9 Type Inference Some languages like Haskell and SML use type inference which means the user does not need to explicitly give types for all names: parameters and functions the compiler works it out. Consider: sumlist s = if null s then 0 else (head s) + sumlist (tail s) which has type: sumlist :: Num a => [a] > a which means if a is any number type then the function sumlist takes a list of a s and returns a number. Writing code that misuses it will give a type error: (Standard ML (SML) is a general purpose, modular, functional programming language with compile time type checking and type inference) 10 Type Inference Main> sumlist 57 ERROR Cannot infer instance *** Instance : Num [a] *** Expression : sumlist 57 AND all this is done BEFORE the code is executed, ie. by the compiler 11 Dynamic Type Checking Ruby, Python, Lisp, Prolog and others do not have typed variables. Such languages have dynamic type checking. They still prevent incorrect operations on data types but check at runtime. So: (defun sumlist (l) (cond ((null l) 0) (t (+ (car l) (sumlist (cdr l)))) )) 12 2

3 Dynamic Type Checking Examples of running it: [2]> (sumlist ( )) 29 [3]> (sumlist 45) *** CAR: 45 is not a list it tried to execute and failed in the middle of the function attempting to take the head (car) of Dynamic Type Checking Advantages It provides flexibility and speed of development Disadvantages it is possible to write programs that could sometimes produce type errors but with different data might not do so: (cond ((equal x 10) (sumlist 77)) (t (sumlist (1 2 3)))) this code might execute, it might fail dynamic checking languages must have extra hidden runtime code to check values in variables before EVERY operation on them 14 Subtypes Checking with Subtypes Many languages permit some form of subtype relationship If type t 2 is a subtype of t 1 then values of type t 2 can be used where values of type t 1 are expected. Type t 1 is the parent (base or host) type of t 2 The subtype t 2 has all the characteristics of its parent type and then adds some, for example its range of values in some way restricted 15 Subtypes But all the operations of the parent type are applicable to the child type. Type checking now does not check that the types of arguments or variables are the same but rather that they are compatible ie. are subtypes of the same base type. 16 Subtyping and Inheritance Subtyping is often associated with inheritance in object oriented languages Most treat a subclass as a subtype: class Parent { public void g() { class Child extends Parent { void fun(parent o) { o.g() Child v = new Child(); fun(v); h d i l f Child 17 Subtyping and Inheritance the parameter passed is a value of Child type which is a subtype of the formal argument so it is compatible. Any operation invoked inside g on the value named by o will be defined on the value v. NB it would be illegal to allow Parent values to be used where Child values are expected because the Child class might have additional attributes that would not be present in the Parent value. 18 3

4 Subranges Another use of subtyping is subrange values used in Ada and some other languages: procedure compat is subtype sta is integer range ; subtype stb is integer range ; i: integer := 3; j : integer; s : sta := 20; t : stb := 10; begin j := s * t; end compat; 19 Subranges Which is OK, s*t is applied between compatible types, both subtypes of integer and the assignment to j is of some subtype value. However Ada also allows the use of a parent type value whenever a child value is expected, this is very odd! In the above example it is legal to assign an integer value to a subrange: s := j; if the value assigned is out of range of left hand side it produces a runtime error 20 is the simplification and generality of having one name to operate safely on values of more than one type For example +, *, apply to ints, doubles in many languages. A function to find the length of a list in Haskell can be applied to any list In 1967 Christopher Strachey identified two principal forms of polymorphism in programming languages: ad hoc polymorphism parametric polymorphism Both these forms of polymorphism are important. They are applicable in different situations 21 ad hoc polymorphism under one name different operations can be applied to different types. This is more commonly called overloading parametric polymorphism one operation can be applied to different types of value. The generic is an example of a form of parametric polymorphism Both these forms of polymorphism are important. They are applicable in different situations 22 is important: Similar operations on different types would need distinct names which would make libraries harder to use Need ad hoc polymorphism (overloading) A monomorphic type system is one where procedures or functions can be applied to only one type. This would mean code must be repeated, a collection would have to be rewritten for different value types Need parametric polymorphism (generics) is important: However dynamic type checked languages offer reuse of code on ANY type of value: (defun length (l) (cond ((null l) 0) (t (+ 1 (length (cdr l)))) )) can be applied to any type of list BUT this is at the cost of no safe compiler checks So this is what a parametric polymorphic type discipline should give: flexibility AND safety

5 Flexible Class in Python class Stack: def init (self): self.items = [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def isempty(self): return (self.items == []) def top(self): return len(self.items) def str (self): return str(self.items) stck = Stack() stck.push(5) stck.push(10) stck.push(15) sum = 0 while not stck.isempty(): sum = sum + stck.pop() print "sum of stack: ", sum 25 Monomorphic Class in Python class Stack { private int stk[]; private int topp; public Stack(){stk=new int[100]; topp= 1; public void push(int s) { stk[++topp]=s; public void pop() { if(topp>=0) topp=topp 1; public boolean empty() { return topp<0; public int top() throws Exception { if(empty()) throw new Exception("stack empty"); else return stk[topp]; 26 Monomorphic Class in Python Parametric : Generics in Java 1 public class IntStackTest { public static void main(string args[]) throws Exception { Stack lifo = new Stack(); lifo.push(20); lifo.push(30); lifo.push(40); int sum = 0; while(! lifo.empty()) { sum = sum + lifo.top() ; lifo.pop(); System.out.println("sum of stack items " + sum); 27 Consider the Stack class example: class Stack<E> { private E[] mem = (E[]) new Object[4096]; private inttopp; public Stack() { topp = 1; public boolean empty() { return topp<0; E top() { assert(! empty()); return mem[topp]; void pop() { assert(! empty()); topp ; void push(e c) { assert(! full()); topp = topp+1; mem[topp] = c; After this definition stacks can be declared 28 Parametric : Generics in Java 2 After this definition stacks can be declared, but the declarations must provide an actual type for the type parameter: Stack<Integer> istk = new Stack<Integer>(); Stack<String> sstk = new Stack<String>(); and values can be pushed: istk.push(4); istk.push(16); istk.push(24); sstk.push("yellow"); sstk.push("blue"); sstk.push("red"); Given: Parametric : Generics in Java 3 Stack<Integer> istk = new Stack<Integer>(); Stack<String> sstk = new Stack<String>(); the following is NOT allowed: istk.push("pink"); it should give a compilation error

6 Parametric in Haskell Consider the simple Haskell function: last s = if null s then error "no last element" else if null (tail s) then (head s) else last (tail s) the function does not depend on the type of the elements of the list the type is: last :: [a] > a where a is a type parameter, the type signature defines all the specific types that can be obtained by substituting any type for the letter a, eg.: [ Int ] > Int [ Float ] > Float [ [Int] ] > [Int] etc. And it is statically type safe, consider: 31 Parametric in Haskell And it is statically type safe, consider: 3 + (last (f x)).. the result of (last (f x)) should be Int because it is an argument to the operator +, the type of last is [a] >a so substituting Int for a (because that s the result) gives the argument to last as [Int] and that can be checked to make sure that s the result of (f x). 32 Parametric : Templates in C++ Parametric : Templates in C++ template <class E> class Stack { private: E mem[256]; int topp; public: Stack(void) { topp= 1; bool empty(void) { return topp<0; bool full(void) { return topp==255; E top(void) { assert(! empty()); return mem[topp]; void pop(void) { assert(! empty()); topp ; void push(e c) { assert(! full()); topp = topp+1; mem[topp] = c; ; 33 Like Java after the definition stacks can be declared, but the declarations must provide an actual type for the type parameter: Stack<int> istk; Stack<string> sstk; and values can be pushed: istk.push(4); istk.push(16); istk.push(24); sstk.push("yellow"); sstk.push("blue"); sstk.push("red"); but NOT: istk.push("pink"); that would, like Java, give a compilation error. But there is a big difference, the instantiation generates a new modified copy of the template. 34 Java before Generics Until version 1.5 Java didn t have a generic (or template) mechanism. Instead it was suggested that containers could hold values of type Object, and since every type is by definition a sub type of Object then by the rules of sub typing the container can hold values of any type. class Stack { protected Object mem[]; protected int topind; public Stack() { mem = new Object[100]; topind= 1; public boolean empty() { return topind<0; public boolean full() { return 99==topind; public Object top() { if(empty()) return null; else return mem[topind]; public void pop() { if(! empty()) topind=topind 1; public void push(object s) { if(! full()) { topind=topind+1; mem[topind]=s; 35 Java before Generics public class BadStackUse { public static void main(string args[]) { Stack filo = new Stack(); int sum = 0; filo.push(new Integer(22)); filo.push(new Integer(33)); filo.push("should be a number"); filo.push(new Integer(55)); System.out.println("Pop contents and add them up"); while(! filo.empty() ) { sum = sum + ((Integer)filo.top()).intValue(); filo.pop(); System.out.println("sum = " + sum); 36 6

7 Java before Generics Here the Stack objects can contain any type descended from Object, that includes all objects. BUT: when the values are popped off the stack they are only Objects so must be cast to the required type, allowing possible runtime errors! i.e When values are popped off the stack they are Objects (which don t all have an integer value) so they must be cast to Integer and then the int can be retrieved: sum = sum + ((Integer)filo.top()).intValue(); but other stuff, like the String above, can be accidentally pushed on the stack with no static compile time type error. this can cause a runtime type error: rabbit(340)$ java BadStackUse Pop contents and add them up java.lang.classcastexception: at BadStackUse.main(BadStackUse.java:27) 37 Overloading or ad hoc polymorphism Ad hoc polymorphism is different operations on different types but with the same name: the arithmetic operators +, *,, etc. are applicable to more than one type in explicitly programmer typed languages like Java it is simple: the compiler easily determines which instruction to use by the declared or inferred types of its operands user functions (or methods) can be overloaded : int sumsq(int a,int b) { return a*a + b*b; double sumsq(double a, double b) { return a*a + b*b; the compiler can infer which piece of code to use by the context: double x; sumsq(x,3.0) obviously use the double sumsq function 38 Inheritance and class Base { String name; public Base(String n) { name=n; public String fullname() { return "Base: "+name; class Derived extends Base { public Derived(String n) { super(n); public String fullname() { return "Derived: "+name; public class SubTypeEg01 { public static void main(string args[]) { Base b = new Base("Mummy"); Derived d = new Derived("Baby"); Random rand = new Random(System.nanoTime()); Base bb = rand.nextint(2)==1? d : b; System.out.println( bb.fullname() ); 39 Inheritance and The program defines 2 classes with a subtype relationship, the method fullname() is different in each. Because derived class objects can be used anywhere a parent class object is needed, the variable bb can refer to either type, the compiler cannot know which class of object is referred to by bb when fullname() is called: System.out.println( bb.fullname() ); the runtime system must dynamically select the appropriate version of the method, this is called dynamic binding 40 7

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 6 Robert Grimm, New York University 1 Review Last week Function Languages Lambda Calculus SCHEME review 2 Outline Promises, promises, promises Types,

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

More information

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes INF 212/CS 253 Type Systems Instructors: Harry Xu Crista Lopes What is a Data Type? A type is a collection of computational entities that share some common property Programming languages are designed to

More information

Chapter 9. Subprograms

Chapter 9. Subprograms Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling

More information

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS Type Systems Instructors: Crista Lopes Copyright Instructors. What is a Data Type? A type is a collection of computational entities that share some common property Programming

More information

Inheritance and Substitution (Budd chapter 8, 10)

Inheritance and Substitution (Budd chapter 8, 10) Inheritance and Substitution (Budd chapter 8, 10) 1 2 Plan The meaning of inheritance The syntax used to describe inheritance and overriding The idea of substitution of a child class for a parent The various

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6] 1 Lecture Overview Types 1. Type systems 2. How to think about types 3. The classification of types 4. Type equivalence structural equivalence name equivalence 5. Type compatibility 6. Type inference [Scott,

More information

Chapter 9. Subprograms

Chapter 9. Subprograms Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly

More information

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1 Object-Oriented Languages and Object-Oriented Design Ghezzi&Jazayeri: OO Languages 1 What is an OO language? In Ada and Modula 2 one can define objects encapsulate a data structure and relevant operations

More information

Some instance messages and methods

Some instance messages and methods Some instance messages and methods x ^x y ^y movedx: dx Dy: dy x

More information

Subprograms. Copyright 2015 Pearson. All rights reserved. 1-1

Subprograms. Copyright 2015 Pearson. All rights reserved. 1-1 Subprograms Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling Subprograms Indirectly

More information

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation

More information

Names, Scopes, and Bindings II. Hwansoo Han

Names, Scopes, and Bindings II. Hwansoo Han Names, Scopes, and Bindings II Hwansoo Han Scope Rules A scope is textual region where bindings are active A program section of maximal size Bindings become active at the entry No bindings change in the

More information

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result. Every program uses data, either explicitly or implicitly to arrive at a result. Data in a program is collected into data structures, and is manipulated by algorithms. Algorithms + Data Structures = Programs

More information

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc. Chapter 13 Object Oriented Programming Contents 13.1 Prelude: Abstract Data Types 13.2 The Object Model 13.4 Java 13.1 Prelude: Abstract Data Types Imperative programming paradigm Algorithms + Data Structures

More information

Types, Type Inference and Unification

Types, Type Inference and Unification Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

More information

Lecture 12 ADTs and Stacks

Lecture 12 ADTs and Stacks Lecture 12 ADTs and Stacks Modularity Divide the program into smaller parts Advantages Keeps the complexity managable Isolates errors (parts can be tested independently) Can replace parts easily Eliminates

More information

Functions and Recursion. Dr. Philip Cannata 1

Functions and Recursion. Dr. Philip Cannata 1 Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata 2 let transformation,

More information

Type Bindings. Static Type Binding

Type Bindings. Static Type Binding Type Bindings Two key issues in binding (or associating) a type to an identifier: How is type binding specified? When does the type binding take place? N. Meng, S. Arthur 1 Static Type Binding An explicit

More information

Type Checking and Type Inference

Type Checking and Type Inference Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability. Scope vs. Lifetime It is usually required that the lifetime of a run-time object at least cover the scope of the identifier. That is, whenever you can access an identifier, the run-time object it denotes

More information

The role of semantic analysis in a compiler

The role of semantic analysis in a compiler Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

Pierce Ch. 3, 8, 11, 15. Type Systems

Pierce Ch. 3, 8, 11, 15. Type Systems Pierce Ch. 3, 8, 11, 15 Type Systems Goals Define the simple language of expressions A small subset of Lisp, with minor modifications Define the type system of this language Mathematical definition using

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt

Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt Introduction to Software Testing Chapter 2.4 Graph Coverage for Design Elements Paul Ammann & Jeff Offutt www.introsoftwaretesting.com OO Software and Designs Emphasis on modularity and reuse puts complexity

More information

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy 06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 6: Polymorphic Type Systems 1. Polymorphic

More information

UNIT II Structuring the Data, Computations and Program. Kainjan Sanghavi

UNIT II Structuring the Data, Computations and Program. Kainjan Sanghavi UNIT II Structuring the Data, Computations and Program B y Kainjan Sanghavi Contents Monomorphic versus polymorphic type systems Case Study- The type structure of C++ and Java Structuring the computation

More information

C++ Programming: Introduction to C++ and OOP (Object Oriented Programming)

C++ Programming: Introduction to C++ and OOP (Object Oriented Programming) C++ Programming: Introduction to C++ and OOP (Object Oriented Programming) 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Brief introduction to C++ OOP vs. Procedural

More information

Topic 9: Type Checking

Topic 9: Type Checking Recommended Exercises and Readings Topic 9: Type Checking From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6 and

More information

Topic 9: Type Checking

Topic 9: Type Checking Topic 9: Type Checking 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

SEMANTIC ANALYSIS TYPES AND DECLARATIONS SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether

More information

Concepts of Programming Languages

Concepts of Programming Languages Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Programmiersprachen (Programming Languages)

Programmiersprachen (Programming Languages) 2016-05-13 Preface Programmiersprachen (Programming Languages) coordinates: lecturer: web: usable for: requirements: No. 185.208, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/ps.html

More information

Fundamentals of Programming Languages

Fundamentals of Programming Languages Fundamentals of Programming Languages 1. DEFINITIONS... 2 2. BUILT-IN TYPES AND PRIMITIVE TYPES... 3 TYPE COMPATIBILITY... 9 GENERIC TYPES... 14 MONOMORPHIC VERSUS POLYMORPHIC... 16 TYPE IMPLEMENTATION

More information

CMSC 4023 Chapter 9. Fundamentals of Subprograms Introduction

CMSC 4023 Chapter 9. Fundamentals of Subprograms Introduction 9. 9.1. Introduction Two fundamental abstraction facilities Process abstraction Emphasized from early days Data abstraction Emphasized in the1980s 9.2. 9.2.1. General Subprogram Characteristics Each subprogram

More information

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus Types Type checking What is a type? The notion varies from language to language Consensus A set of values A set of operations on those values Classes are one instantiation of the modern notion of type

More information

MIDTERM EXAMINATION - CS130 - Spring 2005

MIDTERM EXAMINATION - CS130 - Spring 2005 MIDTERM EAMINATION - CS130 - Spring 2005 Your full name: Your UCSD ID number: This exam is closed book and closed notes Total number of points in this exam: 231 + 25 extra credit This exam counts for 25%

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Example: Haskell algebraic data types (1)

Example: Haskell algebraic data types (1) Example: Haskell algebraic data types (1) Type declaration: data Number = Exact Int Inexact Float Set of values: Each Number value consists of a tag, together with either an Integer variant (if the tag

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts ISBN 0-321-49362-1 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language

More information

CSC 533: Organization of Programming Languages. Spring 2005

CSC 533: Organization of Programming Languages. Spring 2005 CSC 533: Organization of Programming Languages Spring 2005 Language features and issues variables & bindings data types primitive complex/structured expressions & assignments control structures subprograms

More information

TYPES, VALUES AND DECLARATIONS

TYPES, VALUES AND DECLARATIONS COSC 2P90 TYPES, VALUES AND DECLARATIONS (c) S. Thompson, M. Winters 1 Names, References, Values & Types data items have a value and a type type determines set of operations variables Have an identifier

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Programming Paradigms, Fall 06

Programming Paradigms, Fall 06 Programming Paradigms, Fall 06 Multiple Choice Exam January 29, 2007, 10:00 11:15 ID Name Each of the following questions has exactly one correct answer. For each question, you may select one or more answers

More information

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer. The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees

More information

Types. What is a type?

Types. What is a type? Types What is a type? Type checking Type conversion Aggregates: strings, arrays, structures Enumeration types Subtypes Types, CS314 Fall 01 BGRyder 1 What is a type? A set of values and the valid operations

More information

Properties of an identifier (and the object it represents) may be set at

Properties of an identifier (and the object it represents) may be set at Properties of an identifier (and the object it represents) may be set at Compile-time These are static properties as they do not change during execution. Examples include the type of a variable, the value

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

CA Compiler Construction

CA Compiler Construction CA4003 - Compiler Construction Semantic Analysis David Sinclair Semantic Actions A compiler has to do more than just recognise if a sequence of characters forms a valid sentence in the language. It must

More information

CSc 520 Principles of Programming Languages

CSc 520 Principles of Programming Languages CSc 520 Principles of Programming Languages 16 : Types Polymorphism Christian Collberg collberg+520@gmail.com Department of Computer Science University of Arizona Copyright c 2008 Christian Collberg [1]

More information

CSCE 314 Programming Languages. Type System

CSCE 314 Programming Languages. Type System CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Informatica 3 Syntax and Semantics

Informatica 3 Syntax and Semantics Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 13: Types and Type-Checking 19 Feb 07 Semantic Analysis Last time: Semantic errors related to scopes Symbol tables Name resolution This lecture:

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Abstract data types &

Abstract data types & Abstract Data Types & Object-Oriented Programming COS 301 - Programming Languages Chapters 11 & 12 in the book Slides are heavily based on Sebesta s slides for the chapters, with much left out! Abstract

More information

Abstract Data Types & Object-Oriented Programming

Abstract Data Types & Object-Oriented Programming Abstract Data Types & Object-Oriented Programming COS 301 - Programming Languages Chapters 11 & 12 in the book Slides are heavily based on Sebesta s slides for the chapters, with much left out! Abstract

More information

CS263: Runtime Systems Lecture: High-level language virtual machines

CS263: Runtime Systems Lecture: High-level language virtual machines CS263: Runtime Systems Lecture: High-level language virtual machines Today: A Review of Object-oriented features Chandra Krintz UCSB Computer Science Department Virtual machines (VMs) Terminology Aka managed

More information

Chapter 5 Names, Binding, Type Checking and Scopes

Chapter 5 Names, Binding, Type Checking and Scopes Chapter 5 Names, Binding, Type Checking and Scopes Names - We discuss all user-defined names here - Design issues for names: -Maximum length? - Are connector characters allowed? - Are names case sensitive?

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Imperative Programming

Imperative Programming Naming, scoping, binding, etc. Instructor: Dr. B. Cheng Fall 2004 1 Imperative Programming The central feature of imperative languages are variables Variables are abstractions for memory cells in a Von

More information

(Not Quite) Minijava

(Not Quite) Minijava (Not Quite) Minijava CMCS22620, Spring 2004 April 5, 2004 1 Syntax program mainclass classdecl mainclass class identifier { public static void main ( String [] identifier ) block } classdecl class identifier

More information

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target

More information

Programming Languages: Lecture 11

Programming Languages: Lecture 11 1 Programming Languages: Lecture 11 Chapter 9: Subprograms Jinwoo Kim jwkim@jjay.cuny.edu Chapter 9 Topics 2 Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments

More information

Programming Languages

Programming Languages Programming Languages Types CSCI-GA.2110-001 Summer 2011 What is a type? A type consists of a set of values The compiler/interpreter defines a mapping of these values onto the underlying hardware. 2 /

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Functions and Recursion

Functions and Recursion Programming Languages Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Jython in Java Java (Object Oriented) ACL2 (Propositional Induction) Relation Algorithmic Information

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages

More information

CSCI 3155: Principles of Programming Languages Exercise sheet #14 28 June 2007

CSCI 3155: Principles of Programming Languages Exercise sheet #14 28 June 2007 : Principles of Programming Languages Exercise sheet #14 28 June 2007 Group name: Abstract Datatypes This exercise is partially a lab exercise. You will have to use both SML and an object-oriented language

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-19: Type

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

What is an algorithm?

What is an algorithm? Announcements CS 142 Stacks & Queues Program 3 has been assigned due 10/6 by 11:55pm Program details on website 2 Creating new Data Structures We ve used objects to create new data types such as Point,

More information

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis? Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator

More information

CMSC 331 Final Exam Section 0201 December 18, 2000

CMSC 331 Final Exam Section 0201 December 18, 2000 CMSC 331 Final Exam Section 0201 December 18, 2000 Name: Student ID#: You will have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for

More information