Download presentation
Presentation is loading. Please wait.
1
Lecture 4: Type Systems
2
Variables Type Most languages associate a variable with a single type
The type determines the range of values and the operations allowed for a variable In some languages (e.g., Lisp, Python, Prolog) a variable can take on values of any type. OO languages (e.g. Java) have a few primitive types (int, float, char) and everything else is a pointer to an object, but the objects form a kind of user-defined type system
3
Functions have types too
Procedures or mehtods that return a value have a type, also: the type of the value returned A type signature describes the types of each input and the type of the output power: float × integer float
4
Contrasts in Type Systems
Type systems are often described by their design decisions along several dimensions Static vs. dynamic types Strong vs. Weak typing Explicit vs. implicit type conversion Explicit vs. implicit type declarations
5
Type Binding Def: A binding is an association between a name and an attribute Def: Binding time is the time at which a binding takes place.
6
Type Binding Time Language design time, e.g., bind operator symbols to operations Language implementation time, e.g., bind floating point type to a representation Compile time, e.g., bind a variable to a type in C or Java Link time Load time, e.g., references to dlls in C/C++ Runtime, e.g., dynamic type bindings
7
Type Bindings Def: A binding is static if it occurs before run time and remains unchanged throughout program execution. Def: A binding is dynamic if it occurs during execution or can change during execution of the program. Type binding issues include: How is a type specified? When does the binding take place? If static, type may be specified by either explicit or an implicit declarations
8
Declarations Many languages require or allow the types of variables and functions to be declared Def: An explicit declaration is a program statement used for declaring the types of variables e.g., int i = 0; Def: An implicit declaration is a default mechanism for specifying types of variables (the first appearance of the variable in the program) e.g., i = 0;
9
Implicit Variable Declarations
Some examples of implicit type declarations In C undeclared variables are assumed to be of type int In Perl, variables of type scalar, array and hash begin with a or %, respectively. Fortran variables beginning with I-N are assumed to be of type integer.
10
Type Inference Types are determined from the context of the reference, rather than just by assignment statement The compiler can trace how values flow through variables and function arguments The result is that the types of most variables can be deduced! Any remaining ambiguity is treated as an error the programmer must fix by adding explicit declarations
11
Type Inferencing in ML fun circumf(r) = *r*r; // infer r is real fun time10(x) = 10*x; // infer x is integer fun square(x) = x*x; // can’t deduce types // default type is int We can explicitly type in several ways and enable the compiler to deduce that the function returns a real and takes a real argument fun square(x):real = x*x; fun square(x:real) = x*x; fun square(x) = x:real*x; fun square(x) = x*x:real;
12
Implicit Variable Declarations
Advantages and disadvantages Advantages: writability, convenience Disadvantages: reliability – requiring explicit type declarations catches bugs revealed by type mis-matches
13
Static Type Binding In a static type system, types are fixed before the program is run (e.g., compile time) Compatibility checking can be done by a compiler and errors flagged Some claim that most program errors are type errors
14
Static Type Binding The advantage is that the resulting code need not check for type mismatches at run time, which speeds up execution It typically requires adding type declarations (a pain) but these can also be seen as a kind of documentation (a benefit), note that this is only for explicit declarations
15
Dynamic Type Binding A variable’s type can change as the program runs
might be re-bound on every assignment. Used in scripting languages (Javascript, PHP, Python) and some older languages (Lisp, Basic, Prolog, APL) Here’s a javascript example list = [2, 4.33, 6, 8]; list = 17.3;
16
Dynamic Type Binding The advantages of dynamic typing include
Flexibility for the programmer Obviates the need for “polymorphic” types Development of generic functions (e.g. sort) But there are disadvantages as well Types have to be constantly checked at run time A compiler can’t detect errors via type mis-matches Mostly used by scripting languages today
17
Duck Typing A kind of dynamic typing typified by Python ad Ruby
An object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class If it walks like a duck and quacks like a duck, I would call it a duck.
18
Duck Typing example def calculate(a, b, c): return (a+b)*c a = calculate(1, 2, 3) b = calculate([1, 2, 3], [4, 5, 6], 2) c = calculate('apples','and oranges,', 3) print 'a is', a print 'b is', b print 'c is', c
19
Type Checking Type checking is the activity of ensuring that the operands of an operator are of compatible types This automatic conversion is called a coercion. A type error is the application of an operator to an operand of an inappropriate type Note: If all type bindings are static, nearly all checking can be static If type bindings are dynamic, type checking must be dynamic
20
Type Checking A compatible type is one that is either legal for the operator, or is allowed under language rules to be implicitly converted, by compiler-generated code, to a legal type. This automatic conversion is called a coercion.
21
Weak typing and coersion
Doing a lot of implicit (automatic) coersion weakens the type system Most languages do it to some degree X = 1 Y = 2.0 X + Y But overuse can cause problems Y = “2”
22
Weak typing and coercion
Doing a lot of implicit (automatic) coercion weakens the type system Most languages do it to some degree X = 1 Y = 2.0 X + Y But overuse can cause problems Y = “2” Many languages will produce the float 3.0 for X+Y X+Y is 3 in Visual Basic and “12” in javascript
23
Strong vs. Weak Typing We often categorize a programming languages into two classes: Strongly typed Weakly typed Based on their system of assigning types to variables and functions The notions of strong and weak typing do not have consensus definitions, however
24
Strong Typing Features
A programming language is strongly typed if Type errors are always detected There is strict enforcement of type rules with no exceptions. All types are known at compile time, i.e. are statically bound.
25
Strong Typing Features
A programming language is strongly typed if With variables that can store values of more than one type, incorrect type usage can be detected at run-time. Strong typing catches more errors at compile time than weak typing, resulting in fewer run-time exceptions.
26
Which languages have strong typing?
Assembly language is un-typed Fortran 77 isn’t because it doesn’t check parameters and because of variable equivalence statements. The languages Ada, Java, and Haskell are strongly typed. Pascal is (almost) strongly typed, but variant records screw it up
27
Which languages have strong typing?
C and C++ are sometimes described as strongly typed, but are perhaps better described as weakly typed because parameter type checking can be avoided and unions are not type checked Coercion rules strongly affect strong typing—they can weaken it considerably (C++ versus Ada)
28
Type Safety A programming language is type safe if the only operations that are performed on data in the language are those sanctioned by the type of the data The checking can be done at compile time or run time C/C++ is not type safe Java and Standard ML are considered type safe Haskell are type safe if you don’t use some advanced features
29
Subtyping Cell ConwayLifeCell is a subtype of Cell
Cell is a supertype of ConwayLifeCell ConwayLifeCell ≤ Cell ConwayLifeCell
30
Inheritance class B extends A B is a subtype of A B inherits from A
To implement a subtype, it is often useful to use the implementation of its supertype This is also called “subclassing” In Most OO languages: class B extends A B is a subtype of A B inherits from A class C implements F C is a subtype of F both subtyping and inheritance just subtyping
31
Inheritance Type compatibility rules: Wherever a super type value can be used, a sub type value can be used. But the opposite is not true. Examples: a = b; type of b <= type of a f(b); type of b <= parameter type of f f(){ … return b; type of b <= return type of f }
32
Method Dispatch B is a subtype of A
If both A and B have a method display which method should be called? A a = new A (); B b = new B (); a.display (); b.display (); a = b; a.display () Calls class A’s display method Calls class B’s display method Calls class B’s display method
33
Dynamic Dispatch Search for the method up the type hierarchy, starting from the actual (dynamic) type of the object apparent type a A a = new A (); B b = new B (); a.display (); b.display (); A actual type b B apparent type actual type
34
Dynamic Dispatch Search for the method up the type hierarchy, starting from the actual (dynamic) type of the object apparent type a A a = new A (); B b = new B (); a.display (); b.display (); a = b; A actual type b B apparent type actual type Now: apparent type of a is A, actual type of a is B
35
Apparent and Actual Types
Apparent types are associated with declarations: they never change Actual types are associated with object: they are always a subtype of the apparent type Compiler does type checking using apparent type Virtual Machine does method dispatch using actual type
36
Downcasting String s = (String) elements.elementAt (0);
java.util.Vector: public Object elementAt (int i); public class StringSet { Vector elements; public String choose () { String s = elements.elementAt (0); return s; } String s = (String) elements.elementAt (0); Casting changes the apparent type. The VM must check that the actual type is a subtype of the cast type.
37
A Type Hierarchy Shape Quadrangle Equilateral Triangle Parallelogram
Rhombus Rectangle What are the supertypes of Square? Square What are the subtypes of Parallelogram?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.