Haskell Base Library Quick Reference

This page lists classes, types and functions that we will often use in our course. For the complete story, see the full library documentation at haskell.org.

Quick jump:

Type classes

class Eq e

Instances: All basic types except functions
Minimal definition: either (==) or (/=)

(==), (/=) :: e → e → Bool
Equality and inequality operators.

class Ord o (superclass: Eq)

Instances: All basic types except functions
Minimal definition: either compare or (<=)

(<), (<=), (>), (>=) :: o → o → Bool
Comparison operators.
compare :: o → o → Ordering
Compare two values, returning an Ordering (i.e. LT, EQ, or GT).
min, max :: o → o → o
Return the minimum or maximum of two values.

class Enum e

Instances: Bool, Char, Int, Integer, Float, Double
Minimal definition: fromEnum, toEnum

An enumerable type that can be used in ranges such as [1 .. 5].

pred :: e → e
succ :: e → e
Predecessor and successor functions.
fromEnum :: e -> Int
toEnum :: Int -> e
Convert an enumerable value from and to an Int.

class Bounded b

Instances: Bool, Char, Int

minBound :: b
maxBound :: b
Lower and upper bounds for a type.

class Read r

Instances: All basic types except functions

read :: String → r
Parse a value from a string.

class Show s

Instances: All basic types except functions

show :: sString
Convert a value to its string representation.

Numeric type classes

class Num n

Instances: Int, Integer, Float, Double
Minimal definition
: (+), (*), abs, signum, fromInteger, ((-) | negate)

(+), (-), (*) :: n → n → n
Addition, subtraction, and multiplication operators.
abs :: n → n
Absolute value.
fromInteger :: Integer -> n
Convert an Integer to any numeric type.
fromInteger 0 should be the additive identity; fromInteger 1 should be the multiplicative identity.
negate :: n → n
Unary negation.
signum :: n -> n
Compute the sign of a number, i.e. -1 if the number is negative, 0 if is it zero, or + 1 if it is positive.

class Integral i (superclasses: Num, Ord, Enum)

Instances: Int, Integer

div, mod :: i → i → i
Integer division (truncating toward -∞) and modulus (always non-negative).
divMod :: i → i → (i, i)
divMod a b returns the pair (div i b, mod i b).
toInteger :: i → Integer
Convert any Integral type to an Integer.

class Fractional f (superclass: Num)

Instances: Float, Double

(/) :: f → f → f
The division operator.
recip :: f -> f
recip x returns the reciprocal of x, i.e. 1 / x.

class RealFrac r (superclasses: Fractional, Ord)

Instances: Float, Double

ceiling :: Integral i => r → i
ceiling x returns the smallest integer that is not less than x.
floor :: Integral i => r → i
floor x returns the greatest integer that is not greater than x.
round :: Integral i => r → i
round x rounds x to the nearest integer (or to the even integer if x is halfway between integers).

class Floating f (superclass: Fractional)

Instances: Float, Double

(**) :: f → f → f
Exponentiation to a Floating power.
cos :: f → f
exp :: f → f
log :: f → f
pi :: f
sin :: f → f
sqrt :: f → f
tan :: f → f
Standard numeric functions.

class RealFloat r (superclasses: RealFrac, Floating)

Instances: Float, Double

atan2 :: r -> r -> r
atan2 y x returns the angle of the vector from the origin to the point (x, y), in the range [-π, π].
isInfinite :: r -> Bool
True if r is positive or negative infinity.
isNan :: r -> Bool
True if r is NaN.

Numbers

type Int

Instance of: Integral

A fixed-length signed integer. In GHC, this is a 64-bit value.

type Integer

Instance of: Integral

A signed integer of arbitrary size.

type Float
type Double

Instance of: RealFrac

Single- and double-precision floating-point numbers.

numeric functions

(^) :: (Num n, Integral i) => n → i → n
Exponentiation to an integer power.
even :: Integral i => i → Bool
True if a number is even.
fromIntegral :: (Integral i, Num n) => i → n
Convert an integral value to a number of any type. Defined as
fromIntegral i = fromInteger (toInteger i)
gcd :: Integral i => i → i → i
The greatest common divisor function.
lcm :: Integral i => i → i → i
The least common multiple function.
odd :: Integral i => i → Bool
True if a number is odd.

