



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Even more powerful than the idea of recursion is the idea of abstraction—which is a lot easier to implement if you can make your own types. Your goal after this lecture is to...
Example: Complex Numbers
1 cadd (a,b) (c,d) = (a + c, b + d) 2 cmul (a,b) (c,d) = (a ∗ c - b ∗ d, 3 a ∗ d + b ∗ c)
We could use tuples to represent complex numbers, like this. (What are the types of these functions?) Why might this be a bad idea?
Record Type Definitions
data Name = Name { field :: type [, field :: type... ] }
1 data Complex = Complex { re :: Float, im :: Float } 2 3 cadd’ x y = Complex { re = re x + re y, 4 im = im x + im y }
Activity I
Simple Type Definitions
data Name = Name [type · · ·] [| Name [type · · ·] · · ·]
1 data Contest = Rock | Scissors | Paper 2 data Velocity = MetersPerSecond Float 3 | FeetPerSecond Float
Activity Write the code to take a Mylist and return a Haskell list.
Type Constructors and Memory
x = 4 -- allocates 4 n = [] -- allocates empty list n2 = n -- does NOT allocate memory l = x:n -- A cons cell is allocated, but not the 4 or the empty list
What is the memory diagram for this code?
How about this code?
x = 4 n = Nil n2 = n l = Cons x n
Example: length Write the function to take the length of a Mylist.
Now try writing Reverse. Make sure it’s O(n) time.
Parameters Haskell supports parametric polymorphism, like templates in C++ or generics in Java.
1 data Glist a = GCons a (Glist a) 2 | GNil 3 deriving Show
Activity
A very common type definition
data Maybe a = Just a | Nothing
1 2 getItem key [] = Nothing 3 getItem key ((k,v):xs) = 4 if key == k then Just v 5 else getItem key xs
*Main> getItem 3 [(2,"french hens"), (3,"turtle doves")] Just "turtle doves" *Main> getItem 5 [(2,"french hens"), (3,"turtle doves")] Nothing