# PROGRAMMING IN HASKELL - PowerPoint PPT Presentation Download Presentation PROGRAMMING IN HASKELL

PROGRAMMING IN HASKELL Download Presentation ## PROGRAMMING IN HASKELL

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. PROGRAMMING IN HASKELL Author: Prof Graham Hutton Functional Programming Lab School of Computer Science University of Nottingham, UK (Used with Permission)

2. The > prompt means that the system is ready to evaluate an expression. For example: > 2+3*4 14 > (2+3)*4 20 > sqrt (3^2 + 4^2) 5.0

3. The Standard Prelude The library file Prelude.hs provides a large number of standard functions. In addition to the familiar numeric functions such as + and *, the library also provides many useful functions on lists. • Because of the predefinitions, GHCi may complain if you try to redefine something it already has a definition for. • Select the first element of a list: • Single line comments are preceded by ``--'' and continue to the end of the line. > head [1,2,3,4,5] 1

4. Remove the first element from a list: > tail [1,2,3,4,5] [2,3,4,5] • Select the nth element of a list: > [1,2,3,4,5] !! 2 3 • Select the first n elements of a list: > take 3 [1,2,3,4,5] [1,2,3]

5. Remove the first n elements from a list: > drop 3 [1,2,3,4,5] [4,5] • Calculate the length of a list: > length [1,2,3,4,5] 5 • Calculate the sum of a list of numbers: > sum [1,2,3,4,5] 15

6. Calculate the product of a list of numbers: > product [1,2,3,4,5] 120 • Append two lists: > [1,2,3] ++ [4,5] [1,2,3,4,5] • Reverse a list: > reverse [1,2,3,4,5] [5,4,3,2,1]

7. Mathematics Haskell f x f(x) f x y f(x,y) f (g x) f(g(x)) f x (g y) f(x,g(y)) f(x)g(y) f x * g y Examples

8. Haskell Scripts • As well as the functions in the standard prelude, you can also define your own functions; • New functions are defined within a script, a text file comprising a sequence of definitions; • By convention, Haskell scripts usually have a .hs suffix on their filename. This is not mandatory, but is useful for identification purposes.

9. My First Script When developing a Haskell script, it is useful to keep two windows open, one running an editor for the script, and the other running GHCi. Start an editor, type in the following two function definitions, and save the script as test.hs: double x = x + x quadruple x = double (double x)

10. Leaving the editor open, click on the file to open ghci using that file: Now both Prelude.hs and test.hs are loaded, and functions from both scripts can be used: > quadruple 10 40 > take (double 2) [1,2,3,4,5,6] [1,2,3,4]

11. Leaving GHCi open, return to the editor, add the following two definitions, and resave. From within GHCi, enter :r (to reload the changed file) factorial n = product [1..n] average ns = sum ns `div` length ns Note: • These functions are defined via an equation • div is enclosed in back quotes, not forward; • x `f` y is just syntactic sugar for f x y.

12. GHCi does not automatically detect that the script has been changed, so a reload command must be executed before the new definitions can be used: > :r Reading file "test.hs" > factorial 10 3628800 > average [1,2,3,4,5] 3

13. xs ns nss Naming Requirements • Function and argument names must begin with a lower-case letter. For example: myFun fun1 arg_2 x’ • By convention, list arguments usually have an s suffix on their name. For example:

14. a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 The Layout Rule In a sequence of definitions, each definition must begin in precisely the same column:

15. means The layout rule avoids the need for explicit syntax to indicate the grouping of definitions. We can introduce local variables on the right hand side via a “where” clause. a = b + c where b = 1 c = 2 d = a * 2 a = b + c where {b = 1; c = 2} d = a * 2 implicit grouping explicit grouping

16. Useful Commands in GHCi CommandMeaning :load name load script name :reload reload current script :edit name edit script name :edit edit current script :type expr show type of expr :? show all commands :quit quit

17. Exercises (1) (2) Try out the examples of this lecture Fix the syntax errors in the program below, and test your solution. N = a ’div’ length xs where a = 10 xs = [1,2,3,4,5]