Booleans

type Bool

Instance of: Bounded

A value that is either True or False.

(&&) :: Bool → Bool → Bool
(||) :: Bool → Bool → Bool
Logical AND and OR operators.
not :: Bool → Bool
Logical negation.

Characters

type Char

Instance of: Bounded

Any Unicode character.

Import the Data.Char module to access these functions:

chr :: Int → Char
Convert a Unicode code point to a character. For example, chr(65) is 'A'.
digitToInt :: Char → Int
Convert a Char to the corresponding Int. For example, (digitToInt '7') == 7. Hexadecimal digits are supported.
intToDigit :: Int → Char
Convert an Int in the range 0..15 to the corresponding Char. For example, (intToDigit 7) == '7'. Hexadecimal digits are supported.
isAlpha :: Char → Bool
Check whether a character is a letter.
isAlphaNum :: Char → Bool
Check whether a character is a letter or digit.
isDigit :: Char → Bool
Check whether a character is a digit.
isLower :: Char → Bool
Check whether a character is a lowercase letter.
isSpace :: Char → Bool
Check whether a character is whitespace.
isUpper :: Char → Bool
Check whether a character is an uppercase letter.
ord :: Char → Int
Convert a character to a Unicode code point. For example, ord('A') is 65.
toLower :: Char → Char
Convert a character to lowercase.
toUpper :: Char → Char
Convert a character to uppercase.

Strings

type String = [Char]

A string is a list of characters.

lines :: String → [String]
Break a string into a list of lines, separated by newline characters.
unlines :: [String] → String
Join a list of strings into a single string, separating the strings with newline characters.
unwords :: [String] → String
Join a list of strings into a single string, separating the strings with spaces.
words :: String → [String]
Break a string into a list of words, separated by sequences of whitespace characters.

Additional string functions

Import the Text.Read module to access these functions:

readMaybe :: Read a => String -> Maybe a
Read a value from a string if possible; otherwise return Nothing.

Functions

(.) :: (b → c) → (a → b) → (a → c)
The function composition operator.
($) :: (a → b) → a → b
The function application operator. $ has low precedence and binds to the right, so

f $ g $ h x == f (g (h x))

const :: a -> b -> a
(const x) is a function that maps any value to x.
id :: a → a
The identity function.
until :: (a -> Bool) -> (a -> a) -> a -> a
until p f x applies f as many times as necessary to the value x until p holds, then returns the resulting value.

Ordering

Import the Data.Ord module to get this function:

comparing :: Ord a => (b → a) → b → b → Ordering
Given a function that extracts a comparison key, return a function that compares two values. In other words,
comparing p x y = compare (p x) (p y)
This is a convenient helper function for functions such as maximumBy and sortBy. For example,
sortBy (comparing snd) list
will sort a list of pairs by their second element.

Maybe

data Maybe t = Nothing | Just t

Import the Data.Maybe module to access these functions:

catMaybes :: [Maybe a] → [a]
Given a list of Maybes, return a list of all the Just values.
fromJust :: Maybe a → a
Return the value in a Just, throwing an error if the argument is Nothing.
fromMaybe :: a → Maybe a → a
Given a default value and a Maybe, return the default value if the Maybe is Nothing; otherwise return the value in the Maybe.
isJust :: Maybe a → Bool
Return True if the argument is a Just.
listToMaybe :: [a] → Maybe a
Return (Just a) where a is the first element of the list, or Nothing on an empty list.
maybe :: b -> (a -> b) -> Maybe a -> b
This function takes a default value, a function f, and a Maybe value. If the Maybe value is Nothing, it returns the default value. Otherwise, it applies f to the value inside the Maybe and returns the result.
maybeToList :: Maybe a → [a]
Return the singleton list [x] when given (Just x), or [] when given Nothing.
Import the Control.Applicative module to access this operator:
<|> :: Maybe a -> Maybe a -> Maybe a
Return a Just with the first of the given values that is a Just, if there is any; otherwise return Nothing.

Either

data Either a b = Left a | Right b

An Either holds a value in either a Left or a Right. Typically a Left represents an error, and a Right represents a successful computation. In this sense an Either is like a Maybe in which an error result has an associated value.

Tuples

type (a, b)
type (a, b, c)

fst :: (a, b) → a
snd :: (a, b) → b
Return the first or second component of a pair.

