cse536 functional programming 1 6/28/2015 lecture #3, oct 4, 2004 reading assignments –finish...
Post on 21-Dec-2015
214 views
TRANSCRIPT
Cse536 Functional Programming
104/18/23
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
Cse536 Functional Programming
204/18/23
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 destructorshead 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 Auxiliaryreverse x = [4,3,2,1]
zip x y = [(1,"a"), (2,"b"), (3,"c"), (4,"d")]
Cse536 Functional Programming
304/18/23
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)), ... ]
Cse536 Functional Programming
404/18/23
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
Cse536 Functional Programming
504/18/23
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 Functionsord :: Char -> Int
chr :: Int -> Char
• Lots of interesting functions in the prelude.
Cse536 Functional Programming
604/18/23
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]
Cse536 Functional Programming
704/18/23
• 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
Computing Square Root
Cse536 Functional Programming
804/18/23
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
Cse536 Functional Programming
904/18/23
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 data declaration defines new functions and constants, which provide an abstract interface to the newly defined type.
Cse536 Functional Programming
1004/18/23
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 only elements 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
Cse536 Functional Programming
1104/18/23
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.
Cse536 Functional Programming
1204/18/23
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
Cse536 Functional Programming
1304/18/23
Patterns are not always necessary
• An alternate definition might bedayval :: 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 =
Cse536 Functional Programming
1404/18/23
Example function
dayafter d =
valday (((dayval d) + 1) `mod` 7)
? dayafter Tue
Wed
Cse536 Functional Programming
1504/18/23
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
Cse536 Functional Programming
1604/18/23
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 =
Cse536 Functional Programming
1704/18/23
Example functions on Taggernumber (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
Cse536 Functional Programming
1804/18/23
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
Cse536 Functional Programming
1904/18/23
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
Cse536 Functional Programming
2004/18/23
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)
Cse536 Functional Programming
2104/18/23
A
B
C
D
E
F
Poly = [A,B,C,D,E,F]
Area = Area(Triangle [A,B,C]) + Area(Poly[A,C,D,E,F])