18. (3) Show how the library function last that selects the last element of a list can be defined using the functions introduced in this lecture. (4) Can you think of another possible definition for last? (5) Similarly, show how the library function init that removes the last element from a list can be defined in two different ways.

19. PROGRAMMING IN HASKELL Types and Classes

20. False True What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values:

21. Algebraic types • there are still things we are missing such as • The types for the months January… December. • The type whose elements are either a number or a string.  (a house will either have a number or name, say) • A type of tree. • All of these can be modeled as algebraic types.

22. The simplest form of an algebraic type is an enumerated type. data Season = Spring | Summer | Fall | Winter data Weather = Rainy | Hot | Cold data Color = Red | Blue| Green|Yellow deriving (Show,Eq,Ord) data Ordering = LT|EQ|GT  --  built into the Ordering Class  A more complicated algebraic type (the product type) allows for the type constructor to have types associated with it. data Student = USU String  Int data Address = None | Addr String data Age = Years Int data Shape = Circle Float | Rectangle Float Float data Tree a = Branch (Tree a) (Tree a) | Leaf a data Point a = Pt a a Thus, Student is formed from a String (call it st) and an Int (call it x) and the element Student formed from them will be recognized as USU st x

23. The general form of the algebraic type is • data TypeName •    = Con1 T11 .. T1n | •       Con2 T21..T2m | Each Coni is a constructor which may be followed by zero or more types.  We build elements of TypeName by applying this constsructor functions to arguments.

24. Algebraic types can also be recursive data Expr = Lit Int | Add Expr Expr | Sub Expr Expr data Tree = Nil | Node Int Tree Tree printBST:: Tree -> [Int] printBST Nil = [] printBST (Node x left right) = (printBST left) ++ [x]++ (printBST right) main> printBST (Node 5 (Node 3 Nil Nil) Nil) [3,5]

25. Type Errors Applying a function to one or more arguments of the wrong type is called a type error. > 1 + False Error 1 is a number and False is a logical value, but + requires two numbers.

26. Types in Haskell • If evaluating an expression e would produce a value of type t, then e has type t, written e :: t • Every well formed expression has a type, which can be automatically calculated at compile time using a process called type inference.

27. All type errors are found at compile time, which makes programs safer and faster by removing the need for type checks at run time. • In GHCi, the :type command calculates the type of an expression, without evaluating it: > not False True > :type not False not False :: Bool

28. - logical values Bool - single characters Char - strings of characters String - fixed-precision integers Int - arbitrary-precision integers Integer - floating-point numbers Float Basic Types Haskell has a number of basic types, including:

29. List Types A list is sequence of values of the same type: [False,True,False] :: [Bool] [’a’,’b’,’c’,’d’] :: [Char] In general: [t] is the type of lists with elements of type t.

30. Note: • The type of a list says nothing about its length: [False,True] :: [Bool] [False,True,False] :: [Bool] • The type of the elements is unrestricted. For example, we can have lists of lists: [[’a’],[’b’,’c’]] :: [[Char]]

31. Tuple Types (like a struct or record) A tuple is a sequence of values of different types: (False,True) :: (Bool,Bool) (False,’a’,True) :: (Bool,Char,Bool) In general: (t1,t2,…,tn) is the type of n-tuples whose ith components have type ti for any i in 1…n.

32. Note: • The type of a tuple shows its size: (False,True) :: (Bool,Bool) (False,True,False) :: (Bool,Bool,Bool) • The type of the components is unrestricted: (’a’,(False,’b’)) :: (Char,(Bool,Char)) (True,[’a’,’b’]) :: (Bool,[Char])

33. Function Types A function is a mapping from values of one type to values of another type: not :: Bool  Bool isDigit :: Char  Bool In general: t1  t2 is the type of functions that map values of type t1 to values to type t2.

34. Note: • The arrow  is typed at the keyboard as ->. • The argument and result types are unrestricted. For example, functions with multiple arguments or results are possible using lists or tuples: addPair:: (Int,Int) Int addPair(x,y) = x+y zeroto :: Int [Int] zeroto n = [0..n]

