Prelude
Contents
Description
The Haskell 2010 Prelude: a standard module imported by default into all Haskell modules. For more documentation, see the Haskell 2010 Report http://www.haskell.org/onlinereport/.
- Bool
- &&
- ||
- not
- otherwise :: Bool
- data Maybe a
- maybe :: b -> (a -> b) -> Maybe a -> b
- data Either a b
- either :: (a -> c) -> (b -> c) -> Either a b -> c
- Ordering
- Char
- type String = [Char]
- fst :: (a, b) -> a
- snd :: (a, b) -> b
- curry :: ((a, b) -> c) -> a -> b -> c
- uncurry :: (a -> b -> c) -> (a, b) -> c
- Eq
- Ord
- class Enum a where
- succ :: a -> a
- pred :: a -> a
- toEnum :: Int -> a
- fromEnum :: a -> Int
- enumFrom :: a -> [a]
- enumFromThen :: a -> a -> [a]
- enumFromTo :: a -> a -> [a]
- enumFromThenTo :: a -> a -> a -> [a]
- class Bounded a where
- Int
- Integer
- Float
- Double
- type Rational = Ratio Integer
- class (Eq a, Show a) => Num a where
- class (Num a, Ord a) => Real a where
- toRational :: a -> Rational
- class (Real a, Enum a) => Integral a where
- class Num a => Fractional a where
- (/) :: a -> a -> a
- recip :: a -> a
- fromRational :: Rational -> a
- class Fractional a => Floating a where
- class (Real a, Fractional a) => RealFrac a where
- class (RealFrac a, Floating a) => RealFloat a where
- floatRadix :: a -> Integer
- floatDigits :: a -> Int
- floatRange :: a -> (Int, Int)
- decodeFloat :: a -> (Integer, Int)
- encodeFloat :: Integer -> Int -> a
- exponent :: a -> Int
- significand :: a -> a
- scaleFloat :: Int -> a -> a
- isNaN :: a -> Bool
- isInfinite :: a -> Bool
- isDenormalized :: a -> Bool
- isNegativeZero :: a -> Bool
- isIEEE :: a -> Bool
- atan2 :: a -> a -> a
- subtract :: Num a => a -> a -> a
- even :: Integral a => a -> Bool
- odd :: Integral a => a -> Bool
- gcd :: Integral a => a -> a -> a
- lcm :: Integral a => a -> a -> a
- (^) :: (Num a, Integral b) => a -> b -> a
- (^^) :: (Fractional a, Integral b) => a -> b -> a
- fromIntegral :: (Integral a, Num b) => a -> b
- realToFrac :: (Real a, Fractional b) => a -> b
- class Monad m where
- class Functor f where
- fmap :: (a -> b) -> f a -> f b
- mapM :: Monad m => (a -> m b) -> [a] -> m [b]
- mapM_ :: Monad m => (a -> m b) -> [a] -> m ()
- sequence :: Monad m => [m a] -> m [a]
- sequence_ :: Monad m => [m a] -> m ()
- (=<<) :: Monad m => (a -> m b) -> m a -> m b
- id :: a -> a
- const :: a -> b -> a
- (.) :: (b -> c) -> (a -> b) -> a -> c
- flip :: (a -> b -> c) -> b -> a -> c
- ($) :: (a -> b) -> a -> b
- until :: (a -> Bool) -> (a -> a) -> a -> a
- asTypeOf :: a -> a -> a
- error
- undefined :: a
- seq
- ($!) :: (a -> b) -> a -> b
- map :: (a -> b) -> [a] -> [b]
- (++) :: [a] -> [a] -> [a]
- filter
- head
- last
- tail
- init
- null
- length
- !!
- reverse
- foldl
- foldl1 :: (a -> a -> a) -> [a] -> a
- foldr :: (a -> b -> b) -> b -> [a] -> b
- foldr1
- and
- or
- any
- all
- sum :: Num a => [a] -> a
- product :: Num a => [a] -> a
- concat
- concatMap
- maximum :: Ord a => [a] -> a
- minimum :: Ord a => [a] -> a
- scanl
- scanl1
- scanr
- scanr1
- iterate
- repeat
- replicate
- cycle
- take
- drop
- splitAt
- takeWhile
- dropWhile
- span
- break
- elem
- notElem
- lookup
- zip
- zip3
- zipWith
- zipWith3
- unzip
- unzip3
- lines :: String -> [String]
- words :: String -> [String]
- unlines :: [String] -> String
- unwords :: [String] -> String
- type ShowS = String -> String
- class Show a where
- shows :: Show a => a -> ShowS
- showChar :: Char -> ShowS
- showString :: String -> ShowS
- showParen :: Bool -> ShowS -> ShowS
- ReadS
- Read
- reads :: Read a => ReadS a
- readParen
- read :: Read a => String -> a
- lex
- IO
- putChar :: Char -> IO ()
- putStr :: String -> IO ()
- putStrLn :: String -> IO ()
- print :: Show a => a -> IO ()
- getChar :: IO Char
- getLine :: IO String
- getContents :: IO String
- interact :: (String -> String) -> IO ()
- FilePath
- readFile :: FilePath -> IO String
- writeFile :: FilePath -> String -> IO ()
- appendFile :: FilePath -> String -> IO ()
- readIO :: Read a => String -> IO a
- readLn :: Read a => IO a
- IOError
- ioError
- userError
- catch :: IO a -> (IOError -> IO a) -> IO a
Standard types, classes and related functions
Basic data types
The Maybe type encapsulates an optional value. A value of type
either contains a value of type Maybe aa (represented as ),
or it is empty (represented as Just aNothing). Using Maybe is a good way to
deal with errors or exceptional cases without resorting to drastic
measures such as error.
The Maybe type is also a monad. It is a simple kind of error
monad, where all errors are represented by Nothing. A richer
error monad can be built using the Data.Either.Either type.
The Either type represents values with two possibilities: a value of
type is either Either a b or Left a.
Right b
The Either type is sometimes used to represent a value which is
either correct or an error; by convention, the Left constructor is
used to hold an error value and the Right constructor is used to
hold a correct value (mnemonic: "right" also means "correct").
Tuples
curry :: ((a, b) -> c) -> a -> b -> cSource
curry converts an uncurried function to a curried function.
uncurry :: (a -> b -> c) -> (a, b) -> cSource
uncurry converts a curried function to a function on pairs.
Basic type classes
Class Enum defines operations on sequentially ordered types.
The enumFrom... methods are used in Haskell's translation of
arithmetic sequences.
Instances of Enum may be derived for any enumeration type (types
whose constructors have no fields). The nullary constructors are
assumed to be numbered left-to-right by fromEnum from 0 through n-1.
See Chapter 10 of the Haskell Report for more details.
For any type that is an instance of class Bounded as well as Enum,
the following should hold:
- The calls
andsuccmaxBoundshould result in a runtime error.predminBound -
fromEnumandtoEnumshould give a runtime error if the result value is not representable in the result type. For example,is an error.toEnum7 ::Bool -
enumFromandenumFromThenshould be defined with an implicit bound, thus:
enumFrom x = enumFromTo x maxBound
enumFromThen x y = enumFromThenTo x y bound
where
bound | fromEnum y >= fromEnum x = maxBound
| otherwise = minBound
Methods
the successor of a value. For numeric types, succ adds 1.
the predecessor of a value. For numeric types, pred subtracts 1.
Convert from an Int.
Convert to an Int.
It is implementation-dependent what fromEnum returns when
applied to a value that is too large to fit in an Int.
Used in Haskell's translation of [n..].
enumFromThen :: a -> a -> [a]Source
Used in Haskell's translation of [n,n'..].
enumFromTo :: a -> a -> [a]Source
Used in Haskell's translation of [n..m].
enumFromThenTo :: a -> a -> a -> [a]Source
Used in Haskell's translation of [n,n'..m].
The Bounded class is used to name the upper and lower limits of a
type. Ord is not a superclass of Bounded since types that are not
totally ordered may also have upper and lower bounds.
The Bounded class may be derived for any enumeration type;
minBound is the first constructor listed in the data declaration
and maxBound is the last.
Bounded may also be derived for single-constructor datatypes whose
constituent types are in Bounded.
Numbers
Numeric types
Numeric type classes
class (Eq a, Show a) => Num a whereSource
Basic numeric class.
Minimal complete definition: all except negate or (-)
Methods
Unary negation.
Absolute value.
Sign of a number.
The functions abs and signum should satisfy the law:
abs x * signum x == x
For real numbers, the signum is either -1 (negative), 0 (zero)
or 1 (positive).
fromInteger :: Integer -> aSource
Conversion from an Integer.
An integer literal represents the application of the function
fromInteger to the appropriate value of type Integer,
so such literals have type (.
Num a) => a
class (Num a, Ord a) => Real a whereSource
Methods
toRational :: a -> RationalSource
the rational equivalent of its real argument with full precision
class (Real a, Enum a) => Integral a whereSource
Methods
integer division truncated toward zero
integer remainder, satisfying
(x `quot` y)*y + (x `rem` y) == x
integer division truncated toward negative infinity
integer modulus, satisfying
(x `div` y)*y + (x `mod` y) == x
quotRem :: a -> a -> (a, a)Source
divMod :: a -> a -> (a, a)Source
toInteger :: a -> IntegerSource
conversion to Integer
class Num a => Fractional a whereSource
Fractional numbers, supporting real division.
Minimal complete definition: fromRational and (recip or ()
/)
Methods
fractional division
reciprocal fraction
fromRational :: Rational -> aSource
Conversion from a Rational (that is ).
A floating literal stands for an application of Ratio IntegerfromRational
to a value of type Rational, so such literals have type
(.
Fractional a) => a
class Fractional a => Floating a whereSource
Trigonometric and hyperbolic functions and related functions.
Minimal complete definition:
pi, exp, log, sin, cos, sinh, cosh,
asin, acos, atan, asinh, acosh and atanh
Methods
class (Real a, Fractional a) => RealFrac a whereSource
Extracting components of fractions.
Minimal complete definition: properFraction
Methods
properFraction :: Integral b => a -> (b, a)Source
The function properFraction takes a real fractional number x
and returns a pair (n,f) such that x = n+f, and:
-
nis an integral number with the same sign asx; and -
fis a fraction with the same type and sign asx, and with absolute value less than1.
The default definitions of the ceiling, floor, truncate
and round functions are in terms of properFraction.
truncate :: Integral b => a -> bSource
returns the integer nearest truncate xx between zero and x
round :: Integral b => a -> bSource
returns the nearest integer to round xx;
the even integer if x is equidistant between two integers
ceiling :: Integral b => a -> bSource
returns the least integer not less than ceiling xx
floor :: Integral b => a -> bSource
returns the greatest integer not greater than floor xx
class (RealFrac a, Floating a) => RealFloat a whereSource
Efficient, machine-independent access to the components of a floating-point number.
Minimal complete definition:
all except exponent, significand, scaleFloat and atan2
Methods
floatRadix :: a -> IntegerSource
a constant function, returning the radix of the representation
(often 2)
floatDigits :: a -> IntSource
a constant function, returning the number of digits of
floatRadix in the significand
floatRange :: a -> (Int, Int)Source
a constant function, returning the lowest and highest values the exponent may assume
decodeFloat :: a -> (Integer, Int)Source
The function decodeFloat applied to a real floating-point
number returns the significand expressed as an Integer and an
appropriately scaled exponent (an Int). If
yields decodeFloat x(m,n), then x is equal in value to m*b^^n, where b
is the floating-point radix, and furthermore, either m and n
are both zero or else b^(d-1) <= m < b^d, where d is the value
of . In particular, floatDigits x.
decodeFloat 0 = (0,0)
encodeFloat :: Integer -> Int -> aSource
encodeFloat performs the inverse of decodeFloat
the second component of decodeFloat.
significand :: a -> aSource
the first component of decodeFloat, scaled to lie in the open
interval (-1,1)
scaleFloat :: Int -> a -> aSource
multiplies a floating-point number by an integer power of the radix
True if the argument is an IEEE "not-a-number" (NaN) value
isInfinite :: a -> BoolSource
True if the argument is an IEEE infinity or negative infinity
isDenormalized :: a -> BoolSource
True if the argument is too small to be represented in
normalized format
isNegativeZero :: a -> BoolSource
True if the argument is an IEEE negative zero
True if the argument is an IEEE floating point number
a version of arctangent taking two real floating-point arguments.
For real floating x and y, computes the angle
(from the positive x-axis) of the vector from the origin to the
point atan2 y x(x,y). returns a value in the range [atan2 y x-pi,
pi]. It follows the Common Lisp semantics for the origin when
signed zeroes are supported. , with atan2 y 1y in a type
that is RealFloat, should return the same value as .
A default definition of atan yatan2 is provided, but implementors
can provide a more accurate implementation.
Numeric functions
lcm :: Integral a => a -> a -> aSource
is the smallest positive integer that both lcm x yx and y divide.
(^^) :: (Fractional a, Integral b) => a -> b -> aSource
raise a number to an integral power
fromIntegral :: (Integral a, Num b) => a -> bSource
general coercion from integral types
realToFrac :: (Real a, Fractional b) => a -> bSource
general coercion to fractional types
Monads and functors
The Monad class defines the basic operations over a monad,
a concept from a branch of mathematics known as category theory.
From the perspective of a Haskell programmer, however, it is best to
think of a monad as an abstract datatype of actions.
Haskell's do expressions provide a convenient syntax for writing
monadic expressions.
Minimal complete definition: >>= and return.
Instances of Monad should satisfy the following laws:
return a >>= k == k a m >>= return == m m >>= (\x -> k x >>= h) == (m >>= k) >>= h
Instances of both Monad and Functor should additionally satisfy the law:
fmap f xs == xs >>= return . f
The instances of Monad for lists, Data.Maybe.Maybe and System.IO.IO
defined in the Prelude satisfy these laws.
Methods
(>>=) :: m a -> (a -> m b) -> m bSource
Sequentially compose two actions, passing any value produced by the first as an argument to the second.
(>>) :: m a -> m b -> m bSource
Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.
Inject a value into the monadic type.
Fail with a message. This operation is not part of the
mathematical definition of a monad, but is invoked on pattern-match
failure in a do expression.
sequence :: Monad m => [m a] -> m [a]Source
Evaluate each action in the sequence from left to right, and collect the results.
sequence_ :: Monad m => [m a] -> m ()Source
Evaluate each action in the sequence from left to right, and ignore the results.
Miscellaneous functions
flip :: (a -> b -> c) -> b -> a -> cSource
takes its (first) two arguments in the reverse order of flip ff.
($) :: (a -> b) -> a -> bSource
Application operator. This operator is redundant, since ordinary
application (f x) means the same as (f . However, $ x)$ has
low, right-associative binding precedence, so it sometimes allows
parentheses to be omitted; for example:
f $ g $ h x = f (g (h x))
It is also useful in higher-order situations, such as ,
or map ($ 0) xs.
Data.List.zipWith ($) fs xs
until :: (a -> Bool) -> (a -> a) -> a -> aSource
yields the result of applying until p ff until p holds.
List operations
map :: (a -> b) -> [a] -> [b]Source
map f xs is the list obtained by applying f to each element
of xs, i.e.,
map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] map f [x1, x2, ...] == [f x1, f x2, ...]
(++) :: [a] -> [a] -> [a]Source
Append two lists, i.e.,
[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
If the first list is not finite, the result is the first list.
Reducing lists (folds)
foldr :: (a -> b -> b) -> b -> [a] -> bSource
foldr, applied to a binary operator, a starting value (typically
the right-identity of the operator), and a list, reduces the list
using the binary operator, from right to left:
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
Special folds
product :: Num a => [a] -> aSource
The product function computes the product of a finite list of numbers.
Building lists
Scans
Infinite lists
Sublists
Searching lists
Zipping and unzipping lists
Functions on strings
lines :: String -> [String]Source
lines breaks a string up into a list of strings at newline
characters. The resulting strings do not contain newlines.
words :: String -> [String]Source
words breaks a string up into a list of words, which were delimited
by white space.
Converting to and from String
Converting to String
Conversion of values to readable Strings.
Minimal complete definition: showsPrec or show.
Derived instances of Show have the following properties, which
are compatible with derived instances of Text.Read.Read:
- The result of
showis a syntactically correct Haskell expression containing only constants, given the fixity declarations in force at the point where the type is declared. It contains only the constructor names defined in the data type, parentheses, and spaces. When labelled constructor fields are used, braces, commas, field names, and equal signs are also used. - If the constructor is defined to be an infix operator, then
showsPrecwill produce infix applications of the constructor. - the representation will be enclosed in parentheses if the
precedence of the top-level constructor in
xis less thand(associativity is ignored). Thus, ifdis0then the result is never surrounded in parentheses; ifdis11it is always surrounded in parentheses, unless it is an atomic expression. - If the constructor is defined using record syntax, then
showwill produce the record-syntax form, with the fields given in the same order as the original declaration.
For example, given the declarations
infixr 5 :^: data Tree a = Leaf a | Tree a :^: Tree a
the derived instance of Show is equivalent to
instance (Show a) => Show (Tree a) where
showsPrec d (Leaf m) = showParen (d > app_prec) $
showString "Leaf " . showsPrec (app_prec+1) m
where app_prec = 10
showsPrec d (u :^: v) = showParen (d > up_prec) $
showsPrec (up_prec+1) u .
showString " :^: " .
showsPrec (up_prec+1) v
where up_prec = 5
Note that right-associativity of :^: is ignored. For example,
-
produces the stringshow(Leaf 1 :^: Leaf 2 :^: Leaf 3)"Leaf 1 :^: (Leaf 2 :^: Leaf 3)".
Methods
Arguments
| :: Int | the operator precedence of the enclosing
context (a number from |
| -> a | the value to be converted to a |
| -> ShowS |
Convert a value to a readable String.
showsPrec should satisfy the law
showsPrec d x r ++ s == showsPrec d x (r ++ s)
Derived instances of Text.Read.Read and Show satisfy the following:
-
(x,"")is an element of(.Text.Read.readsPrecd (showsPrecd x ""))
That is, Text.Read.readsPrec parses the string produced by
showsPrec, and delivers the value that showsPrec started with.
showChar :: Char -> ShowSSource
utility function converting a Char to a show function that
simply prepends the character unchanged.
showString :: String -> ShowSSource
utility function converting a String to a show function that
simply prepends the string unchanged.
Converting from String
read :: Read a => String -> aSource
The read function reads input from a string, which must be
completely consumed by the input process.
Basic Input and output
Simple I/O operations
Output functions
print :: Show a => a -> IO ()Source
The print function outputs a value of any printable type to the
standard output device.
Printable types are those that are instances of class Show; print
converts values to strings for output using the show operation and
adds a newline.
For example, a program to print the first 20 integers and their powers of 2 could be written as:
main = print ([(n, 2^n) | n <- [0..19]])
Input functions
getContents :: IO StringSource
The getContents operation returns all user input as a single string,
which is read lazily as it is needed
(same as hGetContents stdin).
interact :: (String -> String) -> IO ()Source
The interact function takes a function of type String->String
as its argument. The entire input from the standard input device is
passed to this function as its argument, and the resulting string is
output on the standard output device.
Files
readFile :: FilePath -> IO StringSource
The readFile function reads a file and
returns the contents of the file as a string.
The file is read lazily, on demand, as with getContents.
writeFile :: FilePath -> String -> IO ()Source
The computation writeFile file str function writes the string str,
to the file file.
appendFile :: FilePath -> String -> IO ()Source
The computation appendFile file str function appends the string str,
to the file file.
Note that writeFile and appendFile write a literal string
to a file. To write a value of any printable type, as with print,
use the show function to convert the value to a string first.
main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
Exception handling in the I/O monad
catch :: IO a -> (IOError -> IO a) -> IO aSource
The catch function establishes a handler that receives any IOError
raised in the action protected by catch. An IOError is caught by
the most recent handler established by catch. These handlers are
not selective: all IOErrors are caught. Exception propagation
must be explicitly provided in a handler by re-raising any unwanted
exceptions. For example, in
f = catch g (\e -> if IO.isEOFError e then return [] else ioError e)
the function f returns [] when an end-of-file exception
(cf. isEOFError) occurs in g; otherwise, the
exception is propagated to the next outer handler.
When an exception propagates outside the main program, the Haskell
system prints the associated IOError value and exits the program.
Non-I/O exceptions are not caught by this variant; to catch all
exceptions, use Control.Exception.catch from Control.Exception.