Presentation is loading. Please wait.

Presentation is loading. Please wait.

PROGRAMMING IN HASKELL

Similar presentations


Presentation on theme: "PROGRAMMING IN HASKELL"— Presentation transcript:

1 PROGRAMMING IN HASKELL
Type declarations and Modules Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)

2 Sections An operator written between its two arguments can be converted into a curried function written before its two arguments by using parentheses. For example: > 1+2 3 > (+) 1 2

3 This convention also allows one of the arguments of the operator to be included in the parentheses.
For example: > (1+) 2 3 > (+2) 1 In general, if  is an operator then functions of the form (), (x) and (y) are called sections.

4 Why Are Sections Useful?
Useful functions can sometimes be constructed in a simple way using sections. For example: - successor function - reciprocation function - doubling function - halving function (1+) (*2) (/2) (1/)

5 Exercise Consider a function safetail that behaves in the same way as tail, except that safetail maps the empty list to the empty list, whereas tail gives an error in this case. Define safetail using: (a) a conditional expression; (b) guarded equations; (c) pattern matching. Hint: the library function null :: [a]  Bool can be used to test if a list is empty.

6 Higher order functions
Last time we started discussing higher order functions, or functions that take other functions are input. These are heavily useful, and are one of the strengths of Haskell! Let’s recap and then see a few more…

7 Higher order functions
Last time: Map: take something and apply it to everything in a list ghci> map (+3) [1,5,3,1,6] [4,8,6,4,9] ghci> map (++ "!") ["BIFF", "BANG", "POW"] ["BIFF!","BANG!","POW!"] ghci> map (replicate 3) [3..6] [[3,3,3],[4,4,4],[5,5,5],[6,6,6]] ghci> map (map (^2)) [[1,2],[3,4,5,6],[7,8]] [[1,4],[9,16,25,36],[49,64]]

8 The Foldr Function A number of functions on lists can be defined using the following simple pattern of recursion: f [] = v f (x:xs) = x  f xs f maps the empty list to some value v, and any non-empty list to some function  applied to its head and f of its tail.

9 v = 0 v = 1 v = True For example: sum [] = 0 sum (x:xs) = x + sum xs
 = + product [] = 1 product (x:xs) = x * product xs v = 1  = * and [] = True and (x:xs) = x && and xs v = True  = &&

10 The higher-order library function foldr (fold right) encapsulates this simple pattern of recursion, with the function  and the value v as arguments. For example: sum = foldr (+) 0 product = foldr (*) 1 or = foldr (||) False and = foldr (&&) True

11 Foldr itself can be defined using recursion:
foldr :: (a  b  b)  b  [a]  b foldr f v [] = v foldr f v (x:xs) = f x (foldr f v xs) However, it is best to think of foldr non-recursively, as simultaneously replacing each (:) in a list by a given function, and [] by a given value.

12 For example: = = = = Replace each (:) by (+) and [] by 0. sum [1,2,3]
foldr (+) 0 [1,2,3] = foldr (+) 0 (1:(2:(3:[]))) = 1+(2+(3+0)) = 6 = Replace each (:) by (+) and [] by 0.

13 For example: = = = = Replace each (:) by (*) and [] by 1.
product [1,2,3] foldr (*) 1 [1,2,3] = foldr (*) 1 (1:(2:(3:[]))) = 1*(2*(3*1)) = 6 = Replace each (:) by (*) and [] by 1.

14 Other Foldr Examples Even though foldr encapsulates a simple pattern of recursion, it can be used to define many more functions than might first be expected. Recall the length function: length :: [a]  Int length [] = 0 length (_:xs) = 1 + length xs

15 Replace each (:) by _ n  1+n and [] by 0.
For example: length [1,2,3] length (1:(2:(3:[]))) = 1+(1+(1+0)) = 3 = Replace each (:) by _ n  1+n and [] by 0. Hence, we have: length = foldr (_ n  1+n) 0

16 Replace each (:) by x xs  xs ++ [x] and [] by [].
Now recall the reverse function: reverse [] = [] reverse (x:xs) = reverse xs ++ [x] For example: Replace each (:) by x xs  xs ++ [x] and [] by []. reverse [1,2,3] reverse (1:(2:(3:[]))) = (([] ++ [3]) ++ [2]) ++ [1] = [3,2,1] =

