250 likes | 329 Views
Lecture #2, Sept 29, 2004. Reading Assignments Begin Chapter 2 of the Text Home work #1 can be found on the webpage, under the assignments link, and as an extra handout, given out in class today Today’s Topics Definition by cases Definition by patterns Local definitions
E N D
Lecture #2, Sept 29, 2004 • Reading Assignments • Begin Chapter 2 of the Text • Home work #1 can be found on the webpage, under the assignments link, and as an extra handout, given out in class today • Today’s Topics • Definition by cases • Definition by patterns • Local definitions • Function types and prototyping • Overloaded functions • Ways to make functions • Tuples • Polymorphism • Operators as functions • Functions as Arguments • Functions returned as values
Definition by Cases absolute x | x < 0 = -x | x >= 0 = x ? absolute 3 3 (6 reductions, 13 cells) ? absolute (- 5) 5 (9 reductions, 13 cells) ?
Definition By Patterns Pattern may contain constructors constructors are always capitalized • Example on Booleans myand True False = False myand True True = True myand False False = False myand False True = False • Order Matters • Variables in Patterns match anything myand2 True True = True myand2 x y = False • What happens if we reverse the order of the two equations above?
File Contents hd (x:xs) = x tl (x:xs) = xs firstOf3 [x,y,z] = x Hugs Session ? hd [1,2,3] 1 ? firstOf3 [1,2,3] 1 ? firstOf3 [1,2,3,4] Program error: {firstOf3 [1, 2, 3, 4]} Patterns On lists
Rules for Patterns • All the patterns (on the left) should have compatible types • The cases should (but are not required to) be exhaustive • There should be no ambiguity as to which case applies. • Ordering fixes ambiguity if there is any. • A Pattern is: • A variable x • A constructor applied to patterns x:xs or Branch(x,y,z) • A constant 3 or [] • A tuple of patterns (x,3,y:ys)
Recursive Functions & Comments • File Contents plus x y = if x == 0 then y else 1 + (plus (x-1) y) len [] = 0 len (x:xs) = 1 + (len xs) • Hugs session ? plus 3 5 8 ? len [1,2,3,4] 4
Comments -- A comment to the end of the line {- This is a comment to the next -} {- Nesting of {- -} pairs allowed -}
Local Definitions • Local Definitions: Where len2 [] = 0 len2 (x:xs) = one + z where z = len2 xs one = 1 • Indentation matters ! Same sequence of tokens but different meaning where a = f x y -- y is a variable used as b = g z -- an arg to function f where a = f x y b = g z -- y is the name of fun -- being defined • Location of <newline> makes a big difference • RULE of thumb Definitions at the same scope should be indented equally far.
Function Types & Prototyping • Typing f a b c = a + b + c + 1 has type f :: Int -> Int -> Int -> Int Read as f:: Int -> (Int -> (Int -> Int)) • Prototyping plus :: Int -> Int -> Int plus x y = if x == 0 then y else 1 + (plus (x-1) y) myand :: Bool -> Bool -> Bool myand True False = False myand True True = True myand False False = False myand False True = False
Overloading and Classes ? :type difference difference:: Num a => a -> a -> a ? difference 3 4 -1 ? difference 4.5 7.8 -3.3 ? The class Num is a predicate on types
Ways to Create Functions • By defining: plusone x = x+1 ? plusone 3 4 • By operator section ? (3+) 5 8 ? map (3+) [2,3,4] [5, 6, 7] • By lambda expression ? (\ x -> x+2) 5 7 ? map (\x -> x*2) [2,3,4] [4, 6, 8]
Creating Functions (cont.) • By currying (partial application) ? plus 3 plus 3 ? :type (plus 3) plus 3 :: Int -> Int ? map (plus 3) [3,4] [6, 7] • By composition ? map (head . tail) [[2,3,4],[4,5,6]] [3, 5] • By combinator: k x y = x • Functions which return functions ? map (k 3) [1,2,3] [3, 3, 3]
Expressions, Values, and Types • There are three types of distinguished entities in Haskell • Expressions • 5 + 3 • len [1,2,3] • rev [2,9] • len • Values • 8 • 3 • [9,2] • <<function>> • Types • Int • Int • [ Int ] • [ a ] -> Int
Tuples • Heterogeneous Collection of a fixed width • Tuple Expressions • (5+3, not True) • (tl [1,2,3], [2]++[3,4], “abc”) • Evaluate to Tuple Values • (8, False) • ([2,3], [2,3,4], “abc”) • And have Tuple Types • (Int, Bool) • ([Int], [Int], String)
Typing Tuples ? :type (1,"x",True) (1,"x",True)::(Int,String,Bool) ? :type (1,2) (1,2) :: (Int,Int) ? :type (2,("x",3)) (2,("x",3))::(Int,(String,Int)) • Note: (Int,([Char],Int)) <> (Int,[Char],Int) • Pattern matching on tuples ? (\ (a,b) -> a) (2,3) 2 ? (\ (a,b) -> b + 2) (2,3) 5
Used when returning multiple values • Function that splits a list into two pieces at some particular position split 2 [1,2,3,4] --> ([1,2],[3,4]) split 3 [1,2,3,4,5,6,7] ---> ([1, 2, 3],[4, 5, 6, 7]) split 0 [1,2,3] --> ([],[1,2,3]) split 0 x = ([],x) split n [] = ([],[]) split n (x:xs) = (x:ys,zs) where (ys,zs) = split (n-1) xs
Polymorphism (FN pp 16, GITH pp3-5) • Consider: tag1 x = (1,x) ? :type tag1 tag1 :: a -> (Int,a) • Other functions have types like this consider (++) ? :type (++) (++) :: [a] -> [a] -> [a] ? :type ([1,2]++) ([1,2] ++) :: [Int] -> [Int] • What are some other polymorphic functions and their types? • id :: • reverse :: • head :: • tail :: • (:) :: • split ::
Operators as functions (FN pp 6-8 & 21 GITH pp 11-12) ? :type (:) (:) :: a -> [a] -> [a] ? :type (++) (++) :: [a] -> [a] -> [a] ? :type (+) (+) :: Num a => a -> a -> a • Operator Precedence • level 9 . !! • level 8 ^ • level 7 * / `div` `rem` `mod` • level 6 + - • level 5 : ++ \\ • level 4 == /= < <= > >= `elem` • level 3 && • level 2 || • level 1 (not used in the prelude)
Associativity(FN pp 22-23) • Right • 2 : 3 : 4 : [] = 2 : (3 : (4 : [])) • Other Right Associative operators (:) (^) (++) (&&) (||) • Left • 7 - 6 - 2 = (7 - 6) - 2 • Other Left Associative operators (!!) (-) (*) (+) • Non-associative • (<) (>) ... (i.e. all the relational operators)
Defining one’s own operators(FN pp 23) infix 4 `inlist` infix 3 -&- x `inlist` [] = False x `inlist` (y:ys) = if x==y then True else x `inlist` ys ? 3 `inlist` [1,2,4] False ? 3 `inlist` [1,2,3,5] True
Functions as arguments(FN pp 25-28) • Consider: mymap f [] = [] mymap f (x:xs) = (f x):(mymap f xs) • The parameter f is a function! • What is the type of mymap ? mymap :: (a -> b) -> [a] -> [b] • What happens when it is applied? map add1 map ( \ x -> 3) [1,2,3]
When do you define a higher order function? • Abstraction is the key mysum [] = 0 mysum (x:xs) = (+)x (mysum xs) myprod [] = 1 myprod (x:xs) = (*)x (myprod xs) myand [] = True myand (x:xs) = (&&)x (myand xs) • Note the similarities in definition and in use ? mysum [1,2,3] 6 ? myprod [2,3,4] 24 ? myand [True, False] False
Abstracting myfoldr ope [] = e myfoldr ope (x:xs) = op x (myfoldr op e xs) ? :t myfoldr myfoldr :: (a -> b -> b) -> b -> [a] -> b ? myfoldr (+) 0 [1,2,3] 6 ?
Functions returned as values • Consider: k x = (\ y -> x) ? (k 3) 5 3 • Another Example: plusn n = (\ x -> x + n) ? (plusn 4) 5 9 • Is plusn different from plus? why? • plus x y = x + y
Additional Examples The webpage includes a link (in the lecture notes section, under today’s date, Sept. 29, 2004) to some additional examaples • Numerical Functions • Differentiation and square root. pp 30-32 Fokker Notes • Primes. pp 29 Fokker Notes • Display Tool. pp 105 Reade Book • Numbers in Long Hand • Sorting. pp 106-109 Reade Book • Making Change. Bird & Wadler