35. We can also define a function via pattern match of the arguments. error is a built-in error function which causes program termination and the printing of the string. fac 0 = 1 fac (n+1) = product [1..(n+1)] or… fac2 n | n <  0    = error "input to fac is negative"       | n == 0    = 1       | n >  0    = product [1..n]

36. n+k -- patterns • useful when writing inductive definitions over integers. For example: x ^ 0     = 1 -- defines symbol as an operator x ^ (n+1) = x*(x^n)  fac 0 = 1 fac (n+1) = (n+1)*fac n  ack 0 n = n+1 ack (m+1) 0 = ack m 1 ack (m+1) (n+1) = ack m (ack (m+1) n)

37. The infix operators are really just functions. Notice the pattern matching. (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs++ys)

38. Curried Functions Functions with multiple arguments are also possible by returning functions as results: add’ :: (IntInt) Int add’ :: Int (Int Int) add’ x y = x+y add’ takes an integer x and returns a function add’ x. In turn, this function takes an integer y and returns the result x+y. In a curried function, the arguments can be partially applied. This allows us to get multiple functions with one declaration. In this case, we have a two parameter version of add’ and a one parameter version by passing add’ 5 (for example)

39. Note: • addPairand add’ produce the same final result, but addPairtakes its two arguments at the same time, whereas add’ takes them one at a time: addPair:: (Int,Int)  Int add’ :: Int (Int Int) • Functions that take their arguments one at a time are called curried functions, celebrating the work of Haskell Curry on such functions.

40. Why curried functions? • Curry – named for inventor - Haskell Curry. It is also called partial application. • Currying is like a nested function a function of a function… • If we don’t supply all the arguments to a curried function, we create a NEW function (that just needs the rest of its arguments). Why is that useful? • It allows function reuse • we can pass the new function to be used in a case that needs fewer arguments. For example: map (f) [1,3,5,6] applies f to each element of the list f needs to work with a single argument Because of currying, we can pass (+3), (^4), (*2) (add 5) • functions are objects – we can pass them around as such

41. Functions • Function application is curried, associates to the left, and always has a higher precedence than infix operators. • Thus ``f x y + g a b'' parses as ``((f x) y) + ((g a) b)''

42. So why do we want a curried function? • Suppose we had already defined add’ and had the need to add 5 to every element of a list. • Doing something to every element is a list is a common need. It is called “mapping” • Instead of creating a separate function to add five, we can call map (add’ 5) [1,2,3,4,5] or even map (+5) [1,2,3,4,5]

43. Functions with more than two arguments can be curried by returning nested functions: mult :: Int  (Int  (Int  Int)) mult x y z = x*y*z mult takes an integer x and returns a function mult x, which in turn takes an integer y and returns a function mult x y, which finally takes an integer z and returns the result x*y*z.

44. Why is Currying Useful? Curried functions are more flexible than functions on tuples, because useful functions can often be made by partially applying a curried function. For example: add’ 1 :: Int  Int take 5 :: [Int]  [Int] drop 5 :: [Int]  [Int]

45. Currying Conventions To avoid excess parentheses when using curried functions, two simple conventions are adopted: • The arrow  associates to the right. Int  Int  Int  Int Means Int  (Int  (Int  Int)).

46. As a consequence, it is then natural for function application to associate to the left. (Similar to a parse tree where the expression lower in the tree has the highest precedence). mult x y z Means ((mult x) y) z. Unless tupling is explicitly required, all functions in Haskell are normally defined in curried form.

47. Polymorphic Functions A function is called polymorphic (“of many forms”) if its type contains one or more type variables. length :: [a]  Int for any type a, length takes a list of values of type a and returns an integer.

48. In contrast, a monomorphic function works on only type type • inc:: Int ->Int • inc x = x+1

49. Note: • length :: [a] ->Int • Type variables can be instantiated to different types in different circumstances: > length [False,True] 2 > length [1,2,3,4] 4 a = Bool a = Int • Type variables must begin with a lower-case letter, and are usually named a, b, c, etc.

50. Many of the functions defined in the standard prelude are polymorphic. For example: fst :: (a,b)  a first element head :: [a]  a first in list take :: Int [a]  [a] pull so many from beginning zip :: [a]  [b]  [(a,b)] pull off pairwise into tuples id :: a  a identity