Import the Data.Tuple module to access this function:

swap :: (a, b) → (b, a)
Swap the components of a pair.

Lists

type [a]

A list of elements of type a.

Lists can be compared lexicographically.

[] :: [a]
The empty list.
(:) :: a → [a] → [a]
Prepend an element to a list.
(++) :: [a] → [a] → [a]
Append two lists.
(!!) :: [a] → Int → a
Return the nth element of a non-empty list.
all :: (a → Bool) → [a] → Bool
Return true if all values in a list (or other foldable) satisfy a predicate.
and :: [Bool] → Bool
Return true if all values in a boolean list (or other foldable) are true.
any :: (a → Bool) → [a] → Bool
Return true if any values in a list (or other foldable) satisfy a predicate.
concat :: [[a]] → [a]
Flatten a list (or other foldable) of lists into a single-level list.
concatMap :: (a → [b]) → [a] → [b]
Map a function over a list (or other foldable) and concatenate the resulting lists.
drop :: Int → [a] → [a]
Drop the first n elements from a list. If the list has fewer than n elements, the empty list is returned.
dropWhile :: (a → Bool) → [a] → [a]
Drop the longest prefix of elements that satisfy a predicate.
elem :: Eq a => a → [a] → Bool
Return true if a list (or other foldable) contains a given value.
filter :: (a → Bool) → [a] → [a]
Select all elements of a list that satisfy a predicate.
head :: [a] → a
Return the first element of a non-empty list.
init :: [a] → [a]
Return all elements of a list except the last element. The list must be non-empty.
iterate :: (a → a) → a → [a]
Return an infinite list generated by applying a function repeatedly:

iterate f x = [x, f x, f (f x), ...]