17 Replace each (:) by (:) and [] by ys.
Hence, we have: reverse = foldr (x xs  xs ++ [x]) [] Finally, we note that the append function (++) has a particularly compact definition using foldr: Replace each (:) by (:) and [] by ys. (++ ys) = foldr (:) ys

18 Why Is Foldr Useful? Some recursive functions on lists, such as sum, are simpler to define using foldr. Properties of functions defined using foldr can be proved using algebraic properties of foldr, such as fusion and the banana split rule. Advanced program optimizations can be simpler if foldr is used in place of explicit recursion.

19 Other Library Functions
The library function (.) returns the composition of two functions as a single function. (.) :: (b  c)  (a  b)  (a  c) f . g = x  f (g x) For example: odd :: Int  Bool odd = not . even

20 The library function all decides if every element of a list satisfies a given predicate.
all :: (a  Bool)  [a]  Bool all p xs = and [p x | x  xs] For example: > all even [2,4,6,8,10] True

21 Dually, the library function any decides if at least
one element of a list satisfies a predicate. any :: (a  Bool)  [a]  Bool any p xs = or [p x | x  xs] For example: > any isSpace "abc def" True

22 The library function takeWhile selects elements from a list while a predicate holds of all the elements. takeWhile :: (a  Bool)  [a]  [a] takeWhile p [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] For example: > takeWhile isAlpha "abc def" "abc"

23 Dually, the function dropWhile removes elements while a predicate holds of all the elements.
dropWhile :: (a  Bool)  [a]  [a] dropWhile p [] = [] dropWhile p (x:xs) | p x = dropWhile p xs | otherwise = x:xs For example: > dropWhile isSpace " abc" "abc"

24 String is a synonym for the type [Char].
Type Declarations In Haskell, a new name for an existing type can be defined using a type declaration. type String = [Char] String is a synonym for the type [Char].

25 Type declarations can be used to make other types easier to read
Type declarations can be used to make other types easier to read. For example, given type Pos = (Int,Int) we can define: origin :: Pos origin = (0,0) left :: Pos  Pos left (x,y) = (x-1,y)

26 Like function definitions, type declarations can also have parameters
Like function definitions, type declarations can also have parameters. For example, given type Pair a = (a,a) we can define: mult :: Pair Int  Int mult (m,n) = m*n copy :: a  Pair a copy x = (x,x)

27 Type declarations can be nested:
type Pos = (Int,Int) type Trans = Pos  Pos However, they cannot be recursive: type Tree = (Int,[Tree])

28 Bool is a new type, with two new values False and True.
Data Declarations A completely new type can be defined by specifying its values using a data declaration. data Bool = False | True Bool is a new type, with two new values False and True.

29 Note: The two values False and True are called the constructors for the type Bool. Type and constructor names must begin with an upper-case letter. Data declarations are similar to context free grammars. The former specifies the values of a type, the latter the sentences of a language.

30 Values of new types can be used in the same ways as those of built in types. For example, given
data Answer = Yes | No | Unknown we can define: answers :: [Answer] answers = [Yes,No,Unknown] flip :: Answer  Answer flip Yes = No flip No = Yes flip Unknown = Unknown

31 The constructors in a data declaration can also have parameters
The constructors in a data declaration can also have parameters. For example, given data Shape = Circle Float | Rect Float Float we can define: square :: Float  Shape square n = Rect n n area :: Shape  Float area (Circle r) = pi * r^2 area (Rect x y) = x * y

32 Note: Shape has values of the form Circle r where r is a float, and Rect x y where x and y are floats. Circle and Rect can be viewed as functions that construct values of type Shape: Circle :: Float  Shape Rect :: Float  Float  Shape

33 Not surprisingly, data declarations themselves can also have parameters. For example, given
data Maybe a = Nothing | Just a we can define: safediv :: Int  Int  Maybe Int safediv _ 0 = Nothing safediv m n = Just (m `div` n) safehead :: [a]  Maybe a safehead [] = Nothing safehead xs = Just (head xs)

34 Exercises: FIX – no show
Write a function safeSecond which takes a list and returns its second element (assuming it has one). Note: you’ll need the following: data Maybe a = Nothing | Just a safehead :: [a]  Maybe a safehead [] = Nothing safehead xs = Just (head xs)

