Lecture Notes: Chapter 2 Types Lecture Notes: Chapter 2
Midterm 2011 נתונות הפרוצדורות foo ו-goo: (define foo (lambda (x) (display x) (newline) (+ x 2))) (define goo (lambda (x) (display 5) (newline) (+ x 1))) א. בחישוב של הביטוי > (foo (goo 0)) התקבל הפלט הבא על המסך: 5 1 3 מהי שיטת החישוב של האינטרפרטר? סמן בעיגול תשובה יחידה. 1. applicative order 2. normal order
Types Recall values Type is a set of values that have stuff in common Since every expression has a value, one can associate an expression with a type We can identify the type of an expression
Types: Why? Prevent nonsense computations Example: > (+ ((lambda (x) x) (lambda (x) x)) 4) +: expects type <number> as 1st argument, given: #<procedure:x>; other arguments were: 4
Well Typeness & Well Typeness Rules A set of rules that make sure the types of expression do not conflict Previous expression is not well typed
Another Example > (define x 4) > (+ 3 (if (> x 0) (+ x 1) 'non-positive)) 5 > (define x 0) > (+ 3 (if (> x 0) (+ x 1) 'non-positive)) +: expects type <number> as 2nd argument, given: "non-positive value"; other arguments were: 3 The if expression is no well typed.
Static and Dynamic Typing Static: type checking before runtime Java, C#, C++, ML Dynamic: type checking at runtime Scheme, JS, Python
Type Classification Primitive Atomic Composite Built in User cannot add new Atomic Sets of atomic values Composite Composed of others
Specification of a Type Values Value constructor Identification predicates Equality predicates Operations
Atomic Types So far: Number, Boolean, Symbol and Void Specifications: c’mone…
Composite Types So far: Procedure, Pair and List Type constructor
Procedure Types Type constructor: -> Value constructor: lambda [t1 * … * tn -> t] denotes type of all n-ary procedures [Empty -> t] type of parameter-less procedures Value constructor: lambda ID predicate: procedure? Equality predicate: none Challenge is to find the type of the procedure
Pair Types Type constructor: Pair: Value constructor: cons: Pair(t1, t2) Value constructor: cons: ID predicate: pair? Equality predicate: equal?
List Types Type constructor: Value constructor: cons, list Homogeneous: List(t) Heterogeneous: List Value constructor: cons, list ID predicate: list? Equality predicate: equal?
Type Language for Scheme We need a language to describe inferred types (and for writing contracts…) For simplicity we do not include union Tuple type: a composite type: Type constructors: *, Empty
BNF Grammar of the Type Language Type -> ’Void’ | Non-void Non-void -> Atomic | Composite | Type-variable Atomic -> ’Number’ | ’Boolean’ | ’Symbol’ Composite -> Procedure | Pair | List Procedure -> ’[’ Tuple ’->’ Type ’]’ Tuple -> (Non-void ’*’ )* Non-void | ’Empty’ Pair -> ’Pair’ ’(’ Non-void ’,’ Non-void ’)’ List -> ’List’ ’(’ Non-void ’)’ | ’List’ Type-variable -> A symbol starting with an upper case letter פרוצדורה לא יכולה לקבל Void פרוצדורה לא יכולה להחזיר Empty.