Sergej Chodarev
Sergej Chodarev
x strcmp ( x str1, x str2 )
x pow ( x base, x exponent )
int strcmp ( const char* str1, const char* str2 )
double pow ( double base, double exponent )
A type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute.
— Benjamin C. Pierce. Types and Programming Languages. 2002
Špecifické typy namiesto všeobecných údajových štruktúr
Komplikovanejší jazyk
A program fragment is said to have good behavior, or equivalently to be well behaved, if it does not cause any forbidden error to occur.
A program that passes the typechecker is said to be well typed.
Type soundness — well-typed programs are well behaved.
— Luca Cardelli: Type Systems
List strings = new ArrayList();
strings.add("some string");
String s = strings.get(0); // error!
List strings = new ArrayList();
strings.add("some string");
String s = (String) strings.get(0);
Cat
≤ Animal
Cat[]
≤ Animal[]
Cat[] cats = new Cat[10];
Animal[] animals = cats;
animals[0] = new Duck(); // Exception!
List<Cat>
≤ List<Animal>
?
List<Animal> animals = new ArrayList<Cat>(); // error!
List<Cat>
≤ List<? extends Animal>
List<? extends Animal> animals = new ArrayList<Cat>();
…
Animal a = animals.get(0);
animals.add(new Duck()); // error!
animals.add(new Cat()); // error!
List<Animal>
≤ List<? super Cat>
List<? super Cat> cats = new ArrayList<Animal>();
...
cats.add(new Cat());
Cat cat = cats.get(0); // error!
Object cat = cats.get(0);
? extends
, ? super
)out
, in
)template <typename A>
struct ListNode {
A data;
ListNode<A>* next;
};
data Vect a =
Nil
| Cons a (Vect a)
append :: Vect a -> Vect a -> Vect a
append Nil ys = ys
append (Cons x xs) ys = Cons x (append xs ys)
data Vect : Nat -> Type -> Type where
Nil : Vect 0 a
Cons : (x : a) -> (xs : Vect n a) -> Vect (n + 1) a
append : Vect n a -> Vect m a -> Vect (n + m) a
append Nil ys = ys
append (Cons x xs) ys = Cons x (append xs ys)
G. Bracha, M. Odersky, D. Stoutamire, and P. Wadler,
“Making the future safe for the past,”
OOPSLA '98, doi: 10.1145/286936.286957