last :: [a] → a
Return the last element of a non-empty list.
length :: [a] → Int
Return the length of a list.
lookup :: Eq a => a → [(a, b)] → Maybe b
Look up a key in an association list, i.e. a list of (key, value) pairs.
map :: (a → b) → [a] → [b]
Apply a function to all elements of a list.
maximum :: Ord a => [a] → a
Return the largest value in a list (or other foldable).
minimum :: Ord a => [a] → a
Return the smallest value in a list (or other foldable).
null :: [a] → Bool
Return true if a list is empty.
or :: [Bool] → Bool
Return true if any values in a boolean list (or other foldable) are true.
product :: Num a => [a] → a
Return the product of a list (or other foldable) of numbers.
repeat :: a → [a]
Produce an infinite list of identical elements.
replicate :: Int → a → [a]
Produce a list with n identical elements.
reverse :: [a] → [a]
Reverse a list.
scanl :: (a -> b -> a) -> a -> [b] -> [a]
Like foldl, but returns a series of accumulated values rather than just the final value.
scanl1 :: (a -> a -> a) -> [a] -> [a]
A variant of scanl that has no starting value argument (and so it can't be applied to empty lists).
scanr :: (b -> a -> a) -> a -> [b] -> [a]
Like foldr, but returns a series of accumulated values rather than just the final value.
scanr1 :: (a -> a -> a) -> [a] -> [a]
A variant of scanr that has no starting value argument (and so it can't be applied to empty lists).
span :: (a → Bool) → [a] → ([a], [a])
Split a list into two lists using a predicate p. (span p l) is equivalent to (takeWhile p l, dropWhile p l).
splitAt :: Int → [a] → ([a], [a])
Split a list into two lists: the first contains the first n elements, and the second contains the remaining elements. (splitAt n xs) is equivalent to (take n xs, drop n xs).
sum :: Num a => [a] → a
Return the sum of a list (or other foldable) of numbers.
tail :: [a] → a
Return a list of all elements except the first element. The list must be non-empty.
take :: Int → [a] → [a]
Return the first n elements of a list. If the list has fewer than n elements, the entire list is returned.
takeWhile :: (a → Bool) → [a] → [a]
Return the longest prefix of elements that satisfy a predicate.
unzip :: [(a, b)] → ([a], [b])
Produce a pair of lists from a list of pairs.
unzip3 :: [(a, b, c)] → ([a], [b], [c])
Produce a triple of lists from a list of triples.
zip :: [a] → [b] → [(a, b)]
Produce a list of pairs from a pair of lists. If one of the input lists is shorter than the other, excess elements of the longer list are discarded.
zip3 :: [a] → [b] → [c] → [(a, b, c)]
zip3 takes three lists and returns a list of triples.
zipWith :: (a → b → c) → [a] → [b] → [c]
A generalized version of zip that combines corresponding elements using the given function rather than a tupling function.

Additional list functions

Import the Data.List module to access these functions:

(\\) :: Eq a => [a] → [a] → [a]
Return the difference of two sets represented by lists. The result will contain no duplicates unless duplicates were already present in the first of the input lists.
delete :: Eq a => a → [a] → [a]
Delete the first occurrence of a value from a list. If the value is not found, the list is returned unchanged:
> delete 7 [2, 3, 7, 1, 5]
[2,3,1,5]
> delete 6 [2, 3, 7, 1, 5]
[2,3,7,1,5]
elemIndex :: Eq a => a → [a] → Maybe Int
Return the index of the first element in the given list that is equal to the query element, or Nothing if there is no such element. Elements are indexed starting from 0.
find :: (a → Bool) → [a] → Maybe a
Return the first element in the list that satisfies the given predicate, or Nothing if there is none.
group :: Eq a => [a] → [[a]]
Group adjacent identical elements into sublists. For example,

group "Mississippi" == ["M","i","ss","i","ss","i","pp","i"]

groupBy :: (a → a → Bool) → [a] → [[a]]
Like group, but using a caller-specified equality test rather than (==).
inits :: [a] → [[a]]
Return all initial segments of a list. For example,

inits "abc" == ["","a","ab","abc"]

intercalate :: [a] → [[a]] → [a]
Insert a list of elements between each pair of lists in the second argument. Usually you will use this function when you want to join strings. For example, intercalate ", " ["abc", "def", "ghi"] returns "abc, def, ghi".
intersect :: Eq a => [a] → [a] → [a]
Return an intersection of two sets represented by lists. The result will contain no duplicates unless duplicates were already present in one of the original lists.
isInfixOf :: Eq a => [a] → [a] → Bool
Take two lists and return true if the first list is contained anywhere within the second.
isPrefixOf :: Eq a => [a] → [a] → Bool
Take two lists and return true if the first list is a prefix of the second.
isSuffixOf :: Eq a => [a] → [a] → Bool
Take two lists and return true if the first list is a suffix of the second.
maximumBy :: (a → a → Ordering) → [a] → a
Compute the largest element of a list with respect to a comparison function.
minimumBy :: (a → a → Ordering) → [a] → a
Compute the smallest element of a list with respect to a comparison function.
nub :: Eq a => [a] → [a]
Remove duplicate elements from a list. Note that this function runs in O(N2).
partition :: (a → Bool) → [a] → ([a], [a])
Given a predicate and a list, return lists of elements that do and do not satisfy the predicate. In other words,

(partition p list) == (filter p list, filter (\x → not (p x)) list)

permutations :: [a] → [[a]]
Given a list, return a list of all of its permutations.
singleton :: a -> [a]
Produce a list with a single element.
sort :: Ord a => [a] → [a]
Sort a list, keeping duplicates.
sortBy :: (a → a → Ordering) → [a] → [a]
Sort elements using a comparison function.
sortOn :: Ord b => (a -> b) -> [a] -> [a]
Sort by comparing the results of a key function applied to each element.
tails :: [a] → [[a]]
Return all final segments of a list. For example,

tails "abc" == ["abc", "bc", "c", ""]

transpose :: [[a]] → [[a]]
Transpose the rows and columns of a list of lists. For example, transpose [[1,2,3],[4,5,6]] returns [[1,4],[2,5],[3,6]].
union :: Eq a => [a] → [a] → [a]
Return a union of two sets represented by lists. The result will contain no duplicates unless duplicates were already present in one of the original lists.

Arrays

Import the Data.Array module to get these functions:

class Ix a (superclass: Ord)

A type class for types that can be array indices. Instances of this class include Int, Integer, Char, and tuples of types that belong to the same type class Ix.

data Array i e

The type of immutable arrays with indices of type i and elements of type e.
(!) :: Ix i => Array i e => i -> e
Return the value at a given index in an array.
accumArray :: Ix i => (a -> e -> a) -> a -> (i, i) -> [(i, e)] -> Array i a
Build an array from an accumulating function, an intial value, a range of indices and an association list. All values in the association list with the same key will be folded together using the given function, which performs a left fold.
array :: Ix i => (i, i) -> [(i, e)] -> Array i e
Build an array from a range of indices and an association list of values.
assocs :: Ix i => Array i e -> [(i, e)]
Return an assocation list of all indices and elements in index order.
elems :: Array i e -> [e]
Return a list of all elements in an array in index order.
listArray :: Ix i => (i, i) -> [e] -> Array i e
Build an array from a range of indices and a list of values.

Input/output

type IO a

An I/O action that returns a value of type a.

getContents :: IO String
Return all input as a single string, which is read lazily as needed.
getLine :: IO String
Read a line from standard input.
interact :: (String -> String) -> IO ()
Read all input as a single string, apply the given function to it, and write it to the output.
print :: Show a => a → IO ()
Print a value of any printable type, followed by a newline.
putStr :: String → IO ()
Write a string to standard output.
putStrLn :: String → IO ()
Write a string to standard output, followed by a newline character.
readLn :: Read a => IO a
Read a line and parse it into a value of any readable type.

Additional I/O-related functions

Import the System.IO module to access these functions:
data BufferMode = NoBuffering | LineBuffering | BlockBuffering
A buffering mode.
hSetBuffering :: Handle -> BufferMode -> IO ()
Set the buffering mode on an I/O stream. The following call will disable buffering on standard output:
      hSetBuffering stdout NoBuffering
That will cause Haskell to automatically flush the output after each call to putStr, so that it will be visible on the terminal before a following call to getLine.

Printf

Import the Text.Printf module to access this function:

printf :: PrintfType r => String → r
Produce a formatted string. For example:
>>> printf "%s, %d, %.4f" "hello" 123 pi
hello, 123, 3.1416
This version is largely compatible with other implementations of printf, such as in the standard C library. For example, in the format string above, %s represents a string, %d represents a integer and %.4f is a floating-point number rounded to four digits after the decimal point. See the official documentation for more details.

Functor

A functor is a type of value that can hold or produce other values.

class Functor f

Instances: [], Either, Maybe, IO, ((->) r)
Minimal definition: fmap

fmap :: (a -> b) -> f a -> f b
Apply a function to a functorial value.
(<$>) :: Functor f => (a -> b) -> f a -> f b
An infix synonym for fmap.
If the functor is a monad, f <$> a is the same as
do
    x <- a
    return (f x)

functor functions

(<$) :: a -> f b -> f a
Replace all values with the same value.
If the functor is a monad, a <$ b is the same as
do
    b
    return a

Import Data.Functor to get this function:

($>) :: f b -> a -> f a
A flipped version of (<$).

Foldable

class Foldable t

A foldable is a container that holds a sequence of values.

Instances: [], Maybe
Minimal definition: foldr

foldl :: (a → b → a) → a → t b → a
Fold a list (or other foldable) using a binary operator, from left to right. In the type signature above, a is the accumulator type and b is the list element type. The function passed to foldl takes the accumulator as its first argument, i.e. on the left.
foldl f a [x1, x2, x3, …, xn] = f (… (f (f (f a x1) x2) x3) … xn)
For example,

foldl (+) 0 [1, 2, 3] = (((0 + 1) + 2) + 3) = 6
foldl (-) 0 [1, 2, 3] = (((0 - 1) - 2) - 3) = -6

foldl1 :: (a → a → a) → t a → a
A variant of foldl that has no starting value argument (and so it can't be applied to empty lists).
foldr :: (b → a → a) → a → t b → a
Fold a list (or other foldable) using a binary operator, from right to left. In the type signature above, a is the accumulator type and b is the list element type. The function passed to foldr takes the accumulator as its second argument, i.e. on the right.
foldr f a [x1, x2, x3, …, xn] = f x1 (f x2 (f x3 (… (f xn a) …)))
For example,

foldr (+) 0 [1, 2, 3] = 1 + (2 + (3 + 0)) = 6
foldr (-) 0 [1, 2, 3] = 1 - (2 - (3 - 0)) = 2

foldr1 :: (a → a → a) → t a → a
A variant of foldr that has no starting value argument (and so it can't be applied to empty lists).

Applicative

class Applicative f (superclass: Functor)

Instances: [], Either, Maybe, IO, ((->) r)

An applicative is a functor in which a value holding a function can be applied to another value.

pure :: a -> f a
Produce an applicative value.
(<*>) :: f (a -> b) -> f a -> f b
Apply one applicative to another.
If the applicative is a monad, a <*> b is the same as
do
    f <- a
    x <- b
    return (f x)
(*>) :: m a -> m b -> m b
Compose two actions, discarding any value produced by the first.
If the applicative is a monad, a *> b is the same as
do
    a
    b
(<*) :: m a -> m b -> m b
Compose two actions, discarding any value produced by the second.
If the applicative is a monad, a <* b is the same as
do
    x <- a
    b

    return x

Monad

A monad is a type of value that allows actions to be composed, as in a 'do' block.

class Monad m (superclass: Applicative)

Instances: [], Either, Maybe, IO, ((->) r)

return :: a -> m a
Produce a monadic value.
(>>=) :: m a -> (a -> m b) -> m b
Compose two actions, passing a value produced by the first as an argument to the second.
a >>= f is the same as
do
    x <- a
    f x

monad functions

mapM :: Monad m => (a → m b) → [a] → m [b]
Map a function that returns a monadic value over a list, then combine the results into a single monadic value.
mapM_ :: Monad m => (a → m b) → [a] → m ()
Like mapM, but ignores the resulting values.
sequence :: Monad m => [m a] → m [a]
Combine a list of monadic values into a single monadic value.
sequence [a, b, c] is the same as
do
  x <- a
  y <- b
  z <- c
  return [x, y, z]
sequence_ :: Monad m => [m a] → m ()
Like sequence, but ignores the resulting values.

Import the Control.Monad module to access these functions:

ap :: Monad m => m (a -> b) -> m a -> m b
Apply two monadic values. (This is generally the same as <*>.)
ap a b is the same as
do
    f <- a
    x <- b
    return (f x)
forM :: Monad m => [a] → (a → m b) → m [b]
Like mapM, but with the arguments flipped.
forM_ :: Monad m => [a] → (a → m b) → m ()
Like mapM_, but with the arguments flipped.
guard :: Alternative f => Bool -> f ()
Use this function to add a guard to a 'do' block.
liftM :: Monad m => (a -> b) -> m a -> m b
Apply a function to a monadic value. (This is generally the same as fmap.)
liftM f a is equivalent to
do
  x <- a
  return (f x)
replicateM :: Applicative m => Int -> m a -> m [a]
Apply an action a number of times, then return a list of the results.
replicateM_ :: Applicative m => Int -> m a -> m ()
Like replicateM, but ignores the resulting values.
when :: Monad m => Bool → m () → m ()
A conditional for monadic values, useful for I/O actions. Equivalent to
when p v = if p then v else return ()

Reader

Import the Control.Monad.Reader module to access this monad:

type Reader r a

A computation with a readable environment of type r.

ask :: Reader r r
Return the environment.
asks :: (r -> a) -> Reader r a
Return a projection of the current environment.
runReader :: Reader r a -> r -> a
Run a reader computation in the given environment.

State

Import the Control.Monad.State module to access this monad:

type State s a

A stateful computation with a state of type s.

get :: State s s
Return the current state.
gets :: (s -> a) -> State s a
Return a projection of the current state.
put :: s -> State s ()
Replace the state inside the monad.
runState :: State s a -> s -> (a, s)
Run a computation, returning its result and the final state.

Writer

Import the Control.Monad.Writer module to access this monad:

type Writer w a

A computation that can produce output of type w, which must implement the Monoid type class.

runWriter :: Writer w a -> (a, w)
Run a writer computation, returning its result and the collected output.
tell :: w -> Writer w ()
Append to the monad's output.

Paths

type FilePath = String

A FilePath represents a filename.

Import the System.FilePath module to access these functions:

combine :: FilePath → FilePath → FilePath
(</>) :: FilePath → FilePath → FilePath
Combine two paths. The infix operator </> is a synonym for the combine function. For example,
"mydir" </> "myfile.txt"
will produce "mydir/myfile.txt" on Unix or macOS, and "mydir\myfile.txt" on Windows.
takeExtension :: FilePath → String
Return a filename's extension. For example, takeExtension "mydir/myfile.png" will return ".png".

Files

readFile :: FilePath → IO String
Read a file (lazily) and return its contents as a string.
writeFile :: FilePath → String → IO ()
Write a string to a file.

Directories

Import the System.Directory module to access these functions:

doesDirectoryExist :: FilePath → IO Bool
Return True if the given path exists and is a directory (i.e. not a file), otherwise False.
doesFileExist :: FilePath → IO Bool
Return True if the given path exists and is a file (i.e. not a directory), otherwise False.
listDirectory :: FilePath → IO [FilePath]
Return a list of the names of all files and directories in the given directory. (The special directories "." and ".." are not included in the returned list.)

Random numbers

To access these functions, you must install the random package and import the System.Random module.

class RandomGen g
Instances: StdGen

A random number generator.

next :: g -> (Int, g)

Return a random Int in a certain range, plus a new generator.

split :: g -> (g, g)

Split a random number generator into two generators.

data StdGen
Instance of: RandomGen

The standard random number generator implementation.

mkStdGen :: Int -> StdGen

Make a StdGen given a seed value.

newStdGen :: IO StdGen

Return a new random number generator with a system-dependent seed.

class Random r
Instances: All built-in numeric types, Bool, Char; also tuples of these types

A type that can be generated randomly.

random :: RandomGen g => g -> (r, g)

Generate a random value, together with a new generator. For bounded types, the range is normally the whole type. For fractional types, the range is normally the interval [0, 1).

randomR :: RandomGen g => (r, r) -> g -> (r, g)

Given a range (lo, hi) and a generator, returns a value in the interval [low, hi], together with a new generator.

randomRs :: RandomGen g => (r, r) -> g -> [r]

A plural variant of randomR, producing an infinite list of random values instead of returning a new generator.

randoms :: RandomGen g => g -> [r]

A plural variant of random, producing an infinite list of random values instead of returning a new generator.

Environment

Import the System.Environment module to access this function:

getArgs :: IO [String]
Return a list of the program's command-line arguments.

Debugging

Import the Debug.Trace module to access this function:

trace :: String → a → a
(trace str x) outputs the given string, then returns x.

Miscellaneous

error :: String → a
Stop execution and display an error message.

Parsec

Import Text.Parsec and Text.Parsec.String to access these functions.

type Parser a
A parser that returns a value of type a.
<|> :: Parser a -> Parser a -> Parser a
p <|> q first tries p. If it succeeds, its value is returned. If p fails without consuming any input, q is tried.
char :: Char -> Parser Char
Parse the given character.
digit :: Parser Char
Parse and return a ASCII digit.
letter :: Parser Char
Parse and return an alphabetic character.
many :: Parser a -> Parser [a]
Apply a parser zero or more times, and return a list of the returned values.
many1 :: Parser a -> Parser [a]
Apply a parser one or more times, and return a list of the returned values.
oneOf :: String -> Parser Char
Parse any of the characters in the given string.
parse :: Parser a -> String -> String -> Either ParseError a
parse p filePath input runs the parser p on the given input. filePath is only used in error reporting, and may be the empty string. Returns a value of type Right a if the parse succeeds, otherwise a Left ParseError.
spaces :: Parser ()
Skip zero or more whitespace characters.
string :: String -> Parser String
Parse the given string and return it.
string' :: String -> Parser String
Like string, but does not consume any input if the parse fails.
try :: Parser a -> Parser a
Run a parser. If it succeeds, return its value; if it fails, fail and pretend that no input has been consumed.

Parsec.Expr

Import Text.Parsec.Expr to access these functions.

data Assoc = AssocNone | AssocLeft | AssocRight
The associativity of an operator.
data Operator a =
      Infix (Parser (a -> a -> a)) Assoc
    | Prefix (Parser (a -> a))
    | Postfix (Parser (a -> a))
An operator that works on values of type a.
(Actually Operator has additional type arguments, but I've omitted them from this documentation for simplicity. When you write a table of operators to pass to buildExpressionParser, you can avoid giving it an explicit type if you don't want to deal with these extra arguments.)
buildExpressionParser :: [[Operator a]] -> Parser a -> Parser a
Given a table of operators and a term parser, return a parser that can parse expressions. The table lists operators in order of descending precedence. All operators in a single sublist will have the same precedence.