programming in haskell - math.rs · haskell scripts as well as the functions in the standard...
TRANSCRIPT
![Page 1: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/1.jpg)
0
PROGRAMMING IN HASKELL
Chapter 2 - First Steps
![Page 2: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/2.jpg)
1
The Hugs System
Hugs is an implementation of Haskell 98, and is the most widely used Haskell system;
The interactive nature of Hugs makes it well suited for teaching and prototyping purposes;
Hugs is available on the web from:
www.haskell.org/hugs
![Page 3: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/3.jpg)
2
Starting Hugs
% hugs
__ __ __ __ ____ ___ _________________________________________
|| || || || || || ||__ Hugs 98: Based on the Haskell 98 standard
||___|| ||__|| ||__|| __|| Copyright (c) 1994-2005
||---|| ___|| World Wide Web: http://haskell.org/hugs
|| || Report bugs to: [email protected]
|| || _________________________________________
>
On a Unix system, Hugs can be started from the % prompt by simply typing hugs:
![Page 4: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/4.jpg)
3
The Hugs > prompt means that the Hugs system is ready to evaluate an expression. For example:
> 2+3*4
14
> (2+3)*4
20
> sqrt (3^2 + 4^2)
5.0
![Page 5: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/5.jpg)
4
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.
Select the first element of a list:
> head [1,2,3,4,5]
1
![Page 6: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/6.jpg)
5
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]
![Page 7: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/7.jpg)
6
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
![Page 8: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/8.jpg)
7
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]
![Page 9: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/9.jpg)
8
Function Application
In mathematics, function application is denoted using parentheses, and multiplication is often denoted using juxtaposition or space.
f(a,b) + c d
Apply the function f to a and b, and add the result to the product of c and d.
![Page 10: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/10.jpg)
9
In Haskell, function application is denoted using space, and multiplication is denoted using *.
f a b + c*d
As previously, but in Haskell syntax.
![Page 11: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/11.jpg)
10
Moreover, function application is assumed to have higher priority than all other operators.
f a + b
Means (f a) + b, rather than f (a + b).
![Page 12: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/12.jpg)
11
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
![Page 13: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/13.jpg)
12
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.
![Page 14: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/14.jpg)
13
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 Hugs. Start an editor, type in the following two function definitions, and save the script as test.hs:
![Page 15: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/15.jpg)
14
% hugs test.hs
Leaving the editor open, in another window start up Hugs with the new script:
> 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:
![Page 16: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/16.jpg)
15
factorial n = product [1..n]
average ns = sum ns `div` length ns
Leaving Hugs open, return to the editor, add the following two definitions, and resave:
div is enclosed in back quotes, not forward;
x `f` y is just syntactic sugar for f x y.
Note:
![Page 17: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/17.jpg)
16
> :reload
Reading file "test.hs"
> factorial 10
3628800
> average [1,2,3,4,5]
3
Hugs does not automatically detect that the script has been changed, so a reload command must be executed before the new definitions can be used:
![Page 18: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/18.jpg)
17
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
![Page 19: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/19.jpg)
18
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
![Page 20: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/20.jpg)
19
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
![Page 21: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/21.jpg)
20
Useful Hugs Commands
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 Hugs
![Page 22: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/22.jpg)
21
Exercises
N = a ’div’ length xs
where
a = 10
xs = [1,2,3,4,5]
Try out slides 2-8 and 14-17 using Hugs. Fix the syntax errors in the program below, and test your solution using Hugs.
(1)
(2)
![Page 23: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/23.jpg)
22
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? (4)
![Page 24: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/24.jpg)
0
PROGRAMMING IN HASKELL
Chapter 3 - Types and Classes
![Page 25: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/25.jpg)
1
What is a Type?
A type is a name for a collection of related values. For example, in Haskell the basic type
True False
Bool
contains the two logical values:
![Page 26: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/26.jpg)
2
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.
![Page 27: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/27.jpg)
3
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.
![Page 28: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/28.jpg)
4
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 Hugs, the :type command calculates the type of an expression, without evaluating it:
> not False
True
> :type not False
not False :: Bool
![Page 29: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/29.jpg)
5
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
![Page 30: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/30.jpg)
6
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.
![Page 31: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/31.jpg)
7
The type of a list says nothing about its length:
[False,True] :: [Bool]
[False,True,False] :: [Bool]
[[’a’],[’b’,’c’]] :: [[Char]]
Note:
The type of the elements is unrestricted. For example, we can have lists of lists:
![Page 32: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/32.jpg)
8
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.
![Page 33: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/33.jpg)
9
The 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:
The type of the components is unrestricted:
![Page 34: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/34.jpg)
10
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.
![Page 35: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/35.jpg)
11
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:
Note:
add :: (Int,Int) Int
add (x,y) = x+y
zeroto :: Int [Int]
zeroto n = [0..n]
![Page 36: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/36.jpg)
12
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
![Page 37: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/37.jpg)
13
add 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:
Functions 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)
![Page 38: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/38.jpg)
14
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.
![Page 39: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/39.jpg)
15
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]
![Page 40: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/40.jpg)
16
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)).
![Page 41: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/41.jpg)
17
As 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.
![Page 42: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/42.jpg)
18
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.
![Page 43: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/43.jpg)
19
Type variables can be instantiated to different types in different circumstances:
Note:
Type 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
![Page 44: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/44.jpg)
20
Many 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
![Page 45: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/45.jpg)
21
Overloaded Functions
A polymorphic function is called overloaded if its type contains one or more class constraints.
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.
![Page 46: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/46.jpg)
22
Constrained type variables can be instantiated to any types that satisfy the constraints:
Note:
> sum [1,2,3]
6
> sum [1.1,2.2,3.3]
6.6
> sum [’a’,’b’,’c’]
ERROR
Char is not a numeric type
a = Int
a = Float
![Page 47: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/47.jpg)
23
Num - Numeric types
Eq - Equality types
Ord - Ordered types
Haskell has a number of type classes, including:
For example:
(+) :: Num a a a a
(==) :: Eq a a a Bool
(<) :: Ord a a a Bool
![Page 48: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/48.jpg)
24
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.
![Page 49: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/49.jpg)
25
Exercises
[’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? (1)
![Page 50: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/50.jpg)
26
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)
What are the types of the following functions? (2)
Check your answers using Hugs. (3)
![Page 51: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/51.jpg)
0
PROGRAMMING IN HASKELL
Chapter 4 - Defining Functions
![Page 52: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/52.jpg)
1
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.
![Page 53: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/53.jpg)
2
Conditional expressions can be nested:
signum :: Int Int
signum n = if n < 0 then -1 else
if n == 0 then 0 else 1
In Haskell, conditional expressions must always have an else branch, which avoids any possible ambiguity problems with nested conditionals.
Note:
![Page 54: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/54.jpg)
3
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.
![Page 55: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/55.jpg)
4
Guarded equations can be used to make definitions involving multiple conditions easier to read:
The catch all condition otherwise is defined in the prelude by otherwise = True.
Note:
signum n | n < 0 = -1
| n == 0 = 0
| otherwise = 1
![Page 56: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/56.jpg)
5
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.
![Page 57: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/57.jpg)
6
Functions can often be defined in many different ways using pattern matching. For example
(&&) :: Bool Bool Bool
True && True = True
True && False = False
False && True = False
False && False = False
True && True = True
_ && _ = False
can be defined more compactly by
![Page 58: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/58.jpg)
7
True && b = b
False && _ = False
However, the following definition is more efficient, because it avoids evaluating the second argument if the first argument is False:
The underscore symbol _ is a wildcard pattern that matches any argument value.
Note:
![Page 59: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/59.jpg)
8
Patterns may not repeat variables. For example, the following definition gives an error:
b && b = b
_ && _ = False
Patterns are matched in order. For example, the following definition always returns False:
_ && _ = False
True && True = True
![Page 60: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/60.jpg)
9
List Patterns
Internally, every non-empty list is constructed by repeated use of an operator (:) called “cons” that adds an element to the start of a list.
[1,2,3,4]
Means 1:(2:(3:(4:[]))).
![Page 61: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/61.jpg)
10
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.
![Page 62: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/62.jpg)
11
Note:
x:xs patterns must be parenthesised, because application has priority over (:). For example, the following definition gives an error:
x:xs patterns only match non-empty lists:
> head []
Error
head x:_ = x
![Page 63: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/63.jpg)
12
Integer Patterns
pred :: Int Int
pred (n+1) = n
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 maps any positive integer to its predecessor.
![Page 64: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/64.jpg)
13
Note:
n+k patterns must be parenthesised, because application has priority over +. For example, the following definition gives an error:
n+k patterns only match integers k.
> pred 0
Error
pred n+1 = n
![Page 65: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/65.jpg)
14
Lambda Expressions
Functions can be constructed without naming the functions by using lambda expressions.
x x+x
the nameless function that takes a number x and returns the result x+x.
![Page 66: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/66.jpg)
15
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.
Note:
![Page 67: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/67.jpg)
16
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
add = x (y x+y)
means
![Page 68: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/68.jpg)
17
const :: a b a
const x _ = x
is more naturally defined by
const :: a (b a)
const x = _ x
Lambda expressions are also useful when defining functions that return functions as results. For example:
![Page 69: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/69.jpg)
18
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]
Lambda expressions can be used to avoid naming functions that are only referenced once. For example:
![Page 70: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/70.jpg)
19
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
![Page 71: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/71.jpg)
20
This convention also allows one of the arguments of the operator to be included in the parentheses. For example:
> (1+) 2
3
> (+2) 1
3
In general, if is an operator then functions of the form (), (x) and (y) are called sections.
![Page 72: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/72.jpg)
21
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/)
![Page 73: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/73.jpg)
22
Exercises
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.
(1)
![Page 74: PROGRAMMING IN HASKELL - math.rs · 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,](https://reader030.vdocument.in/reader030/viewer/2022033119/5e5b0943da7a43043c13645a/html5/thumbnails/74.jpg)
23
Give three possible definitions for the logical or operator (||) using pattern matching.
(2)
Redefine the following version of (&&) using conditionals rather than patterns:
(3)
True && True = True
_ && _ = False
Do the same for the following version: (4)
True && b = b
False && _ = False