220 likes | 304 Vues
Lecture #3, Oct 4, 2004. Reading Assignments Finish chapter 2 and begin Reading chapter 3 of the Text Today’s Topics Useful functions on lists The prelude functions Strings and Characters Lazy Evaluation Infinite Lists Data-Type declarations
E N D
Lecture #3, Oct 4, 2004 • Reading Assignments • Finish chapter 2 and begin Reading chapter 3 of the Text • Today’s Topics • Useful functions on lists • The prelude functions • Strings and Characters • Lazy Evaluation • Infinite Lists • Data-Type declarations • Defining functions over datatypes using patterns • Enumerations • The Shape Datatype of the text
Useful Functions on lists • Inspect the Haskell Prelude for a complete list • Let x = [1,2,3,4] y = ["a","b","c","d"] • Pair-wise destructors head x = 1 tail x = [2,3,4] init x = [1,2,3] last x = 4 take 2 x = [1,2] drop 2 x = [3,4] takeWhile odd x = [1] dropWhile odd x = [2,3,4] • Useful Auxiliary reverse x = [4,3,2,1] zip x y = [(1,"a"), (2,"b"), (3,"c"), (4,"d")]
Useful Functions on lists • Higher Order Functions • Let: x = [1,2,3,4] y = ["a","b","c","d"] • Then: map f x = [f 1, f 2, f 3, f 4] filter even x = [2,4] foldr (+) e x = 1 + (2 + (3 + (4 + e))) foldl (+) e x = (((e + 1) + 2) + 3) + 4 iterate f 1 = [1, f 1, f(f 1),f(f(f 1)), ... ]
String and Char • String is defined to be a (List Char) ? "abc" abc ? ['a', 'b', 'c'] abc • Be Careful !! Know the difference between: • "a" is a string (A List of Char with one element) • 'a' is a Char • `a` is an operator (note the back-quotes) • Since String = List Char all the list operations work on strings ? “abc” ++ “xyz” abcxyz ? reverse “abc” cba
Quotation Mechanisms • The normal (C-like) back-slash notation is used to embed special characters in String's and Char's ':' colon '\'' single quote '\"' double quote '\\' back-slash '\n' newline '\t' tab • They can also be used in String's "A two \n line string" • Conversion Functions ord :: Char -> Int chr :: Int -> Char • Lots of interesting functions in the prelude.
Lazy Evaluation(GITH pp 12-14) • Consider: repeat x = x : (repeat x) ? repeat 't' “tttttttttttttttttttttttttttttttttttttttttttttttttttttt^C{Interrupted!} • Ok to use a finite Prefix ? take 10 (repeat 't') “tttttttttt” • Remember iterate? ? take 5 (iterate (+1) 1) [1, 2, 3, 4, 5] ? take 5 (iterate (*2) 1) [1, 2, 4, 8, 16] ? take 5 (iterate (/10) 142) [142, 14, 1, 0, 0]
Computing Square Root • Approximating the square root. • Compute the n+1 approximation from the nth approximation of square root of X • an+1 = ( an+ N / an ) / 2 • The Haskell function next n a = (a + (n/a) )/ 2.0 • Example Use ? take 7 (iterate (next 2.0) 1.0) [1.0, 1.5, 1.41667, 1.41422, 1.41421, 1.41421, 1.41421] • How do we know when to stop? [1.0, 1.5, 1.41667, 1.41422, ... .5 .09 .002
Small Changes • Chop off a list when two successive elements are within some small epsilon of each other. within eps (a : b : rest) = if abs( (a/b) -1.0 ) <= eps then b else within eps (b : rest) • Now square root is easy ? within 0.0001 (iterate (next 2.0) 1.0) 1.41421
Defining New Datatypes • Ability to add new datatypes in a programming language is important. • Kinds of datatypes • enumerated types • records (or products or struct) • variant records (or sums) • pointer types • arrays • Haskell’s data declaration provides many of these kinds of types in a uniform way which abstracts from their implementation details. • The datadeclaration defines new functions and constants, which provide an abstract interface to the newly defined type.
The Data Declaration • Enumeration Types data Day = Sun | Mon | Tue | Wed | Thu | Fri | Sat deriving Eq • The names on right hand side are constructor constants and are the onlyelements of the type. valday 0 = Sun valday 1 = Mon valday 2 = Tue valday 3 = Wed valday 4 = Thu valday 5 = Fri valday 6 = Sat ? valday 3 Wed
Constructors & Patterns • data defined types define new constructors and can be accessed by patterns. • Constructors without arguments are constants • Example using case dayval x = case x of Sun -> 0 Mon -> 1 Tue -> 2 Wed -> 3 ; Thu -> 4 ; Fri -> 5 Sat -> 6 • Note: Indentation bounds each clause ( pat -> body) in case, or use a semi-colon rather than indentation.
Patterns in Declarations • In a declaration patterns can be used. Possible to have many lines for a definition if each pattern is distinct. dayval Sun = 0 dayval Mon = 1 dayval Tue = 2 dayval Wed = 3 dayval Thu = 4 dayval Fri = 5 dayval Sat = 6 ? dayval Tue 2
Patterns are not always necessary • An alternate definition might be dayval :: Day -> Int dayval x = let (d,n) = head (filter (\(d,n)->d==x) (zip [Sun,Mon,Tue,Wed,Thu,Fri,Sat] [0..])) in n • Note use of [0..] • [0..]denotes[0,1,2,3, ... ] • Why is an infinite list possible here? • Give a definition of zip using patterns over lists ([] and (x:xs) zip =
Example function dayafter d = valday (((dayval d) + 1) `mod` 7) ? dayafter Tue Wed
Other Enumeration Examples data Move = Paper | Rock | Scissors beats :: Move -> Move beats Paper = Scissors beats Rock = Paper beats Scissors = Rock ? beats Paper Scissors data Bool = True | False data Direction = North | East | South | West
Variant Records • More complicated types data Tagger = Tagn Int | Tagb Bool • NOTE: the types of the constructors are functions (not constants as for enumerated types) Tagb :: Bool -> Tagger Tagn :: Int -> Tagger • As for all constructors: (Tagn 12) • 1) Cannot be simplified. We say it is Canonical • 2) Can be used in a pattern on the left hand side of an =
Example functions on Tagger number (Tagn n) = n boolean (Tagb b) = b isNum (Tagn _) = True isNum (Tagb _) = False ? :t number number :: Tagger -> Int ? number (Tagn 3) 3 ? isNum (Tagb False) False
Another Variant Record-like Type data Temp = Celsius Float | Fahrenheit Float | Kelvin Float • Use patterns to define functions over this type: toKelvin (Celsius c) = Kelvin(c + 273.0) toKelvin (Fahrenheit f) = Kelvin( (f - 32.0) * (5.0/9.0) + 273.0 ) toKelvin (Kelvin k) = Kelvin k
Shape types from the Text data Shape = Rectangle Float Float | Ellipse Float Float | RtTriangle Float Float | Polygon [ (Float,Float) ] deriving Show • Deriving Show • tells the system to build an show function for the type Shape • Using Shape - Functions returning shape objects circle radius = Ellipse radius radius square side = Rectangle side side
Functions over Shape • Functions over shape can be defined using pattern matching area :: Shape -> Float area (Rectangle s1 s2) = s1 * s2 area (Ellipse r1 r2) = pi * r1 * r2 area (RtTriangle s1 s2) = (s1 *s2) / 2 area (Polygon (v1:pts)) = polyArea pts where polyArea :: [ (Float,Float) ] -> Float polyArea (v2 : v3 : vs) = triArea v1 v2 v3 + polyArea (v3:vs) polyArea _ = 0 Note use of prototype Note use of nested patterns Note use of wild card pattern (matches anything)
Poly = [A,B,C,D,E,F] A Area = Area(Triangle [A,B,C]) + Area(Poly[A,C,D,E,F]) B F C E D
TriArea triArea v1 v2 v3 = let a = distBetween v1 v2 b = distBetween v2 v3 c = distBetween v3 v1 s = 0.5*(a+b+c) in sqrt (s*(s-a)*(s-b)*(s-c)) distBetween (x1,y1) (x2,y2) = sqrt ((x1-x2)^2 + (y1-y2)^2)