Types S
Types S
Types
Type
· example · non--example
− int − 2
− string − "Bill"
− int -> string
− (int -> bool) -> string
· intAdd(3,4.5)
· dynamic: at run--time
· trade--off
− dynamic: overhead
(define (tx x)
(cond
((< x 10) x)
(else (car x))))
(if (very-complicated-boolean-expression)
(tx 2)
(tx 11))
example:
example:
· how? informally
function :: α α = β→γ
arg :: β exp :: γ
Rule for applications:
@ :: α β = γ→α
exp1 :: β exp2 :: γ
Example:
function :: α δ = ε→γ
γ = η→β
x :: ζ @ :: β α = ζ→β
ζ = η
@ :: γ x :: η
ε = int
δ = int → int → int
(*) :: δ 2 :: ε
γ = int → int
η = int
β = int
let f = function x -> 2*x;;
· example
β = β1 → β2
α = β2
γ = β1
can substitute
β = γ→α
α = β2
γ = β1
Type Inference: Abstraction
· function x -> e
· x has a type: β, β = α1
· e has a type: γ, γ = α2
substituting we get
α = β→γ
β = α1
γ = α2
Type Inference: Polymorphism 1
# let f = function g -> g(2);;
val f : (int -> ’a) -> ’a = <fun>
· g is used as function so β = β1 → β2
unifying we get
α = (int → β2) → β2
β = int → β2
α1 = int → β2
β1 = int
α2 = β2
Applying Polymorphic Functions
# let f g = g 2;;
val f : (int -> ’a) -> ’a = <fun>
applications
· f : ’t -> ’t =⇒
· g : ’a -> ’b -> ’a * ’b =⇒
− integer addition,
− string concatenation,
− boolean or,
· in ML:
· C++ templates
# let swap(x,y) =
let tmp = !x in x := !y; y := tmp;;
val swap : ’a ref * ’a ref -> unit = <fun>
· C++
− swap’s type
ML Overloading
· very limited in ML
− + overloaded