Haskell Prelude Tour A4
Haskell Prelude Tour A4
Bernie Pope∗
2001
1 Haskell
The Haskell language was conceived during a meeting held at the 1987 Func-
tional Programming and Computer Architecture conference (FPCA 87). At the
time of the conference it was believed that the advancement of functional pro-
gramming was being stifled by the wide variety of languages available. There
were more than a dozen lazy, purely functional languages in existence and none
had widespread support (except perhaps Miranda1 ). A committee was formed
to design the language. The name Haskell was chosen in honour of the mathe-
matician Haskell Curry, whose research forms part of the theoretical basis upon
which many functional languages are implemented. Haskell is widely used within
the functional programming community, and there exists a number of implemen-
tations. In 1998 the Haskell community agreed upon a standard definition of
the language and supporting libraries. One of the aims of standardisation was
to encourage the creation of text books and courses devoted to the language.
The resulting language definition is called Haskell 98.
Haskell is a lazy functional language with polymorphic higher-order func-
tions, algebraic data types and list comprehensions. It has an extensive mod-
ule system, and supports ad-hoc polymorphism (via classes). Haskell is purely
functional, even for I/O. Most Haskell implementations come with a num-
ber of libraries supporting arrays, complex numbers, infinite precision inte-
gers, operating system interaction, concurrency and mutable data structures.
There is a popular interpreter (called Hugs) and many compilers. More infor-
mation about the Haskell language can be found on following the web-page:
www.haskell.org.
Hugs2 is a freely available interpreter for Haskell, which runs under Unix,
Macintosh, and Microsoft Windows. One of the main features of Hugs is that it
provides an interactive programming environment which allows the programmer
to edit scripts, and evaluate arbitrary Haskell expressions. Hugs is based sig-
nificantly on Mark Jones’ Gofer interpreter. More information about the Hugs
interpreter can be found on the following web-page: www.haskell.org/hugs.
The following chapter serves as a reference guide to the Haskell language
(specifically Haskell 98). In particular it concentrates on the content of the
Haskell Prelude, which is a standard library accessible by all Haskell programs.
∗ [email protected]
1 Miranda is a trademark of Research Software, Ltd.
2 Haskell Users’ Gofer System
1
The chapter does not give complete coverage to the whole Prelude, but in-
stead concentrates on those aspects most useful to Haskell beginners (however
it should serve as a valuable resource to experienced Haskell programmers as
well). The first part of the chapter deals with Prelude functions, the second
part of the chapter deals with Prelude operators, and the third part of the deals
with Prelude classes.
2
1.1 Functions from the Haskell Prelude
abs
type: abs :: Num a => a -> a
definition: abs x
| x >= 0 = x
| otherwise = -x
all
type: all :: (a -> Bool) -> [a] -> Bool
and
type: and :: [Bool] -> Bool
any
type: any :: (a -> Bool) -> [a] -> Bool
3
usage: Prelude> any (<11) [1..10]
True
Prelude> any isDigit "123abc"
True
Prelude> any isDigit "alphabetics"
False
atan
type: atan :: Floating a => a -> a
break
type: break :: (a -> Bool) -> [a] -> ([a],[a])
description: given a predicate and a list, breaks the list into two lists
(returned as a tuple) at the point where the predicate is
first satisfied. If the predicate is never satisfied then the
first element of the resulting tuple is the entire list and the
second element is the empty list ([]).
definition: break p xs
= span p’ xs
where
p’ x = not (p x)
ceiling
type: ceiling :: (RealFrac a, Integral b) => a -> b
description: returns the smallest integer not less than its argument.
usage: Prelude> ceiling 3.8
4
Prelude> ceiling (-3.8)
-3
chr
type: chr :: Int -> Char
4
description: applied to an integer in the range 0 – 255, returns the
character whose ascii code is that integer. It is the converse
of the function ord. An error will result if chr is applied
to an integer outside the correct range.
concat
type: concat :: [[a]] -> [a]
cos
type: cos :: Floating a => a -> a
digitToInt
type: digitToInt :: Char -> Int
div
5
type: div :: Integral a => a -> a -> a
doReadFile
type: doReadFile :: String -> String
drop
type: drop :: Int -> [a] -> [a]
description: applied to a number and a list, returns the list with the
specified number of elements removed from the front of the
list. If the list has less than the required number of elements
then it returns [].
definition: drop 0 xs = xs
drop _ [] = []
drop n (_:xs) | n>0 = drop (n-1) xs
drop _ _ = error "PreludeList.drop: negative argument"
dropWhile
type: dropWhile :: (a -> Bool) -> [a] -> [a]
6
usage: Prelude> dropWhile (<5) [1..10]
[5, 6, 7, 8, 9, 10]
elem
type: elem :: Eq a => a -> [a] -> Bool
description: applied to a value and a list returns True if the value is in
the list and False otherwise. The elements of the list must
be of the same type as the value.
definition: elem x xs = any (== x) xs
usage: Prelude> elem 5 [1..10]
True
Prelude> elem "rat" ["fat", "cat", "sat", "flat"]
False
error
type: error :: String -> a
description: applied to a string creates an error value with an associated
message. Error values are equivalent to the undefined value
(undefined), any attempt to access the value causes the
program to terminate and print the string as a diagnostic.
definition: defined internally.
usage: error "this is an error message"
exp
type: exp :: Floating a => a -> a
description: the exponential function (exp n is equivalent to en ).
definition: defined internally.
usage: Prelude> exp 1
2.71828
filter
type: filter :: (a -> Bool) -> [a] -> [a]
description: applied to a predicate and a list, returns a list containing
all the elements from the argument list that satisfy the
predicate.
definition: filter p xs = [k | k <- xs, p k]
usage: Prelude> filter isDigit "fat123cat456"
"123456"
flip
type: flip :: (a -> b -> c) -> b -> a -> c
7
description: applied to a binary function, returns the same function with
the order of the arguments reversed.
definition: flip f x y = f y x
floor
type: floor :: (RealFrac a, Integral b) => a -> b
description: returns the largest integer not greater than its argument.
foldl
type: foldl :: (a -> b -> a) -> a -> [b] -> a
definition: foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldl1
type: foldl1 :: (a -> a -> a) -> [a] -> a
foldr
type: foldr :: (a -> b -> b) -> b -> [a] -> b
8
foldr op r [a, b, c] → a ‘op‘ (b ‘op‘ (c
‘op‘ r))
definition: foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
usage: Prelude> foldr (++) [] ["con", "cat", "en", "ate"]
"concatenate"
foldr1
type: foldr1 :: (a -> a -> a) -> [a] -> a
description: folds right over non–empty lists.
definition: foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
usage: Prelude> foldr1 (*) [1..10]
3628800
fromInt
type: fromInt :: Num a => Int -> a
description: Converts from an Int to a numeric type which is in the
class Num.
usage: Prelude> (fromInt 3)::Float
3.0
fromInteger
type: fromInteger :: Num a => Integer -> a
description: Converts from an Integer to a numeric type which is in
the class Num.
usage: Prelude> (fromInteger 10000000000)::Float
1.0e+10
fst
type: fst :: (a, b) -> a
description: returns the first element of a two element tuple.
definition: fst (x, _) = x
usage: Prelude> fst ("harry", 3)
"harry"
head
type: head :: [a] -> a
description: returns the first element of a non–empty list. If applied to
an empty list an error results.
9
definition: head (x:_) = x
id
type: id :: a -> a
definition: id x = x
usage: Prelude> id 12
12
Prelude> id (id "fred")
"fred"
Prelude> (map id [1..10]) == [1..10]
True
init
type: init :: [a] -> [a]
description: returns all but the last element of its argument list. The
argument list must have at least one element. If init is
applied to an empty list an error occurs.
isAlpha
type: isAlpha :: Char -> Bool
isDigit
type: isDigit :: Char -> Bool
10
definition: isDigit c = c >= ’0’ && c <= ’9’
usage: Prelude> isDigit ’1’
True
Prelude> isDigit ’a’
False
isLower
type: isLower :: Char -> Bool
description: applied to a character argument, returns True if the char-
acter is a lower case alphabetic, and False otherwise.
definition: isLower c = c >= ’a’ && c <= ’z’
usage: Prelude> isLower ’a’
True
Prelude> isLower ’A’
False
Prelude> isLower ’1’
False
isSpace
type: isSpace :: Char -> Bool
description: returns True if its character argument is a whitespace char-
acter and False otherwise.
definition: isSpace c = c == ’ ’ || c == ’\t’ || c == ’\n’ ||
c == ’\r’ || c == ’\f’ || c == ’\v’
usage: Prelude> dropWhile isSpace " \nhello \n"
"hello \n"
isUpper
type: isUpper :: Char -> Bool
description: applied to a character argument, returns True if the char-
acter is an upper case alphabetic, and False otherwise.
definition: isDigit c = c >= ’A’ && c <= ’Z’
usage: Prelude> isUpper ’A’
True
Prelude> isUpper ’a’
False
Prelude> isUpper ’1’
False
iterate
type: iterate :: (a -> a) -> a -> [a]
description: iterate f x returns the infinite list [x, f(x), f(f(x)), ...].
11
definition: iterate f x = x : iterate f (f x)
last
type: last :: [a] -> a
length
type: length :: [a] -> Int
definition: length [] = 0
length (x:xs) = 1 + length xs
lines
type: lines :: String -> [String]
definition: lines [] = []
lines (x:xs)
= l : ls
where
(l, xs’) = break (== ’\n’) (x:xs)
ls
| xs’ == [] = []
| otherwise = lines (tail xs’)
log
type: log :: Floating a => a -> a
12
definition: defined internally.
map
type: map :: (a -> b) -> [a] -> [b]
description: given a function, and a list of any type, returns a list where
each element is the result of applying the function to the
corresponding element in the input list.
max
type: max :: Ord a => a -> a -> a
description: applied to two values of the same type which have an or-
dering defined upon them, returns the maximum of the two
elements according to the operator >=.
definition: max x y
| x >= y = x
| otherwise = y
maximum
type: maximum :: Ord a => [a] -> a
min
type: min :: Ord a => a -> a -> a
description: applied to two values of the same type which have an or-
dering defined upon them, returns the minimum of the two
elements according to the operator <=.
13
definition: min x y
| x <= y = x
| otherwise = y
minimum
type: minimum :: Ord a => [a] -> a
mod
type: mod :: Integral a => a -> a -> a
not
type: not :: Bool -> Bool
or
type: or :: [Bool] -> Bool
14
usage: Prelude> or [False, False, True, False]
True
Prelude> or [False, False, False, False]
False
Prelude> or []
False
ord
type: ord :: Char -> Int
description: applied to a character, returns its ascii code as an integer.
definition: defined internally.
usage: Prelude> ord ’A’
65
Prelude> (chr (ord ’A’)) == ’A’
True
pi
type: pi :: Floating a => a
description: the ratio of the circumference of a circle to its diameter.
definition: defined internally.
usage: Prelude> pi
3.14159
Prelude> cos pi
-1.0
putStr
type: putStr :: String -> IO ()
description: takes a string as an argument and returns an I/O action as
a result. A side-effect of applying putStr is that it causes
its argument string to be printed to the screen.
definition: defined internally.
usage: Prelude> putStr "Hello World\nI’m here!"
Hello World
I’m here!
product
type: product :: Num a => [a] -> a
description: applied to a list of numbers, returns their product.
definition: product xs = foldl (*) 1 xs
usage: Prelude> product [1..10]
3628800
15
repeat
type: repeat :: a -> [a]
definition: repeat x
= xs
where xs = x:xs
replicate
type: replicate :: Int -> a -> [a]
reverse
type: reverse :: [a] -> [a]
description: applied to a finite list of any type, returns a list of the same
elements in reverse order.
round
type: round :: (RealFrac a, Integral b) => a -> b
show
type: show :: Show a => a -> String
16
definition: defined internally.
usage: Prelude> "six plus two equals " ++ (show (6 + 2))
"six plus two equals 8"
sin
type: sin :: Floating a => a -> a
description: the trigonometric sine function, arguments are interpreted
to be in radians.
definition: defined internally.
usage: Prelude> sin (pi/2)
1.0
Prelude> ((sin pi)^2) + ((cos pi)^2)
1.0
snd
type: snd :: (a, b) -> b
description: returns the second element of a two element tuple.
definition: snd (_, y) = y
usage: Prelude> snd ("harry", 3)
3
sort
type: sort :: Ord a => [a] -> [a]
description: sorts its argument list in ascending order. The items in the
list must be in the class Ord.
usage: List> sort [1, 4, -2, 8, 11, 0]
[-2,0,1,4,8,11]
note: This is not defined within the Prelude. You must import
the List.hs module to use this function.
span
type: span :: (a -> Bool) -> [a] -> ([a],[a])
description: given a predicate and a list, splits the list into two lists
(returned as a tuple) such that elements in the first list
are taken from the head of the list while the predicate is
satisfied, and elements in the second list are the remaining
elements from the list once the predicate is not satisfied.
definition: span p [] = ([],[])
span p xs@(x:xs’)
| p x = (x:ys, zs)
| otherwise = ([],xs)
where (ys,zs) = span p xs’
17
usage: Prelude> span isDigit "123abc456"
("123", "abc456")
splitAt
type: splitAt :: Int -> [a] -> ([a],[a])
description: given an integer (positive or zero) and a list, splits the list
into two lists (returned as a tuple) at the position corre-
sponding to the given integer. If the integer is greater than
the length of the list, it returns a tuple containing the en-
tire list as its first element and the empty list as its second
element.
sqrt
type: sqrt :: Floating a => a -> a
subtract
type: subtract :: Num a => a -> a -> a
sum
type: sum :: Num a => [a] -> a
18
usage: Prelude> sum [1..10]
55
tail
type: tail :: [a] -> [a]
description: applied to a non–empty list, returns the list without its
first element.
definition: tail (_:xs) = xs
usage: Prelude> tail [1,2,3]
[2,3]
Prelude> tail "hugs"
"ugs"
take
type: take :: Int -> [a] -> [a]
description: applied to an integer (positive or zero) and a list, returns
the specified number of elements from the front of the list.
If the list has less than the required number of elements,
take returns the entire list.
definition: take 0 _ = []
take _ []= []
take n (x:xs)
| n > 0 = x : take (n-1) xs
take _ _ = error "PreludeList.take: negative argument"
usage: Prelude> take 4 "goodbye"
"good"
Prelude> take 10 [1,2,3]
[1,2,3]
takeWhile
type: takewhile :: (a -> Bool) -> [a] -> [a]
description: applied to a predicate and a list, returns a list containing
elements from the front of the list while the predicate is
satisfied.
definition: takeWhile p [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
usage: Prelude> takeWhile (<5) [1, 2, 3, 10, 4, 2]
[1, 2, 3]
tan
type: tan :: Floating a => a -> a
19
description: the trigonometric function tan, arguments are interpreted
to be in radians.
toLower
type: toLower :: Char -> Char
definition: toLower c
| isUpper c = toEnum (fromEnum c - fromEnum ’A’ + fromEnum ’a’)
| otherwise = c
toUpper
type: toUpper :: Char -> Char
definition: toUpper c
| isLower c = toEnum (fromEnum c - fromEnum ’a’ + fromEnum ’A’)
| otherwise = c
truncate
type: truncate :: (RealFrac a, Integral b) => a -> b
20
note:
unlines
type: unlines :: [String] -> String
description: converts a list of strings into a single string, placing a new-
line character between each of them. It is the converse of
the function lines.
definition: unlines xs
= concat (map addNewLine xs)
where
addNewLine l = l ++ "\n"
usage: Prelude> unlines ["hello world", "it’s me,", "eric"]
"hello world\nit’s me,\neric\n"
until
type: until :: (a -> Bool) -> (a -> a) -> a -> a
description: given a predicate, a unary function and a value, it recur-
sively re–applies the function to the value until the pred-
icate is satisfied. If the predicate is never satisfied until
will not terminate.
definition: until p f x
| p x = x
| otheriwise = until p f (f x)
usage: Prelude> until (>1000) (*2) 1
1024
unwords
type: unwords :: [String] -> String
description: concatenates a list of strings into a single string, placing a
single space between each of them.
definition: unwords [] = []
unwords ws
= foldr1 addSpace ws
where
addSpace w s = w ++ (’ ’:s)
usage: Prelude> unwords ["the", "quick", "brown", "fox"]
"the quick brown fox"
words
type: words :: String -> [String]
description: breaks its argument string into a list of words such that
each word is delimited by one or more whitespace charac-
ters.
21
definition: words s
| findSpace == [] = []
| otherwise = w : words s’’
where
(w, s’’) = break isSpace findSpace
findSpace = dropWhile isSpace s
zip
type: zip :: [a] -> [b] -> [(a,b)]
description: applied to two lists, returns a list of pairs which are formed
by tupling together corresponding elements of the given
lists. If the two lists are of different length, the length of
the resulting list is that of the shortest.
definition: zip xs ys
= zipWith pair xs ys
where
pair x y = (x, y)
zipWith
type: zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
22
1.2 A description of standard Haskell operators
Operators are simply functions of one or two arguments. Operators usually get
written between their arguments (called infix notation), rather than to the left
of them. Many operators have symbolic names (like + for plus), however this is
out of convention rather than necessity. Others have completely textual names
(such as ‘div‘ for integer division).
The following table lists many useful operators defined in the Prelude. Def-
initions of associativity and binding power are given after the table.
23
Associativity: sequences of operator applications are allowed in Haskell for
the convenience of the programmer. However, in some circumstances the mean-
ing of such a sequence can be ambiguous. For example, we could interpret the
expression 8 - 2 - 1 in two ways, either as (8 - 2) - 1, or as 8 - (2 - 1)
(each interpretation having a different value). Associativity tells us whether a
sequence of a particular operator should be bracketed to the left or to the right.
As it happens, the minus operator (-) is left associative, and so Haskell chooses
the first of the alternative interpretations as the meaning of the above expres-
sion. The choice of associativity for an operator is quite arbitrary, however,
they usually follow conventional mathematical notation. Note that some opera-
tors are non-associative, which means that they cannot be applied in sequence.
For example, the equality operator (==) is non–associative, and therefore the
following expression is not allowed in Haskell: 2 == (1 + 1) == (3 - 1).
24
notes: (f.g.h) x is equivalent to f (g (h x)).
**
description: raises its first argument to the power of its second argu-
ment. The arguments must be in the Floating numerical
type class, and the result will also be in that class.
usage: Prelude> 3.2**pi
38.6345
^
description: raises its first argument to the power of its second argu-
ment. The first argument must be a member of the Num
typeclass, and the second argument must be a member of
the Integral typeclass. The result will be of the same type
as the first argument.
usage: Prelude> 3.2^4
104.858
%
description: takes two numbers in the Integral typeclass and returns
the most simple ratio of the two.
usage: Prelude> 20 % 4
5 % 1
Prelude> (5 % 4)^2
25 % 16
*
description: returns the multiple of its two arguments.
usage: Prelude> 6 * 2.0
12.0
/
description: returns the result of dividing its first argument by its sec-
ond. Both arguments must in the type class Fractional.
usage: Prelude> 12.0 / 2
6.0
‘div‘
description: returns the integral division of the first argument by the
second argument. Both arguments must be in the type
class Integral.
usage: Prelude> 10 ‘div‘ 3
3
Prelude> 3 ‘div‘ 10
0
25
notes: ‘div‘ is integer division such that the result is truncated
towards negative infinity.
‘mod‘
description: returns the integral remainder after dividing the first argu-
ment by the second. Both arguments must be in the type
class Integral.
usage: Prelude> 3 + 4
7
Prelude> (4 % 5) + (1 % 5)
1 % 1
usage: Prelude> 4 - 3
1
Prelude> 4 - (-3)
7
++
description: appends its second list argument onto the end of its first
list argument.
26
usage: Prelude> [1,2,3] ++ [4,5,6]
[1,2,3,4,5,6]
Prelude> "foo " ++ "was" ++ " here"
"foo was here"
/=
description: is True if its first argument is not equal to its second ar-
gument, and False otherwise. Equality is defined by the
== operator. Both of its arguments must be in the Eq type
class.
usage: Prelude> 3 /= 4
True
Prelude> [1,2,3] /= [1,2,3]
False
==
description: is True if its first argument is equal to its second argu-
ment, and False otherwise. Equality is defined by the ==
operator. Both of its arguments must be in the Eq
usage: Prelude> 3 == 4
False
Prelude> [1,2,3] == [1,2,3]
True
<
description: returns True if its first argument is strictly less than its
second argument, and False otherwise. Both arguments
must be in the type class Ord.
usage: Prelude> 1 < 2
True
Prelude> ’a’ < ’z’
True
Prelude> True < False
False
<=
description: returns True if its first argument is less than or equal to its
second argument, and False otherwise. Both arguments
must be in the type class Ord.
usage: Prelude> 3 <= 4
True
Prelude> 4 <= 4
True
Prelude> 5 <= 4
False
>
27
description:
usage: returns True if its first argument is strictly greater than its
second argument, and False otherwise. Both arguments
must be in the type class Ord.
Prelude> 2 > 1
True
Prelude> ’a’ > ’z’
False
Prelude> True > False
True
>=
description:
Prelude> 4 >= 3
True
Prelude> 4 >= 4
True
Prelude> 4 >= 5
False
‘elem‘
‘notElem‘
&&
28
usage: Prelude> True && True
True
Prelude> (3 < 4) && (4 < 5) && False
False
||
29
1.4 Type Classes from the Haskell Prelude
Eq
description: Types which are instances of this class have equality defined
upon them. This means that all elements of such types can
be compared for equality.
notes: Functions which use the equality operators (==, /=) or the
functions elem or notElem will often be subject to the Eq
type class, thus requiring the constraint Eq a => in the
type signature for that function.
Ord
description: Types which are instances of this class have a complete
ordering defined upon them.
notes: Functions which use the comparison operators (>, <, >=,
<=), or the functions max, min, maximum or minimum will
often be subject to the Ord type class, thus requiring the
constraint Ord a => in the type signature for that function.
Enum
description: Types which are instances of this class can be enumerated.
This means that all elements of such types have a mapping
to a unique integer, thus the elements of the type must be
sequentially ordered.
instances: • Bool
• Char
• Int
• Integer
• Float
• Double
Show
description: Types which are instances of this class have a printable
representation. This means that all elements of such types
can be given as arguments to the function show.
30
notes: Functions which use the function show will often be subject
to the Show type class, thus requiring the constraint Show
a => in the type signature for that function.
Read
description: Types which are instances of this class allow a string rep-
resentation of all elements of the type to be converted to
the corresponding element.
instances: • All Prelude types except IO and functions.
notes: Functions which use the function read will often be subject
to the Read type class, thus requiring the constraint Read
a => in the type signature for that function.
Num
description: This is the parent class for all the numeric classes. Any type
which is an instance of this class must have basic numeric
operators (such as plus, minus and multiply) defined on
them, and must be able to be converted from an Int or
Integer to an element of the type.
instances: • Int
• Integer
• Float
• Double
notes: Functions which perform operations which are applicable to
all numeric types, but not to other non–numeric types will
often be subject to the Num type class, thus requiring the
constraint Num a => in the type signature for that function.
Real
description: This class covers all the numeric types whose elements can
be expressed as a ratio.
instances: • Int
• Integer
• Float
• Double
Fractional
description: This class covers all the numeric types whose elements are
fractional. All such types must have division defined upon
them, they must have a reciprocal, and must be convertible
from rational numbers, and double precision floating point
numbers.
instances: • Float
31
• Double
notes: Functions which use the division operator (/) will often be
subject to the Fractional type class, thus requiring the
constraint Fractional a => in the type signature for that
function.
Integral
description: This class covers all the numeric types whose elements are
integral.
instances: • Int
• Integer
notes: Functions which use the operators div or mod will often
be subject to the Integral type class, thus requiring the
constraint Integral a => in the type signature for that
function.
Floating
description: This class covers all the numeric types whose elements are
floating point numbers.
instances: • Float
• Double
32
Eq Show
Ord Num
Integral Floating
Read
33