Presentation is loading. Please wait.

Presentation is loading. Please wait.

0 PROGRAMMING IN HASKELL Some first steps Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)

Similar presentations


Presentation on theme: "0 PROGRAMMING IN HASKELL Some first steps Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)"— Presentation transcript:

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

2 1 Glasgow Haskell Compiler zGHC is the leading implementation of Haskell, and comprises a compiler and interpreter; zThe interactive nature of the interpreter makes it well suited for teaching and prototyping; zGHC is freely available from: www.haskell.org/platform

3 2 Starting GHC % ghci GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim... linking... done. Loading package integer-gmp... linking... done. Loading package base... linking... done. Prelude> The GHC interpreter can be started from the Unix command prompt % by simply typing ghci:

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

5 4 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:

6 5 % ghci test.hs Leaving the editor open, in another window start up GHCi with the new script: > quadruple 10 40 > take (double 2) [1,2,3,4,5,6] [1,2,3,4] Now both the standard library and the file test.hs are loaded, and functions from both can be used:

7 6 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: zdiv is enclosed in back quotes, not forward; zx `f` y is just syntactic sugar for f x y. zSo this is just saying “div (sum ns) (length ns) Note:

8 7 > :reload 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:

9 8 head :: [a] -> a head (x:xs) = x Functions are often done using pattern matching, as well as a declaration of type (more later): Now you try one…

10 9 Exercise myLength : [a] -> Int myLength [] = myLength [x:xs] = Write a program to find the number of elements in a list. Here’s how to start: How do you test this to be sure it works? (Copy your function into an email to me, but don’t send yet.)

11 10 Naming Requirements zFunction and argument names must begin with a lower-case letter. For example: myFunfun1arg_2x’x’ zBy convention, list arguments usually have an s suffix on their name. For example: xsnsnss

12 11 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

13 12 means The layout rule avoids the need for explicit syntax to indicate the grouping of definitions. 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

14 13 Useful GHCi Commands CommandMeaning :load nameload script name :reloadreload current script :edit nameedit script name :editedit current script :type exprshow type of expr :?show all commands :quitquit GHCi

15 14 Exercise N = a ’div’ length xs where a = 10 xs = [1,2,3,4,5] Fix the syntax errors in the program below, and test your solution using GHCi. (Copy your corrected version into an email to me, but don’t send yet.)

16 15 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:

17 16 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.

18 17 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.

19 18 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

20 19 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

21 20 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.

22 21 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:

23 22 Tuple Types 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.

24 23 zThe type of a tuple encodes 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:

25 24 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.

26 25  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: add :: (Int,Int)  Int add (x,y) = x+y zeroto :: Int  [Int] zeroto n = [0..n]

27 26 Exercise [’a’,’b’,’c’] (’a’,’b’,’c’) [(False,’0’),(True,’1’)] ([False,True],[’0’,’1’]) [tail,init,reverse] What are the types of the following values? (Again, add this to that email.)

28 27 Exercise Prelude> myLast [1,2,3,4] 4 Prelude> myLast [‘x’,’y’,’z’] z Write a function in your script that will find the last element in a list. For example: Note that your first line should be declaration plus type, and from there use pattern matching and recursion. (Again, add this to that email.)

29 28 Functions with multiple arguments are also possible by returning functions as results: 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

30 29 zadd and add’ produce the same final result, but add 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. add :: (Int,Int)  Int add’ :: Int  (Int  Int)

31 30 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.

32 31 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]

33 32 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)).

34 33 zAs a consequence, it is then natural for function application to associate to the left. mult x y z Means ((mult x) y) z. Unless tupling is explicitly required, all functions in Haskell are normally defined in curried form.

35 34 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.

36 35 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

37 36 zMany of the functions defined in the standard prelude are polymorphic. For example: fst :: (a,b)  a head :: [a]  a take :: Int  [a]  [a] zip :: [a]  [b]  [(a,b)] id :: a  a


Download ppt "0 PROGRAMMING IN HASKELL Some first steps Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)"

Similar presentations


Ads by Google