Docsity

Functional Programming Lecture Notes: Haskell Basics and Pattern Matching, Study notes of Computer Science

Partial preview of the text

Download Functional Programming Lecture Notes: Haskell Basics and Pattern Matching and more Study notes Computer Science in PDF only on Docsity!

CS 457/557 Functional Programming

Lecture 2

Haskell Basics; Data Types (Shapes)

Booleans

• Type Boolean has constructors (values) True and

False.

• Relational operators return booleans:

• Combinators on booleans:

&& || not

• Examples

Prelude> 5 > 7 False Prelude> 1== False Prelude> 5 < 7 && 1 != True

Definition By Patterns

• Example on booleans

myand True False = False myand True True = True myand False False = False myand False True = False

• The order of definition 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?

Patterns On Lists

• File Contents

hd (x:xs) = x

tl (x:xs) = xs

firstOf3 [x,y,z] = x

• Hugs Session

Main> hd [1,2,3]

Main> firstOf3 [1,2,3]

Main> firstOf3 [1,2,3,4]

Program error: {firstOf3 [1, 2, 3, 4]}

Recursion

• To obtain universal computing power, we need a way to

repeat computations

• Most languages support loops, e.g.

while b do s

• These are completely useless in a purely functional

program (why?)

• Functional programs use recursion instead of iteration.

  • Each recursive activation of function has new set of formal

parameters

  • Function can compute something different each time it is

called!

Some Recursive Functions

plus :: Int -> Int -> Int plus x y = if x == 0 then y else 1 + (plus (x-1) y) len :: [a] -> Int len [] = 0 len (x:xs) = 1 + (len xs) even, odd :: Int -> Bool even 0 = True

even n = odd(n-1)

odd 0 = False

odd n = even(n-1)

Larger example: Sorting

• Insertion sort

sort [] = []

sort (h:t) = insert h (sort t)

where

insert x [] = [x]

insert x (h:t)

| x <= h = x:h:t

| otherwise = h:(insert x t)

Types of Errors

• Syntax errors (use of symbols in unexpected places)

f x = (x*0) = x Main> :r Reading file "lect01.hs": ERROR "lect01.hs" (line 36): Syntax error in input (unexpected `=') Main>

• Undefined variables

lastone2 = head. rev Main> :r Reading script file "lect01.hs": ERROR "lect01.hs" (line 38): Undefined variable "rev" Main>

Types of Errors (cont.)

• More type errors

Prelude> :t head head :: [a] -> a Prelude> head True ERROR: Type error in application *** expression : hd True *** term : True *** type : Bool *** does not match : [a] Prelude> head 1 ERROR - Illegal Haskell 98 class constraint in inferred type *** Expression : head 1 *** Type : Num [a] => a

Overloading and Classes

• If we omitted the type contraint on difference:

difference x y = if x>=y then x-y else y-x Main> :type difference difference :: (Ord a, Num a) => a -> a -> a Main> difference 3 4

Main> difference 4.5 7. -3. Main>

The classes Ord and Num represent sets of types

Records Example: Complex Numbers

• Complex numbers in rectangular format

data Complex = Complex Float Float

deriving Eq

add (Complex r1 i1) (Complex r2 i2) =

Complex (r1+r2) (i1+i2)

mul (Complex r1 i1) (Complex r2 i2) =

Complex (r1r2-i1i2) (r1i2+r2i1)

• Note that Complex is used both to construct new

values and to patternmatch existing ones.

• Deriving clause automatically generates a structural

equality operator

(Complex 2.0 3.0 == Complex 2.0 3.0) ==> True

Enumerations Example

data Month = Jan | Feb | Mar | Apr | May | Jun |

Jul | Aug | Sep | Oct | Nov | Dec

deriving (Eq,Enum,Show)

daysInMonth Sep = 30

daysInMonth Apr = 30

daysInMonth Jun = 30

daysInMonth Nov = 30

daysInMonth Feb = 28

daysInMonth _ = 31

Main> [Jun .. Sep]

[Jun,Jul,Aug,Sep]

Maybe is another useful variant

data Maybe a = Just a

| Nothing

lookup :: a -> [(a,b)] -> Maybe b

lookup k [] = Nothing

lookup k ((k',v):rest) | k == k' = Just v

| otherwise = lookup k rest

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 a show function for the type Shape

• Using Shape Functions returning shape objects

circle radius = Ellipse radius radius

square side = Rectangle side side

• Is there anything unsatisfactory about this definition?