35 Recursive Types In Haskell, new types can be declared in terms of themselves. That is, types can be recursive. data Nat = Zero | Succ Nat Nat is a new type, with constructors Zero :: Nat and Succ :: Nat  Nat.

36 Note: A value of type Nat is either Zero, or of the form Succ n where n :: Nat. That is, Nat contains the following infinite sequence of values: Zero Succ Zero Succ (Succ Zero)

37 represents the natural number
We can think of values of type Nat as natural numbers, where Zero represents 0, and Succ represents the successor function 1+. For example, the value Succ (Succ (Succ Zero)) represents the natural number 1 + (1 + (1 + 0)) 3 =

38 Using recursion, it is easy to define functions that convert between values of type Nat and Int:
nat2int :: Nat  Int nat2int Zero = 0 nat2int (Succ n) = 1 + nat2int n int2nat :: Int  Nat int2nat = Zero int2nat (n+1) = Succ (int2nat n)

39 Two naturals can be added by converting them to integers, adding, and then converting back:
add :: Nat  Nat  Nat add m n = int2nat (nat2int m + nat2int n) However, using recursion the function add can be defined without the need for conversions: add Zero n = n add (Succ m) n = Succ (add m n)

40 For example: add (Succ (Succ Zero)) (Succ Zero) Succ (add (Succ Zero) (Succ Zero)) = Succ (Succ (add Zero (Succ Zero)) = Succ (Succ (Succ Zero)) = Note: The recursive definition for add corresponds to the laws 0+n = n and (1+m)+n = 1+(m+n).

41 Arithmetic Expressions
Consider a simple form of expressions built up from integers using addition and multiplication. 1 + 3 2

42 Using recursion, a suitable new type to represent such expressions can be declared by:
data Expr = Val Int | Add Expr Expr | Mul Expr Expr For example, the expression on the previous slide would be represented as follows: Add (Val 1) (Mul (Val 2) (Val 3))

43 Using recursion, it is now easy to define functions that process expressions. For example:
size :: Expr  Int size (Val n) = 1 size (Add x y) = size x + size y size (Mul x y) = size x + size y eval :: Expr  Int eval (Val n) = n eval (Add x y) = eval x + eval y eval (Mul x y) = eval x * eval y

44 The three constructors have types:
Note: The three constructors have types: Val :: Int  Expr Add :: Expr  Expr  Expr Mul :: Expr  Expr  Expr Many functions on expressions can be defined by replacing the constructors by other functions using a suitable fold function. For example: eval = fold id (+) (*)

45 Binary Trees In computing, it is often useful to store data in a two-way branching structure or binary tree. 5 7 9 6 3 4 1

46 Using recursion, a suitable new type to represent such binary trees can be declared by:
data Tree = Leaf Int | Node Tree Int Tree For example, the tree on the previous slide would be represented as follows: Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9))

47 We can now define a function that decides if a given integer occurs in a binary tree:
occurs :: Int  Tree  Bool occurs m (Leaf n) = m==n occurs m (Node l n r) = m==n || occurs m l || occurs m r But… in the worst case, when the integer does not occur, this function traverses the entire tree.

48 Now consider the function flatten that returns the list of all the integers contained in a tree:
flatten :: Tree  [Int] flatten (Leaf n) = [n] flatten (Node l n r) = flatten l ++ [n] ++ flatten r A tree is a search tree if it flattens to a list that is ordered. Our example tree is a search tree, as it flattens to the ordered list [1,3,4,5,6,7,9].

49 Search trees have the important property that when trying to find a value in a tree we can always decide which of the two sub-trees it may occur in: occurs m (Leaf n) = m==n occurs m (Node l n r) | m==n = True | m<n = occurs m l | m>n = occurs m r This new definition is more efficient, because it only traverses one path down the tree.

50 Exercise Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9)) A binary tree is complete if the two sub-trees of every node are of equal size. Define a function that decides if a binary tree is complete. data Tree = Leaf Int | Node Tree Int Tree occurs :: Int  Tree  Bool occurs m (Leaf n) = m==n occurs m (Node l n r) = m==n || occurs m l || occurs m r


Download ppt "PROGRAMMING IN HASKELL"

Similar presentations


Ads by Google