CS 342 Lecture -*- Outline -*- * Type polymophism (polymorphic = many forms) Abstraction of Type parameters ** makes more general abstractions e.g., sorting arrays in general (vs. arrays of ints) arrays of elements of an arbitrary type sets of elements of any type (vs. sets of ints) *** declaration modules with type parameters called generators in CLU literature ------------ sort = proc[t: type] (a: array[t], cmp: cmptype) cmptype = proctype(t,t) returns(bool) % ... end sort sort_increasing = proc[t: type] (a: array[t]) where t has lt: proctype(t,t) returns(bool) % ... end sort_increasing ------------ **** Trade-offs between requiring operations or passing as arguments issues: generality, flexibility, ease of use ** instantiation supplying the parameters sort[int] sort[string] sort_increasing[real] % have to check that there is a real$lt instantiations of parameterized procedures are procedure objects instantiations of parameterized types are types e.g., array[char] ** Type checking *** type checking instantiations **** static checks parameters must be (names of) types requirements (where clause), if any, must be met **** examples e.g., for sort above, no operations required user passes whatever operation necessary explicitly calls: sort[int](myarray, int$lt) sort[int](myarray, int$gt) sort[real](rarr, my_real_comparison) e.g., for sort_increasing, lt operation required on t calls: sort_increasing[int](myarray) sort_increasing[char](my_char_array) counter-example: sort_increasing[bool](mybools) % illegal! *** type checking for implemenations Within parameterized module (routine or cluster generator) type parameters are names of types (think of as fixed) but they are not equal to any other types! e.g., in sort, i: int x: t i := x % illegal! ** Implemenation of parameterized procedures shares code among instantiations (one copy) required operations passed at run-time