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

Post on 19-Dec-2015

218 views

Category:

## Documents

Embed Size (px)

TRANSCRIPT

• Slide 1
• 0 PROGRAMMING IN HASKELL Author: Prof Graham Hutton Functional Programming Lab School of Computer Science University of Nottingham, UK (Used with Permission)
• Slide 2
• 1 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
• Slide 3
• 2 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. zBecause of the predefinitions, GHCi may complain if you try to redefine something it already has a definition for. zSelect the first element of a list: zSingle line comments are preceded by ``--'' and continue to the end of the line. > head [1,2,3,4,5] 1
• Slide 4
• 3 zRemove the first element from a list: > tail [1,2,3,4,5] [2,3,4,5] zSelect the nth element of a list: > [1,2,3,4,5] !! 2 3 zSelect the first n elements of a list: > take 3 [1,2,3,4,5] [1,2,3]
• Slide 5
• 4 zRemove the first n elements from a list: > drop 3 [1,2,3,4,5] [4,5] zCalculate the length of a list: > length [1,2,3,4,5] 5 zCalculate the sum of a list of numbers: > sum [1,2,3,4,5] 15
• Slide 6
• 5 zCalculate the product of a list of numbers: > product [1,2,3,4,5] 120 zAppend two lists: > [1,2,3] ++ [4,5] [1,2,3,4,5] zReverse a list: > reverse [1,2,3,4,5] [5,4,3,2,1]
• Slide 7
• 6 Examples Mathematics Haskell f(x) f(x,y) f(g(x)) f(x,g(y)) f(x)g(y) f x f x y f (g x) f x (g y) f x * g y
• Slide 8
• 7 Haskell Scripts zAs well as the functions in the standard prelude, you can also define your own functions; zNew functions are defined within a script, a text file comprising a sequence of definitions; zBy convention, Haskell scripts usually have a.hs suffix on their filename. This is not mandatory, but is useful for identification purposes.
• Slide 9
• 8 My First Script double x = x + x quadruple x = double (double x) 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:
• Slide 10
• 9 Leaving the editor open, click on the file to open ghci using that file: > quadruple 10 40 > take (double 2) [1,2,3,4,5,6] [1,2,3,4] Now both Prelude.hs and test.hs are loaded, and functions from both scripts can be used:
• Slide 11
• 10 factorial n = product [1..n] average ns = sum ns `div` length ns Leaving GHCi open, return to the editor, add the following two definitions, and resave. From within GHCi, enter :r (to reload the changed file) zThese functions are defined via an equation zdiv is enclosed in back quotes, not forward; zx `f` y is just syntactic sugar for f x y. Note:
• Slide 12 factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so "> factorial 10 3628800 > average [1,2,3,4,5] 3 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:"> factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so " title="11 > :r Reading file "test.hs" > factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so ">
• 11 > :r Reading file "test.hs" > factorial 10 3628800 > average [1,2,3,4,5] 3 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:
• Slide 13
• 12 Naming Requirements zFunction and argument names must begin with a lower-case letter. For example: myFunfun1arg_2x zBy convention, list arguments usually have an s suffix on their name. For example: xsnsnss
• Slide 14
• 13 The Layout Rule In a sequence of definitions, each definition must begin in precisely the same column: a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 a = 10 b = 20 c = 30
• Slide 15
• 14 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
• Slide 16
• 15 Useful Commands in GHCi CommandMeaning :load nameload script name :reloadreload current script :edit nameedit script name :editedit current script :type exprshow type of expr :?show all commands :quitquit
• Slide 17
• 16 Exercises N = a div length xs where a = 10 xs = [1,2,3,4,5] Try out the examples of this lecture Fix the syntax errors in the program below, and test your solution. (1) (2)
• Slide 18
• 17 Show how the library function last that selects the last element of a list can be defined using the functions introduced in this lecture. (3) Similarly, show how the library function init that removes the last element from a list can be defined in two different ways. (5) Can you think of another possible definition for last? (4)
• Slide 19
• 18 PROGRAMMING IN HASKELL Types and Classes
• Slide 20
• 19 What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type TrueFalse Bool contains the two logical values:
• Slide 21
• Algebraic types zthere are still things we are missing such as yThe types for the months January December. yThe type whose elements are either a number or a string. (a house will either have a number or name, say) yA type of tree. zAll of these can be modeled as algebraic types. 20
• Slide 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 21
• Slide 23
• The general form of the algebraic type is zdata TypeName z = Con 1 T 11.. T 1n | z Con 2 T 21..T 2m | Each Con i is a constructor which may be followed by zero or more types. We build elements of TypeName by applying this constsructor functions to arguments. 22
• Slide 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] 23
• Slide 25
• 24 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.
• Slide 26
• 25 Types in Haskell zIf evaluating an expression e would produce a value of type t, then e has type t, written e :: t zEvery well formed expression has a type, which can be automatically calculated at compile time using a process called type inference.
• Slide 27
• 26 zAll type errors are found at compile time, which makes programs safer and faster by removing the need for type checks at run time. zIn GHCi, the :type command calculates the type of an expression, without evaluating it: > not False True > :type not False not False :: Bool
• Slide 28
• 27 Basic Types Haskell has a number of basic types, including: Bool - logical values Char - single characters Integer - arbitrary-precision integers Float - floating-point numbers String - strings of characters Int - fixed-precision integers
• Slide 29
• 28 List Types [False,True,False] :: [Bool] [a,b,c,d] :: [Char] In general: A list is sequence of values of the same type: [t] is the type of lists with elements of type t.
• Slide 30
• 29 zThe type of a list says nothing about its length: [False,True] :: [Bool] [False,True,False] :: [Bool] [[a],[b,c]] :: [[Char]] Note: zThe type of the elements is unrestricted. For example, we can have lists of lists:
• Slide 31
• 30 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 1n.
• Slide 32
• 31 zThe type of a tuple shows its size: (False,True) :: (Bool,Bool) (False,True,False) :: (Bool,Bool,Bool) (a,(False,b)) :: (Char,(Bool,Char)) (True,[a,b]) :: (Bool,[Char]) Note: zThe type of the components is unrestricted:
• Slide 33
• 32 Function Types not :: Bool Bool isDigit :: Char Bool In general: A function is a mapping from values of one type to values of another type: t1 t2 is the type of functions that map values of type t1 to values to type t2.
• Slide 34
• 33 The arrow is typed at the keyboard as ->. zThe argument and result types are unrestricted. For example, functions with multiple arguments or results are possible using lists or tuples: Note: addPair :: (Int,Int) Int addPair (x,y) = x+y zeroto :: Int [Int] zeroto n = [0..n]
• Slide 35 0 = product [1..n] 34">
• 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] 34
• Slide 36
• n+k -- patterns zuseful 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) 35
• Slide 37
• The infix operators are really just functions. Notice the pattern matching. (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs++ys) 36
• Slide 38
• 37 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. Curried Functions 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)
• Slide 39
• 38 zaddPair and add produce the same final result, but addPair takes its two arguments at the same time, whereas add takes them one at a time: Note: zFunctions that take their arguments one at a time are called curried functions, celebrating the work of Haskell Curry on such functions. addPair :: (Int,Int) Int add :: Int (Int Int)
• Slide 40
• Why curried functions? zCurry named for inventor - Haskell Curry. It is also called partial application. zCurrying is like a nested function a function of a function zIf we dont 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? yIt allows function reuse ywe 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) yfunctions are objects we can pass them around as such 39
• Slide 41
• Functions zFunction application is curried, associates to the left, and always has a higher precedence than infix operators. zThus ``f x y + g a b'' parses as ``((f x) y) + ((g a) b)'' 40
• Slide 42
• So why do we want a curried function? zSuppose we had already defined add and had the need to add 5 to every element of a list. zDoing something to every element is a list is a common need. It is called mapping zInstead 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] 41
• Slide 43
• 42 zFunctions 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.
• Slide 44
• 43 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]
• Slide 45
• 44 Currying Conventions The arrow associates to the right. Int Int Int Int To avoid excess parentheses when using curried functions, two simple conventions are adopted: Means Int (Int (Int Int)).
• Slide 46
• 45 zAs 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.
• Slide 47
• 46 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.
• Slide 48
• In contrast, a monomorphic function works on only type type zinc:: Int ->Int zinc x = x+1 47
• Slide 49
• 48 zlength :: [a] ->Int zType variables can be instantiated to different types in different circumstances: Note: zType variables must begin with a lower-case letter, and are usually named a, b, c, etc. > length [False,True] 2 > length [1,2,3,4] 4 a = Bool a = Int
• Slide 50
• 49 zMany of the functions defined in the standard prelude are polymorphic. For example:...