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.

Slides:



Advertisements
Similar presentations
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Advertisements

0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
0 PROGRAMMING IN HASKELL Chapter 2 - First Steps.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
0 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
0 PROGRAMMING IN HASKELL Chapter 11 - Interactive Programs, Declaring Types and Classes.
0 PROGRAMMING IN HASKELL Chapter 5 – Introduction, The Hugs System, Types and Classes.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
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)
Chapter 9: Functional Programming in a Typed Language.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
Overview of the Haskell 98 Programming Language
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: True.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee.
0 INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
Haskell Basics CSCE 314 Spring CSCE 314 – Programming Studio Using GHC and GHCi Log in to unix.cse.tamu.edu (or some other server) From a shell.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
0 PROGRAMMING IN HASKELL Chapter 2 - First Steps.
List Operations CSCE 314 Spring CSCE 314 – Programming Studio Tuple and List Patterns Pattern matching with wildcards for tuples fst (a, _) = a.
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
1 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Lecture 14: Advanced Topic: Functional Programming
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Polymorphic Functions
Functional Programming
Conditional Expressions
Midterm recap Total was 80 points Distribution range
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Haskell.
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

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

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

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

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]

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

Calculate the product of a list of numbers: 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]

Examples 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 f x y f (g x) f x (g y) f x * g y

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.

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)

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]

GHCi, enter :r (to reload the changed file) 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.

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

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: xs ns nss

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

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 means implicit grouping explicit grouping

Useful Commands in GHCi Command Meaning :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

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] n needs to be lower case div needs back quotes definitions need o be aligned

Can you think of another possible definition for last? (4) 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) Can you think of another possible definition for last? (4) Similarly, show how the library function init that removes the last element from a list can be defined in two different ways. (5) last' ns = ns !! (length ns -1) last1 [z] = z last1 (x:xs) = last xs last2 ns = head (reverse ns) init' ns = reverse( drop 1 (reverse ns)) init2 ns = take (length ns - 1 ) ns

PROGRAMMING IN HASKELL Types and Classes

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: True False

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.

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 data Age = Years Int deriving (Show) howOld x (Years y) = Years (x+y)

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.

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]

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.

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.

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

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

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

The type of a list says nothing about its length: 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]]

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.

The type of a tuple shows its size: 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])

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.

The arrow  is typed at the keyboard as ->. 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]

We can also define a function via pattern match of the arguments 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]

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)

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

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)

Note: addPair 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: 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.

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

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)''

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]

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.

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]

Means Int  (Int  (Int  Int)). 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)).

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.

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.

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

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.

Many of the functions defined in the standard prelude are polymorphic 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

Overloaded Functions Type classes provide a structured way to control polymorphism. sum :: Num a  [a]  a for any numeric type a, sum takes a list of values of type a and returns a value of type a.

Char is not a numeric type Note: Constrained type variables can be instantiated to any types that satisfy the constraints: > sum [1,2,3] 6 > sum [1.1,2.2,3.3] 6.6 > sum [’a’,’b’,’c’] ERROR a = Int a = Float Char is not a numeric type

Haskell has a number of type classes, including: - Numeric types Eq - Equality types Ord - Ordered types For example: (+) :: Num a  a  a  a (==) :: Eq a  a  a  Bool (<) :: Ord a  a  a  Bool See types by entering :t (==)

Hints and Tips When defining a new function in Haskell, it is useful to begin by writing down its type; Within a script, it is good practice to state the type of every new function defined; When stating the types of polymorphic functions that use numbers, equality or orderings, take care to include the necessary class constraints.

Exercises What are the types of the following values? (1) [’a’,’b’,’c’] (’a’,’b’,’c’) [(False,’0’),(True,’1’)] ([False,True],[’0’,’1’]) [tail,init,reverse]

What are the types of the following functions? (2) second xs = head (tail xs) swap (x,y) = (y,x) pair x y = (x,y) double x = x*2 palindrome xs = reverse xs == xs twice f x = f (f x) Check your answers using GHCi. (3)

PROGRAMMING IN HASKELL Defining Functions

Conditional Expressions As in most programming languages, functions can be defined using conditional expressions. abs :: Int  Int abs n = if n  0 then n else -n abs takes an integer n and returns n if it is non-negative and -n otherwise.

Conditional expressions can be nested: signum :: Int  Int signum n = if n < 0 then -1 else if n == 0 then 0 else 1 Note: In Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity problems with nested conditionals.

