lecture-8

lecture-8 - in z-y ; ; 10 Example 3 let foo x = let (y,z) =...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 1 Other kinds of polymorphisms • Sub-type polymorphism void f(Shape s) – Can pass in any sub-type of Shape • Parametric polymorphism void proc_elems(list[T]) – can pass in ANY T – this is the kind in OCaml! 2 Other kinds of polymorphisms • Bounded polymorphism – Like parametric, except can provide a bound void proc_elems(list[T]) WHERE T <= Printable – Hey. .. isn’t this subtype polymorphism? – No, for example: bool ShapeEq(T a, T b) WHERE T <= Shape – Can call on (Rect, Rect) (Circle, Circle) – But not (Rect, Circle) 3 Summary of polymorphism • Subtype • Parametric • Bounded 4 Back to OCaml • Polymorphic types allow us to reuse code • However, not always obvious from staring at code • But. .. Types never entered w/ program! 5 Type inference aka: how in the world does Ocaml figure out all the types for me ??? 6 Example 1 let x = 2 + 3;; let y = string_of_int x;;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 7 Example 2 let x = 2 + 3;; let inc y = x + y;; 8 Example 2 let x = 2 + 3;; let inc y = x + y;; 9 Example 3 let foo x = let (y,z) = x
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: in z-y ; ; 10 Example 3 let foo x = let (y,z) = x in z-y ; ; 11 Example 4 let rec cat l = match l with -&gt; | h::t -&gt; h^(cat t) 12 Example 4 let rec cat l = match l with -&gt; | h::t -&gt; h^(cat t) ML doesnt know what the function does, or even that it terminates. ML only knows its type! 3 13 Example 5 let rec map f l = match l with -&gt; | h::t -&gt;(f h)::(map f t) 14 Example 5 let rec map f l = match l with -&gt; | h::t -&gt;(f h)::(map f t) 15 Inferring types with a Introduce unknown type vars Figure out equalities that must hold, and solve these equalities Remaining types vars get a forall and thus become the a, b, etc. 16 Example 6 let compose (f,g) x = f (g x) 17 Example 6 let compose (f,g) x = f (g x) 18 Example 7 let rec fold f cur l = match l with -&gt; cur | h::t -&gt; fold f (f h cur) t 4 19 Example 7 let rec fold f cur l = match l with -&gt; cur | h::t -&gt; fold f (f h cur) t...
View Full Document

This note was uploaded on 01/08/2011 for the course CSE cse130 taught by Professor Cs during the Fall '10 term at UCSD.

Page1 / 4

lecture-8 - in z-y ; ; 10 Example 3 let foo x = let (y,z) =...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online