As previously, but using guarded equations. As an alternative to conditionals, functions can also be defined using guarded equations. abs n | n  0 = n | otherwise = -n As previously, but using guarded equations.

Guarded equations can be used to make definitions involving multiple conditions easier to read: signum n | n < 0 = -1 | n == 0 = 0 | otherwise = 1 Note: The catch all condition otherwise is defined in the prelude by otherwise = True.

not maps False to True, and True to False. Pattern Matching Many functions have a particularly clear definition using pattern matching on their arguments. not :: Bool  Bool not False = True not True = False not maps False to True, and True to False.

can be defined more compactly by Functions can often be defined in many different ways using pattern matching. For example both :: Bool  Bool  Bool True `both` True = True True `both` False = False False `both` True = False False `both` False = False can be defined more compactly by True`both` True = True _ `both` _ = False

However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False: True `both` b = b False `both` _ = False` Note: The underscore symbol _ is a wildcard pattern that matches any argument value.

Patterns are matched in order Patterns are matched in order. For example, the following definition always returns False: _ && _ = False True && True = True Patterns may not repeat variables. For example, the following definition gives an error: b && b = b _ && _ = False

List Patterns Internally, every non-empty list is constructed by repeated use of an operator (:) called “cons” (for construct ) that adds an element to the start of a list. Note this is NOT the same as concatenation of lists. [1,2,3,4] Means 1:(2:(3:(4:[]))).

Functions on lists can be defined using x:xs patterns. head :: [a]  a head (x:_) = x tail :: [a]  [a] tail (_:xs) = xs head and tail map any non-empty list to its first and remaining elements.

x:xs patterns only match non-empty lists: Note: x:xs patterns only match non-empty lists: > head [] Error x:xs patterns must be parenthesized, because application has priority over (:). For example, the following definition gives an error: head x:_ = x

pred maps any positive integer to its predecessor. Integer Patterns As in mathematics, functions on integers can be defined using n+k patterns, where n is an integer variable and k>0 is an integer constant. pred :: Int  Int pred (n+1) = n pred maps any positive integer to its predecessor.

n+k patterns only match integers  k. Note: n+k patterns only match integers  k. > pred 0 Error n+k patterns must be parenthesised, because application of = has priority over +. For example, the following definition gives an error: pred n+1 = n

Lambda Expressions Functions can be constructed without naming the functions by using lambda expressions. x  x+x twoTimes x  x+x similar to the named function the nameless function that takes a number x and returns the result x+x.

Note: The symbol  is the Greek letter lambda, and is typed at the keyboard as a backslash \. In mathematics, nameless functions are usually denoted using the  symbol, as in x  x+x. In Haskell, the use of the  symbol for nameless functions comes from the lambda calculus, the theory of functions on which Haskell is based.

Why Are Lambda's Useful? Lambda expressions can be used to give a formal meaning to functions defined using currying. For example: add x y = x+y means add = x  (y  x+y)

is more naturally defined by Lambda expressions are also useful when defining functions that return functions as results. For example: const :: a  b  a const x _ = x is more naturally defined by const :: a  (b  a) const x = _  x

Lambda expressions can be used to avoid naming functions that are only referenced once. For example: odds n = map f [0..n-1] where f x = x*2 + 1 can be simplified to odds n = map (x  x*2 + 1) [0..n-1]

Turning infix functions into prefix ones Sections An infix 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

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.

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/)

Exercises (1) 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.

Do the same for the following version: (4) Give three possible definitions for the logical or operator (or) using pattern matching. (2) Redefine the following version of (and) using conditionals rather than patterns: (3) True `and` True = True _ `and` _ = False Do the same for the following version: (4) True `and` b = b False `and` _ = False

PROGRAMMING IN HASKELL

Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. Comprehension has two meanings in English: a. understanding b. the act of process or comprising or including {x2 | x  {1...5}} The set {1,4,9,16,25} of all numbers x2 such that x is an element of the set {1…5}.

Lists Comprehensions In Haskell, a similar comprehension notation can be used to construct new lists from old lists. [x^2 | x  [1..5]] The list [1,4,9,16,25] of all numbers x^2 such that x is an element of the list [1..5].

Note: The expression x  [1..5] is called a generator, as it states how to generate values for x. Comprehensions can have multiple generators, separated by commas. For example: > [(x,y) | x  [1,2,3], y  [4,5]] [(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]

Changing the order of the generators changes the order of the elements in the final list: > [(x,y) | y  [4,5], x  [1,2,3]] [(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)] Multiple generators are like nested loops, with later generators as more deeply nested loops whose variables change value more frequently.

For example: > [(x,y) | y  [4,5], x  [1,2,3]] [(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)] x  [1,2,3] is the last generator, so the value of the x component of each pair changes most frequently.

The list [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)] Dependant Generators Later generators can depend on the variables that are introduced by earlier generators. [(x,y) | x  [1..3], y  [x..3]] The list [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)] of all pairs of numbers (x,y) such that x,y are elements of the list [1..3] and y  x.

Using a dependant generator we can define the library function that concatenates a list of lists: concat :: [[a]]  [a] concat xss = [x | xs  xss, x  xs] For example: > concat [[1,2,3],[4,5],[6]] [1,2,3,4,5,6]

Arithmetic sequences There is a shorthand notation for lists whose elements form an arithmetic series. [1..5]    -- yields [1,2,3,4,5] [1,3..10] -- yields [1,3,5,7,9] In the second list, the difference between the first two elements is used to compute the remaining elements in the series.

Guards List comprehensions can use guards to restrict the values produced by earlier generators. [x | x  [1..10], even x] The list [2,4,6,8,10] of all numbers x such that x is an element of the list [1..10] and x is even.

Using a guard we can define a function that maps a positive integer to its list of factors: factors :: Int  [Int] factors n = [x | x  [1..n], n `mod` x == 0] For example: > factors 15 [1,3,5,15]

A positive integer is prime if its only factors are 1 and itself A positive integer is prime if its only factors are 1 and itself. Hence, using factors we can define a function that decides if a number is prime: prime :: Int  Bool prime n = factors n == [1,n] For example: > prime 15 False > prime 7 True

Using a guard we can now define a function that returns the list of all primes up to a given limit: primes :: Int  [Int] primes n = [x | x  [2..n], prime x] For example: > primes 40 [2,3,5,7,11,13,17,19,23,29,31,37]

The Zip Function A useful library function is zip, which maps two lists to a list of pairs of their corresponding elements. zip :: [a]  [b]  [(a,b)] For example: > zip [’a’,’b’,’c’] [1,2,3,4] [(’a’,1),(’b’,2),(’c’,3)]

Using zip we can define a function returns the list of all pairs of adjacent elements from a list: pairs :: [a]  [(a,a)] pairs xs = zip xs (tail xs) For example: > pairs [1,2,3,4] [(1,2),(2,3),(3,4)]

Using pairs we can define a function that decides if the elements in a list are sorted: sorted :: Ord a  [a]  Bool sorted xs = and [x  y | (x,y)  pairs xs] For example: > sorted [1,2,3,4] True > sorted [1,3,2,4] False

Using zip we can define a function that returns the list of all positions of a specified value in a list: positions :: Eq a  a  [a]  [Int] positions x xs = [i | (x’,i)  zip xs [0..n], x == x’] where n = length xs - 1 For example: > positions 0 [1,0,0,1,0,1,1,0] [1,2,4,7]

String Comprehensions A string is a sequence of characters enclosed in double quotes. Internally, however, strings are represented as lists of characters. "abc" :: String Means [’a’,’b’,’c’] :: [Char].

Because strings are just special kinds of lists, any polymorphic function that operates on lists can also be applied to strings. For example: > length "abcde" 5 > take 3 "abcde" "abc" > zip "abc" [1,2,3,4] [(’a’,1),(’b’,2),(’c’,3)]

Similarly, list comprehensions can also be used to define functions on strings, such as a function that counts the lower-case letters in a string: lowers :: String  Int lowers xs = length [x | x  xs, isLower x] For example: > lowers "Haskell" 6

Exercises (1) A triple (x,y,z) of positive integers is called pythagorean if x2 + y2 = z2. Using a list comprehension, define a function pyths :: Int  [(Int,Int,Int)] that maps an integer n to all such triples with components in [1..n]. For example: > pyths 5 [(3,4,5),(4,3,5)]

(2) A positive integer is perfect if it equals the sum of all of its factors, excluding the number itself. Using a list comprehension, define a function perfects :: Int  [Int] that returns the list of all perfect numbers up to a given limit. For example: > perfects 500 [6,28,496]

(3) The scalar product of two lists of integers xs and ys of length n is give by the sum of the products of the corresponding integers: (xsi * ysi )  i = 0 n-1 Using a list comprehension, define a function that returns the scalar product of two lists.

PROGRAMMING IN HASKELL Recursive Functions

Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int  Int factorial n = product [1..n] factorial maps any integer n to the product of the integers between 1 and n.

Expressions are evaluated by a stepwise process of applying functions to their arguments. For example: factorial 4 product [1..4] = product [1,2,3,4] = 1*2*3*4 = 24 =

Recursive Functions In Haskell, functions can also be defined in terms of themselves. Such functions are called recursive. factorial 0 = 1 factorial (n+1) = (n+1) * factorial n factorial maps 0 to 1, and any other positive integer to the product of itself and the factorial of its predecessor.

For example: = = = = = = = factorial 3 3 * factorial 2 3 * (2 * (1 * 1)) = 3 * (2 * 1) = 3 * 2 = = 6

Note: factorial 0 = 1 is appropriate because 1 is the identity for multiplication: 1*x = x = x*1. The recursive definition diverges on integers  0 because the base case is never reached: > factorial (-1) Error: Control stack overflow

Why is Recursion Useful? Some functions, such as factorial, are simpler to define in terms of other functions. Many functions can naturally be defined in terms of themselves. Properties of functions defined using recursion can be proved using the simple but powerful mathematical technique of induction.

Recursion on Lists Recursion is not restricted to numbers, but can also be used to define functions on lists. product :: [Int]  Int product [] = 1 product (n:ns) = n * product ns product maps the empty list to 1, and any non-empty list to its head multiplied by the product of its tail.

For example: = = = = = product [2,3,4] 2 * product [3,4] 2 * (3 * (4 * 1)) = 24 =

Using the same pattern of recursion as in product we can define the length function on lists. length :: [a]  Int length [] = 0 length (_:xs) = 1 + length xs length maps the empty list to 0, and any non-empty list to the successor of the length of its tail.

For example: = = = = = length [1,2,3] 1 + length [2,3] 1 + (1 + (1 + 0)) = 3 =

Using a similar pattern of recursion we can define the reverse function on lists. reverse :: [a]  [a] reverse [] = [] reverse (x:xs) = reverse xs ++ [x] reverse maps the empty list to the empty list, and any non-empty list to the reverse of its tail appended to its head.

For example: = = = = = reverse [1,2,3] reverse [2,3] ++ [1] (([] ++ [3]) ++ [2]) ++ [1] = [3,2,1] =

Permutation Example permute :: Eq a => [a] -> [[a]] permute xs = [x:ys | x<-xs, ys <- permute (delete' x xs)]

Multiple Arguments Functions with more than one argument can also be defined using recursion. For example: Zipping the elements of two lists: zip :: [a]  [b]  [(a,b)] zip [] _ = [] zip _ [] = [] zip (x:xs) (y:ys) = (x,y) : zip xs ys

Remove the first n elements from a list: drop :: Int  [a]  [a] drop 0 xs = xs drop (n+1) [] = [] drop (n+1) (_:xs) = drop n xs Appending two lists: (++) :: [a]  [a]  [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys)

Quicksort The quicksort algorithm for sorting a list of integers can be specified by the following two rules: The empty list is already sorted; Non-empty lists can be sorted by sorting the tail values  the head, sorting the tail values  the head, and then appending the resulting lists on either side of the head value.

Using recursion, this specification can be translated directly into an implementation: qsort :: [Int]  [Int] qsort [] = [] qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger where smaller = [a | a  xs, a  x] larger = [b | b  xs, b  x] Note: This is probably the simplest implementation of quicksort in any programming language!

For example (abbreviating qsort as q): ++ [3] ++ q [4,5] q [1] q [] ++ [2] ++ q [] q [5] ++ [4] ++ [1] [] [] [5]

Exercises (1) Without looking at the standard prelude, define the following library functions using recursion: Decide if all logical values in a list are true: and :: [Bool]  Bool Concatenate a list of lists : concat([2,3,4],[3,4,5],[4]) = [2,3,4,3,4,5,4] concat :: [[a]]  [a]

Produce a list with n identical elements: replicate :: Int  a  [a] Select the nth element of a list: (!!) :: [a]  Int  a Decide if a value is an element of a list: elem :: Eq a  a  [a]  Bool

Define a recursive function (2) Define a recursive function merge :: [Int]  [Int]  [Int] that merges two sorted lists of integers to give a single sorted list. For example: > merge [2,5,6] [1,3,4] [1,2,3,4,5,6]

Define a recursive function (3) Define a recursive function msort :: [Int]  [Int] that implements merge sort, which can be specified by the following two rules: Lists of length  1 are already sorted; Other lists can be sorted by sorting the two halves and merging the resulting lists.