hx-0.4: Haskell extras (missing utility functions).

Safe HaskellSafe

Haskell.X.Prelude

Synopsis

Documentation

data Bool

Constructors

False 
True 

(&&) :: Bool -> Bool -> Bool

Boolean "and"

(||) :: Bool -> Bool -> Bool

Boolean "or"

not :: Bool -> Bool

Boolean "not"

otherwise :: Bool

otherwise is defined as the value True. It helps to make guards more readable. eg.

  f x | x < 0     = ...
      | otherwise = ...

data Maybe a

The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a), or it is empty (represented as Nothing). 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 Either type.

Constructors

Nothing 
Just a 

Instances

Monad Maybe 
Functor Maybe 
Typeable1 Maybe 
MonadPlus Maybe 
Applicative Maybe 
Foldable Maybe 
Traversable Maybe 
Alternative Maybe 
Eq a => Eq (Maybe a) 
Data a => Data (Maybe a) 
Ord a => Ord (Maybe a) 
Read a => Read (Maybe a) 
Show a => Show (Maybe a) 
Monoid a => Monoid (Maybe a)

Lift a semigroup into Maybe forming a Monoid according to http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be turned into a monoid simply by adjoining an element e not in S and defining e*e = e and e*s = s = s*e for all s ∈ S." Since there is no "Semigroup" typeclass providing just mappend, we use Monoid instead.

maybe :: b -> (a -> b) -> Maybe a -> b

The maybe function takes a default value, a function, and a Maybe value. If the Maybe value is Nothing, the function returns the default value. Otherwise, it applies the function to the value inside the Just and returns the result.

isJust :: Maybe a -> Bool

The isJust function returns True iff its argument is of the form Just _.

isNothing :: Maybe a -> Bool

The isNothing function returns True iff its argument is Nothing.

fromJust :: Maybe a -> a

The fromJust function extracts the element out of a Just and throws an error if its argument is Nothing.

fromMaybe :: a -> Maybe a -> a

The fromMaybe function takes a default value and and Maybe value. If the Maybe is Nothing, it returns the default values; otherwise, it returns the value contained in the Maybe.

listToMaybe :: [a] -> Maybe a

The listToMaybe function returns Nothing on an empty list or Just a where a is the first element of the list.

maybeToList :: Maybe a -> [a]

The maybeToList function returns an empty list when given Nothing or a singleton list when not given Nothing.

catMaybes :: [Maybe a] -> [a]

The catMaybes function takes a list of Maybes and returns a list of all the Just values.

mapMaybe :: (a -> Maybe b) -> [a] -> [b]

The mapMaybe function is a version of map which can throw out elements. In particular, the functional argument returns something of type Maybe b. If this is Nothing, no element is added on to the result list. If it just Just b, then b is included in the result list.

data Either a b

The Either type represents values with two possibilities: a value of type Either a b is either Left a or 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").

Constructors

Left a 
Right b 

Instances

Typeable2 Either 
Monad (Either e) 
Functor (Either a) 
Applicative (Either e) 
(Eq a, Eq b) => Eq (Either a b) 
(Data a, Data b) => Data (Either a b) 
(Ord a, Ord b) => Ord (Either a b) 
(Read a, Read b) => Read (Either a b) 
(Show a, Show b) => Show (Either a b) 

either :: (a -> c) -> (b -> c) -> Either a b -> c

Case analysis for the Either type. If the value is Left a, apply the first function to a; if it is Right b, apply the second function to b.

lefts :: [Either a b] -> [a]

Extracts from a list of Either all the Left elements All the Left elements are extracted in order.

rights :: [Either a b] -> [b]

Extracts from a list of Either all the Right elements All the Right elements are extracted in order.

partitionEithers :: [Either a b] -> ([a], [b])

Partitions a list of Either into two lists All the Left elements are extracted, in order, to the first component of the output. Similarly the Right elements are extracted to the second component of the output.

uneither :: Either a a -> aSource

If an Either contains the same types in Left and Right, unify it by dropping the Either wrapper.

data Char

The character type Char is an enumeration whose values represent Unicode (or equivalently ISO/IEC 10646) characters (see http://www.unicode.org/ for details). This set extends the ISO 8859-1 (Latin-1) character set (the first 256 characters), which is itself an extension of the ASCII character set (the first 128 characters). A character literal in Haskell has type Char.

To convert a Char to or from the corresponding Int value defined by Unicode, use toEnum and fromEnum from the Enum class respectively (or equivalently ord and chr).

isControl :: Char -> Bool

Selects control characters, which are the non-printing characters of the Latin-1 subset of Unicode.

isSpace :: Char -> Bool

Returns True for any Unicode space character, and the control characters \t, \n, \r, \f, \v.

isLower :: Char -> Bool

Selects lower-case alphabetic Unicode characters (letters).

isUpper :: Char -> Bool

Selects upper-case or title-case alphabetic Unicode characters (letters). Title case is used by a small number of letter ligatures like the single-character form of Lj.

isAlpha :: Char -> Bool

Selects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters). This function is equivalent to isLetter.

isAlphaNum :: Char -> Bool

Selects alphabetic or numeric digit Unicode characters.

Note that numeric digits outside the ASCII range are selected by this function but not by isDigit. Such digits may be part of identifiers but are not used by the printer and reader to represent numbers.

isPrint :: Char -> Bool

Selects printable Unicode characters (letters, numbers, marks, punctuation, symbols and spaces).

isDigit :: Char -> Bool

Selects ASCII digits, i.e. '0'..'9'.

isOctDigit :: Char -> Bool

Selects ASCII octal digits, i.e. '0'..'7'.

isHexDigit :: Char -> Bool

Selects ASCII hexadecimal digits, i.e. '0'..'9', 'a'..'f', 'A'..'F'.

isLetter :: Char -> Bool

Selects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters). This function is equivalent to isAlpha.

isMark :: Char -> Bool

Selects Unicode mark characters, e.g. accents and the like, which combine with preceding letters.

isNumber :: Char -> Bool

Selects Unicode numeric characters, including digits from various scripts, Roman numerals, etc.

isPunctuation :: Char -> Bool

Selects Unicode punctuation characters, including various kinds of connectors, brackets and quotes.

isSymbol :: Char -> Bool

Selects Unicode symbol characters, including mathematical and currency symbols.

isSeparator :: Char -> Bool

Selects Unicode space and separator characters.

isAscii :: Char -> Bool

Selects the first 128 characters of the Unicode character set, corresponding to the ASCII character set.

isLatin1 :: Char -> Bool

Selects the first 256 characters of the Unicode character set, corresponding to the ISO 8859-1 (Latin-1) character set.

isAsciiUpper :: Char -> Bool

Selects ASCII upper-case letters, i.e. characters satisfying both isAscii and isUpper.

isAsciiLower :: Char -> Bool

Selects ASCII lower-case letters, i.e. characters satisfying both isAscii and isLower.

class IsString a where

Class for string-like datastructures; used by the overloaded string extension (-foverloaded-strings in GHC).

Methods

fromString :: String -> a

Instances

toUpper :: Char -> Char

Convert a letter to the corresponding upper-case letter, if any. Any other character is returned unchanged.

toLower :: Char -> Char

Convert a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged.

toTitle :: Char -> Char

Convert a letter to the corresponding title-case or upper-case letter, if any. (Title case differs from upper case only for a small number of ligature letters.) Any other character is returned unchanged.

digitToInt :: Char -> Int

Convert a single digit Char to the corresponding Int. This function fails unless its argument satisfies isHexDigit, but recognises both upper and lower-case hexadecimal digits (i.e. '0'..'9', 'a'..'f', 'A'..'F').

intToDigit :: Int -> Char

Convert an Int in the range 0..15 to the corresponding single digit Char. This function fails on other inputs, and generates lower-case hexadecimal digits.

ord :: Char -> Int

The fromEnum method restricted to the type Char.

chr :: Int -> Char

The toEnum method restricted to the type Char.

class AtLeastPair a whereSource

Associated Types

type Fst a Source

type Snd a Source

Methods

fst :: a -> Fst aSource

snd :: a -> Snd aSource

Instances

AtLeastPair (a, b) 
AtLeastPair (a, b, c) 
AtLeastPair (a, b, c, d) 
AtLeastPair (a, b, c, d, e) 

curry :: ((a, b) -> c) -> a -> b -> c

curry converts an uncurried function to a curried function.

uncurry :: (a -> b -> c) -> (a, b) -> c

uncurry converts a curried function to a function on pairs.

swap :: (a, b) -> (b, a)

Swap the components of a pair.

class Eq a where

The Eq class defines equality (==) and inequality (/=). All the basic datatypes exported by the Prelude are instances of Eq, and Eq may be derived for any datatype whose constituents are also instances of Eq.

Minimal complete definition: either == or /=.

Methods

(==) :: a -> a -> Bool

(/=) :: a -> a -> Bool

Instances

Eq Bool 
Eq Char 
Eq Double 
Eq Float 
Eq Int 
Eq Int8 
Eq Int16 
Eq Int32 
Eq Int64 
Eq Integer 
Eq Ordering 
Eq Word 
Eq Word8 
Eq Word16 
Eq Word32 
Eq Word64 
Eq () 
Eq Constr

Equality of constructors

Eq DataRep 
Eq ConstrRep 
Eq Fixity 
Eq ThreadId 
Eq BlockReason 
Eq ThreadStatus 
Eq AsyncException 
Eq ArrayException 
Eq ExitCode 
Eq IOErrorType 
Eq All 
Eq Any 
Eq TypeRepKey 
Eq GeneralCategory 
Eq MaskingState 
Eq IOException 
Eq ArithException 
Eq TypeRep 
Eq TyCon 
Eq Version 
Eq a => Eq [a] 
Eq a => Eq (Ratio a) 
Eq a => Eq (Complex a) 
Eq (TVar a) 
Eq a => Eq (Dual a) 
Eq a => Eq (Sum a) 
Eq a => Eq (Product a) 
Eq a => Eq (First a) 
Eq a => Eq (Last a) 
Eq a => Eq (Down a) 
Eq a => Eq (Maybe a) 
(Eq a, Eq b) => Eq (Either a b) 
(Eq a, Eq b) => Eq (a, b) 
(Eq a, Eq b, Eq c) => Eq (a, b, c) 
(Eq a, Eq b, Eq c, Eq d) => Eq (a, b, c, d) 
(Eq a, Eq b, Eq c, Eq d, Eq e) => Eq (a, b, c, d, e) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => Eq (a, b, c, d, e, f) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g) => Eq (a, b, c, d, e, f, g) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h) => Eq (a, b, c, d, e, f, g, h) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i) => Eq (a, b, c, d, e, f, g, h, i) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j) => Eq (a, b, c, d, e, f, g, h, i, j) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k) => Eq (a, b, c, d, e, f, g, h, i, j, k) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l) => Eq (a, b, c, d, e, f, g, h, i, j, k, l) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n) 
(Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n, Eq o) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) 

class Eq a => Ord a where

The Ord class is used for totally ordered datatypes.

Instances of Ord can be derived for any user-defined datatype whose constituent types are in Ord. The declared order of the constructors in the data declaration determines the ordering in derived Ord instances. The Ordering datatype allows a single comparison to determine the precise ordering of two objects.

Minimal complete definition: either compare or <=. Using compare can be more efficient for complex types.

Methods

compare :: a -> a -> Ordering

(<) :: a -> a -> Bool

(>=) :: a -> a -> Bool

(>) :: a -> a -> Bool

(<=) :: a -> a -> Bool

max :: a -> a -> a

min :: a -> a -> a

Instances

Ord Bool 
Ord Char 
Ord Double 
Ord Float 
Ord Int 
Ord Int8 
Ord Int16 
Ord Int32 
Ord Int64 
Ord Integer 
Ord Ordering 
Ord Word 
Ord Word8 
Ord Word16 
Ord Word32 
Ord Word64 
Ord () 
Ord ThreadId 
Ord BlockReason 
Ord ThreadStatus 
Ord AsyncException 
Ord ArrayException 
Ord ExitCode 
Ord All 
Ord Any 
Ord TypeRepKey 
Ord GeneralCategory 
Ord ArithException 
Ord TypeRep 
Ord TyCon 
Ord Version 
Ord a => Ord [a] 
Integral a => Ord (Ratio a) 
Ord a => Ord (Dual a) 
Ord a => Ord (Sum a) 
Ord a => Ord (Product a) 
Ord a => Ord (First a) 
Ord a => Ord (Last a) 
Ord a => Ord (Down a) 
Ord a => Ord (Maybe a) 
(Ord a, Ord b) => Ord (Either a b) 
(Ord a, Ord b) => Ord (a, b) 
(Ord a, Ord b, Ord c) => Ord (a, b, c) 
(Ord a, Ord b, Ord c, Ord d) => Ord (a, b, c, d) 
(Ord a, Ord b, Ord c, Ord d, Ord e) => Ord (a, b, c, d, e) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f) => Ord (a, b, c, d, e, f) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g) => Ord (a, b, c, d, e, f, g) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h) => Ord (a, b, c, d, e, f, g, h) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i) => Ord (a, b, c, d, e, f, g, h, i) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j) => Ord (a, b, c, d, e, f, g, h, i, j) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k) => Ord (a, b, c, d, e, f, g, h, i, j, k) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l) => Ord (a, b, c, d, e, f, g, h, i, j, k, l) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n) 
(Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n, Ord o) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) 

class Enum a where

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:

    enumFrom     x   = enumFromTo     x maxBound
    enumFromThen x y = enumFromThenTo x y bound
      where
        bound | fromEnum y >= fromEnum x = maxBound
              | otherwise                = minBound

Methods

succ :: a -> a

the successor of a value. For numeric types, succ adds 1.

pred :: a -> a

the predecessor of a value. For numeric types, pred subtracts 1.

toEnum :: Int -> a

Convert from an Int.

fromEnum :: a -> 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.

enumFrom :: a -> [a]

Used in Haskell's translation of [n..].

enumFromThen :: a -> a -> [a]

Used in Haskell's translation of [n,n'..].

enumFromTo :: a -> a -> [a]

Used in Haskell's translation of [n..m].

enumFromThenTo :: a -> a -> a -> [a]

Used in Haskell's translation of [n,n'..m].

class Bounded a where

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.

Methods

minBound :: a

maxBound :: a

Instances

Bounded Bool 
Bounded Char 
Bounded Int 
Bounded Int8 
Bounded Int16 
Bounded Int32 
Bounded Int64 
Bounded Ordering 
Bounded Word 
Bounded Word8 
Bounded Word16 
Bounded Word32 
Bounded Word64 
Bounded () 
Bounded All 
Bounded Any 
Bounded GeneralCategory 
Bounded a => Bounded (Dual a) 
Bounded a => Bounded (Sum a) 
Bounded a => Bounded (Product a) 
(Bounded a, Bounded b) => Bounded (a, b) 
(Bounded a, Bounded b, Bounded c) => Bounded (a, b, c) 
(Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a, b, c, d) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a, b, c, d, e) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f) => Bounded (a, b, c, d, e, f) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g) => Bounded (a, b, c, d, e, f, g) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h) => Bounded (a, b, c, d, e, f, g, h) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i) => Bounded (a, b, c, d, e, f, g, h, i) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j) => Bounded (a, b, c, d, e, f, g, h, i, j) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k) => Bounded (a, b, c, d, e, f, g, h, i, j, k) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l) => Bounded (a, b, c, d, e, f, g, h, i, j, k, l) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m) => Bounded (a, b, c, d, e, f, g, h, i, j, k, l, m) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n) => Bounded (a, b, c, d, e, f, g, h, i, j, k, l, m, n) 
(Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o) => Bounded (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) 

data Int

A fixed-precision integer type with at least the range [-2^29 .. 2^29-1]. The exact range for a given implementation can be determined by using minBound and maxBound from the Bounded class.

data Float

Single-precision floating point numbers. It is desirable that this type be at least equal in range and precision to the IEEE single-precision type.

data Double

Double-precision floating point numbers. It is desirable that this type be at least equal in range and precision to the IEEE double-precision type.

data Int8

8-bit signed integer type

type Rational = Ratio Integer

Arbitrary-precision rational numbers, represented as a ratio of two Integer values. A rational number may be constructed using the % operator.

data Ratio a

Rational numbers, with numerator and denominator of some Integral type.

Instances

Typeable1 Ratio 
Integral a => Enum (Ratio a) 
Eq a => Eq (Ratio a) 
Integral a => Fractional (Ratio a) 
(Data a, Integral a) => Data (Ratio a) 
Integral a => Num (Ratio a) 
Integral a => Ord (Ratio a) 
(Integral a, Read a) => Read (Ratio a) 
Integral a => Real (Ratio a) 
Integral a => RealFrac (Ratio a) 
(Integral a, Show a) => Show (Ratio a) 

class Num a where

Basic numeric class.

Minimal complete definition: all except negate or (-)

Methods

(+) :: a -> a -> a

(*) :: a -> a -> a

(-) :: a -> a -> a

negate :: a -> a

Unary negation.

abs :: a -> a

Absolute value.

signum :: a -> a

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 -> a

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 where

Methods

toRational :: a -> Rational

the rational equivalent of its real argument with full precision

class (Real a, Enum a) => Integral a where

Integral numbers, supporting integer division.

Minimal complete definition: quotRem and toInteger

Methods

quot :: a -> a -> a

integer division truncated toward zero

rem :: a -> a -> a

integer remainder, satisfying

 (x `quot` y)*y + (x `rem` y) == x

div :: a -> a -> a

integer division truncated toward negative infinity

mod :: a -> a -> a

integer modulus, satisfying

 (x `div` y)*y + (x `mod` y) == x

quotRem :: a -> a -> (a, a)

simultaneous quot and rem

divMod :: a -> a -> (a, a)

simultaneous div and mod

toInteger :: a -> Integer

conversion to Integer

class Num a => Fractional a where

Fractional numbers, supporting real division.

Minimal complete definition: fromRational and (recip or (/))

Methods

(/) :: a -> a -> a

fractional division

recip :: a -> a

reciprocal fraction

fromRational :: Rational -> a

Conversion from a Rational (that is Ratio Integer). A floating literal stands for an application of fromRational to a value of type Rational, so such literals have type (Fractional a) => a.

class Fractional a => Floating a where

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

pi :: a

exp :: a -> a

sqrt :: a -> a

log :: a -> a

(**) :: a -> a -> a

logBase :: a -> a -> a

sin :: a -> a

tan :: a -> a

cos :: a -> a

asin :: a -> a

atan :: a -> a

acos :: a -> a

sinh :: a -> a

tanh :: a -> a

cosh :: a -> a

asinh :: a -> a

atanh :: a -> a

acosh :: a -> a

class (Real a, Fractional a) => RealFrac a where

Extracting components of fractions.

Minimal complete definition: properFraction

Methods

properFraction :: Integral b => a -> (b, a)

The function properFraction takes a real fractional number x and returns a pair (n,f) such that x = n+f, and:

  • n is an integral number with the same sign as x; and
  • f is a fraction with the same type and sign as x, and with absolute value less than 1.

The default definitions of the ceiling, floor, truncate and round functions are in terms of properFraction.

truncate :: Integral b => a -> b

truncate x returns the integer nearest x between zero and x

round :: Integral b => a -> b

round x returns the nearest integer to x; the even integer if x is equidistant between two integers

ceiling :: Integral b => a -> b

ceiling x returns the least integer not less than x

floor :: Integral b => a -> b

floor x returns the greatest integer not greater than x

class (RealFrac a, Floating a) => RealFloat a where

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 -> Integer

a constant function, returning the radix of the representation (often 2)

floatDigits :: a -> Int

a constant function, returning the number of digits of floatRadix in the significand

floatRange :: a -> (Int, Int)

a constant function, returning the lowest and highest values the exponent may assume

decodeFloat :: a -> (Integer, Int)

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 decodeFloat x yields (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) <= abs m < b^d, where d is the value of floatDigits x. In particular, decodeFloat 0 = (0,0). If the type contains a negative zero, also decodeFloat (-0.0) = (0,0). The result of decodeFloat x is unspecified if either of isNaN x or isInfinite x is True.

encodeFloat :: Integer -> Int -> a

encodeFloat performs the inverse of decodeFloat in the sense that for finite x with the exception of -0.0, uncurry encodeFloat (decodeFloat x) = x. encodeFloat m n is one of the two closest representable floating-point numbers to m*b^^n (or ±Infinity if overflow occurs); usually the closer, but if m contains too many bits, the result may be rounded in the wrong direction.

exponent :: a -> Int

exponent corresponds to the second component of decodeFloat. exponent 0 = 0 and for finite nonzero x, exponent x = snd (decodeFloat x) + floatDigits x. If x is a finite floating-point number, it is equal in value to significand x * b ^^ exponent x, where b is the floating-point radix. The behaviour is unspecified on infinite or NaN values.

significand :: a -> a

The first component of decodeFloat, scaled to lie in the open interval (-1,1), either 0.0 or of absolute value >= 1/b, where b is the floating-point radix. The behaviour is unspecified on infinite or NaN values.

scaleFloat :: Int -> a -> a

multiplies a floating-point number by an integer power of the radix

isNaN :: a -> Bool

True if the argument is an IEEE "not-a-number" (NaN) value

isInfinite :: a -> Bool

True if the argument is an IEEE infinity or negative infinity

isDenormalized :: a -> Bool

True if the argument is too small to be represented in normalized format

isNegativeZero :: a -> Bool

True if the argument is an IEEE negative zero

isIEEE :: a -> Bool

True if the argument is an IEEE floating point number

atan2 :: a -> a -> a

a version of arctangent taking two real floating-point arguments. For real floating x and y, atan2 y x computes the angle (from the positive x-axis) of the vector from the origin to the point (x,y). atan2 y x returns a value in the range [-pi, pi]. It follows the Common Lisp semantics for the origin when signed zeroes are supported. atan2 y 1, with y in a type that is RealFloat, should return the same value as atan y. A default definition of atan2 is provided, but implementors can provide a more accurate implementation.

data Complex a

Complex numbers are an algebraic type.

For a complex number z, abs z is a number with the magnitude of z, but oriented in the positive real direction, whereas signum z has the phase of z, but unit magnitude.

Instances

Typeable1 Complex 
Eq a => Eq (Complex a) 
RealFloat a => Floating (Complex a) 
RealFloat a => Fractional (Complex a) 
Data a => Data (Complex a) 
RealFloat a => Num (Complex a) 
Read a => Read (Complex a) 
Show a => Show (Complex a) 

realPart :: RealFloat a => Complex a -> a

Extracts the real part of a complex number.

imagPart :: RealFloat a => Complex a -> a

Extracts the imaginary part of a complex number.

mkPolar :: RealFloat a => a -> a -> Complex a

Form a complex number from polar components of magnitude and phase.

cis :: RealFloat a => a -> Complex a

cis t is a complex value with magnitude 1 and phase t (modulo 2*pi).

polar :: RealFloat a => Complex a -> (a, a)

The function polar takes a complex number and returns a (magnitude, phase) pair in canonical form: the magnitude is nonnegative, and the phase in the range (-pi, pi]; if the magnitude is zero, then so is the phase.

magnitude :: RealFloat a => Complex a -> a

The nonnegative magnitude of a complex number.

phase :: RealFloat a => Complex a -> a

The phase of a complex number, in the range (-pi, pi]. If the magnitude is zero, then so is the phase.

conjugate :: RealFloat a => Complex a -> Complex a

The conjugate of a complex number.

subtract :: Num a => a -> a -> a

the same as flip (-).

Because - is treated specially in the Haskell grammar, (- e) is not a section, but an application of prefix negation. However, (subtract exp) is equivalent to the disallowed section.

even :: Integral a => a -> Bool

odd :: Integral a => a -> Bool

gcd :: Integral a => a -> a -> a

gcd x y is the non-negative factor of both x and y of which every common factor of x and y is also a factor; for example gcd 4 2 = 2, gcd (-4) 6 = 2, gcd 0 4 = 4. gcd 0 0 = 0. (That is, the common divisor that is "greatest" in the divisibility preordering.)

Note: Since for signed fixed-width integer types, abs minBound < 0, the result may be negative if one of the arguments is minBound (and necessarily is if the other is 0 or minBound) for such types.

lcm :: Integral a => a -> a -> a

lcm x y is the smallest positive integer that both x and y divide.

(^) :: (Num a, Integral b) => a -> b -> a

raise a number to a non-negative integral power

(^^) :: (Fractional a, Integral b) => a -> b -> a

raise a number to an integral power

fromIntegral :: (Integral a, Num b) => a -> b

general coercion from integral types

realToFrac :: (Real a, Fractional b) => a -> b

general coercion to fractional types

class Functor f where

The Functor class is used for types that can be mapped over. Instances of Functor should satisfy the following laws:

 fmap id  ==  id
 fmap (f . g)  ==  fmap f . fmap g

The instances of Functor for lists, Maybe and IO satisfy these laws.

Methods

fmap :: (a -> b) -> f a -> f b

(<$) :: a -> f b -> f a

Replace all locations in the input with the same value. The default definition is fmap . const, but this may be overridden with a more efficient version.

id :: Category cat => forall a. cat a a

the identity morphism

const :: a -> b -> a

Constant function.

(.) :: Category cat => forall b c a. cat b c -> cat a b -> cat a c

morphism composition

flip :: (a -> b -> c) -> b -> a -> c

flip f takes its (first) two arguments in the reverse order of f.

($) :: (a -> b) -> a -> b

Application operator. This operator is redundant, since ordinary application (f x) means the same as (f $ x). However, $ 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 map ($ 0) xs, or zipWith ($) fs xs.

fix :: (a -> a) -> a

fix f is the least fixed point of the function f, i.e. the least defined x such that f x = x.

on :: (b -> b -> c) -> (a -> b) -> a -> a -> c

(*) `on` f = \x y -> f x * f y.

Typical usage: sortBy (compare `on` fst).

Algebraic properties:

  • (*) `on` id = (*) (if (*) ∉ {⊥, const ⊥})
  • ((*) `on` f) `on` g = (*) `on` (f . g)
  • flip on f . flip on g = flip on (g . f)

until :: (a -> Bool) -> (a -> a) -> a -> a

until p f yields the result of applying f until p holds.

asTypeOf :: a -> a -> a

asTypeOf is a type-restricted version of const. It is usually used as an infix operator, and its typing forces its first argument (which is usually overloaded) to have the same type as the second.

error :: [Char] -> a

error stops execution and displays an error message.

undefined :: a

A special case of error. It is expected that compilers will recognize this and insert error messages which are more appropriate to the context in which undefined appears.

seq :: a -> b -> b

Evaluates its first argument to head normal form, and then returns its second argument as the result.

($!) :: (a -> b) -> a -> b

Strict (call-by-value) application, defined in terms of seq.

class Functor f => Applicative f where

A functor with application, providing operations to

  • embed pure expressions (pure), and
  • sequence computations and combine their results (<*>).

A minimal complete definition must include implementations of these functions satisfying the following laws:

identity
pure id <*> v = v
composition
pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
homomorphism
pure f <*> pure x = pure (f x)
interchange
u <*> pure y = pure ($ y) <*> u

The other methods have the following default definitions, which may be overridden with equivalent specialized implementations:

      u *> v = pure (const id) <*> u <*> v
      u <* v = pure const <*> u <*> v

As a consequence of these laws, the Functor instance for f will satisfy

      fmap f x = pure f <*> x

If f is also a Monad, it should satisfy pure = return and (<*>) = ap (which implies that pure and <*> satisfy the applicative functor laws).

Methods

pure :: a -> f a

Lift a value.

(<*>) :: f (a -> b) -> f a -> f b

Sequential application.

(*>) :: f a -> f b -> f b

Sequence actions, discarding the value of the first argument.

(<*) :: f a -> f b -> f a

Sequence actions, discarding the value of the second argument.

class Monad m where

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, Maybe and IO defined in the Prelude satisfy these laws.

Methods

(>>=) :: m a -> (a -> m b) -> m b

Sequentially compose two actions, passing any value produced by the first as an argument to the second.

(>>) :: m a -> m b -> m b

Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.

return :: a -> m a

Inject a value into the monadic type.

fail :: String -> m a

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.

(=<<) :: Monad m => (a -> m b) -> m a -> m b

Same as >>=, but with the arguments interchanged.

(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c

Left-to-right Kleisli composition of monads.

(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c

Right-to-left Kleisli composition of monads. (>=>), with the arguments flipped

forever :: Monad m => m a -> m b

forever act repeats the action infinitely.

void :: Functor f => f a -> f ()

void value discards or ignores the result of evaluation, such as the return value of an IO action.

join :: Monad m => m (m a) -> m a

The join function is the conventional monad join operator. It is used to remove one level of monadic structure, projecting its bound argument into the outer level.

class Monad m => MonadPlus m where

Monads that also support choice and failure.

Methods

mzero :: m a

the identity of mplus. It should also satisfy the equations

 mzero >>= f  =  mzero
 v >> mzero   =  mzero

mplus :: m a -> m a -> m a

an associative operation

mapM :: Monad m => (a -> m b) -> [a] -> m [b]

mapM f is equivalent to sequence . map f.

mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()

Map each element of a structure to a monadic action, evaluate these actions from left to right, and ignore the results.

forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)

forM is mapM with its arguments flipped.

forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()

forM_ is mapM_ with its arguments flipped.

sequence :: Monad m => [m a] -> m [a]

Evaluate each action in the sequence from left to right, and collect the results.

sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()

Evaluate each monadic action in the structure from left to right, and ignore the results.

msum :: (Foldable t, MonadPlus m) => t (m a) -> m a

The sum of a collection of actions, generalizing concat.

mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a

Direct MonadPlus equivalent of filter filter = (mfilter:: (a -> Bool) -> [a] -> [a] applicable to any MonadPlus, for example mfilter odd (Just 1) == Just 1 mfilter odd (Just 2) == Nothing

filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]

This generalizes the list-based filter function.

mapAndUnzipM :: Monad m => (a -> m (b, c)) -> [a] -> m ([b], [c])

The mapAndUnzipM function maps its first argument over a list, returning the result as a pair of lists. This function is mainly used with complicated data structures or a state-transforming monad.

zipWithM :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m [c]

The zipWithM function generalizes zipWith to arbitrary monads.

zipWithM_ :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m ()

zipWithM_ is the extension of zipWithM which ignores the final result.

foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a

The foldM function is analogous to foldl, except that its result is encapsulated in a monad. Note that foldM works from left-to-right over the list arguments. This could be an issue where (>>) and the `folded function' are not commutative.

       foldM f a1 [x1, x2, ..., xm]

==

       do
         a2 <- f a1 x1
         a3 <- f a2 x2
         ...
         f am xm

If right-to-left evaluation is required, the input list should be reversed.

foldM_ :: Monad m => (a -> b -> m a) -> a -> [b] -> m ()

Like foldM, but discards the result.

replicateM :: Monad m => Int -> m a -> m [a]

replicateM n act performs the action n times, gathering the results.

replicateM_ :: Monad m => Int -> m a -> m ()

Like replicateM, but discards the result.

guard :: MonadPlus m => Bool -> m ()

guard b is return () if b is True, and mzero if b is False.

when :: Monad m => Bool -> m () -> m ()

Conditional execution of monadic expressions. For example,

       when debug (putStr "Debugging\n")

will output the string Debugging\n if the Boolean value debug is True, and otherwise do nothing.

unless :: Monad m => Bool -> m () -> m ()

The reverse of when.

liftM :: Monad m => (a1 -> r) -> m a1 -> m r

Promote a function to a monad.

liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r

Promote a function to a monad, scanning the monadic arguments from left to right. For example,

    liftM2 (+) [0,1] [0,2] = [0,2,1,3]
    liftM2 (+) (Just 1) Nothing = Nothing

liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

ap :: Monad m => m (a -> b) -> m a -> m b

In many situations, the liftM operations can be replaced by uses of ap, which promotes function application.

       return f `ap` x1 `ap` ... `ap` xn

is equivalent to

       liftMn f x1 x2 ... xn

class Monoid a where

The class of monoids (types with an associative binary operation that has an identity). Instances should satisfy the following laws:

  • mappend mempty x = x
  • mappend x mempty = x
  • mappend x (mappend y z) = mappend (mappend x y) z
  • mconcat = foldr mappend mempty

The method names refer to the monoid of lists under concatenation, but there are many other instances.

Minimal complete definition: mempty and mappend.

Some types can be viewed as a monoid in more than one way, e.g. both addition and multiplication on numbers. In such cases we often define newtypes and make those instances of Monoid, e.g. Sum and Product.

Methods

mempty :: a

Identity of mappend

mappend :: a -> a -> a

An associative operation

mconcat :: [a] -> a

Fold a list using the monoid. For most types, the default definition for mconcat will be used, but the function is included in the class definition so that an optimized version can be provided for specific types.

Instances

Monoid Ordering 
Monoid () 
Monoid All 
Monoid Any 
Monoid [a] 
Monoid a => Monoid (Dual a) 
Monoid (Endo a) 
Num a => Monoid (Sum a) 
Num a => Monoid (Product a) 
Monoid (First a) 
Monoid (Last a) 
Monoid a => Monoid (Maybe a)

Lift a semigroup into Maybe forming a Monoid according to http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be turned into a monoid simply by adjoining an element e not in S and defining e*e = e and e*s = s = s*e for all s ∈ S." Since there is no "Semigroup" typeclass providing just mappend, we use Monoid instead.

Monoid b => Monoid (a -> b) 
(Monoid a, Monoid b) => Monoid (a, b) 
(Monoid a, Monoid b, Monoid c) => Monoid (a, b, c) 
(Monoid a, Monoid b, Monoid c, Monoid d) => Monoid (a, b, c, d) 
(Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) => Monoid (a, b, c, d, e) 

(<>) :: Monoid m => m -> m -> m

An infix synonym for mappend.

newtype Dual a

The dual of a monoid, obtained by swapping the arguments of mappend.

Constructors

Dual 

Fields

getDual :: a
 

Instances

Bounded a => Bounded (Dual a) 
Eq a => Eq (Dual a) 
Ord a => Ord (Dual a) 
Read a => Read (Dual a) 
Show a => Show (Dual a) 
Monoid a => Monoid (Dual a) 

newtype Endo a

The monoid of endomorphisms under composition.

Constructors

Endo 

Fields

appEndo :: a -> a
 

Instances

Monoid (Endo a) 

newtype All

Boolean monoid under conjunction.

Constructors

All 

Fields

getAll :: Bool
 

newtype Any

Boolean monoid under disjunction.

Constructors

Any 

Fields

getAny :: Bool
 

newtype Sum a

Monoid under addition.

Constructors

Sum 

Fields

getSum :: a
 

Instances

Bounded a => Bounded (Sum a) 
Eq a => Eq (Sum a) 
Ord a => Ord (Sum a) 
Read a => Read (Sum a) 
Show a => Show (Sum a) 
Num a => Monoid (Sum a) 

newtype Product a

Monoid under multiplication.

Constructors

Product 

Fields

getProduct :: a
 

Instances

Bounded a => Bounded (Product a) 
Eq a => Eq (Product a) 
Ord a => Ord (Product a) 
Read a => Read (Product a) 
Show a => Show (Product a) 
Num a => Monoid (Product a) 

newtype First a

Maybe monoid returning the leftmost non-Nothing value.

Constructors

First 

Fields

getFirst :: Maybe a
 

Instances

Eq a => Eq (First a) 
Ord a => Ord (First a) 
Read a => Read (First a) 
Show a => Show (First a) 
Monoid (First a) 

newtype Last a

Maybe monoid returning the rightmost non-Nothing value.

Constructors

Last 

Fields

getLast :: Maybe a
 

Instances

Eq a => Eq (Last a) 
Ord a => Ord (Last a) 
Read a => Read (Last a) 
Show a => Show (Last a) 
Monoid (Last a) 

class Applicative f => Alternative f where

A monoid on applicative functors.

Minimal complete definition: empty and <|>.

If defined, some and many should be the least solutions of the equations:

Methods

empty :: f a

The identity of <|>

(<|>) :: f a -> f a -> f a

An associative binary operation

some :: f a -> f [a]

One or more.

many :: f a -> f [a]

Zero or more.

newtype Const a b

Constructors

Const 

Fields

getConst :: a
 

Instances

newtype WrappedMonad m a

Constructors

WrapMonad 

Fields

unwrapMonad :: m a
 

newtype WrappedArrow a b c

Constructors

WrapArrow 

Fields

unwrapArrow :: a b c
 

newtype ZipList a

Lists, but with an Applicative functor based on zipping, so that

f <$> ZipList xs1 <*> ... <*> ZipList xsn = ZipList (zipWithn f xs1 ... xsn)

Constructors

ZipList 

Fields

getZipList :: [a]
 

(<$>) :: Functor f => (a -> b) -> f a -> f b

An infix synonym for fmap.

(<**>) :: Applicative f => f a -> f (a -> b) -> f b

A variant of <*> with the arguments reversed.

liftA :: Applicative f => (a -> b) -> f a -> f b

Lift a function to actions. This function may be used as a value for fmap in a Functor instance.

liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c

Lift a binary function to actions.

liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d

Lift a ternary function to actions.

optional :: Alternative f => f a -> f (Maybe a)

One or none.

class Category a => Arrow a where

The basic arrow class.

Minimal complete definition: arr and first, satisfying the laws

where

 assoc ((a,b),c) = (a,(b,c))

The other combinators have sensible default definitions, which may be overridden for efficiency.

Methods

arr :: (b -> c) -> a b c

Lift a function to an arrow.

first :: a b c -> a (b, d) (c, d)

Send the first component of the input through the argument arrow, and copy the rest unchanged to the output.

second :: a b c -> a (d, b) (d, c)

A mirror image of first.

The default definition may be overridden with a more efficient version if desired.

(***) :: a b c -> a b' c' -> a (b, b') (c, c')

Split the input between the two argument arrows and combine their output. Note that this is in general not a functor.

The default definition may be overridden with a more efficient version if desired.

(&&&) :: a b c -> a b c' -> a b (c, c')

Fanout: send the input to both argument arrows and combine their output.

The default definition may be overridden with a more efficient version if desired.

Instances

Arrow (->) 
Monad m => Arrow (Kleisli m) 

newtype Kleisli m a b

Kleisli arrows of a monad.

Constructors

Kleisli 

Fields

runKleisli :: a -> m b
 

Instances

Monad m => Arrow (Kleisli m) 
MonadPlus m => ArrowZero (Kleisli m) 
MonadPlus m => ArrowPlus (Kleisli m) 
Monad m => ArrowChoice (Kleisli m) 
Monad m => ArrowApply (Kleisli m) 
MonadFix m => ArrowLoop (Kleisli m)

Beware that for many monads (those for which the >>= operation is strict) this instance will not satisfy the right-tightening law required by the ArrowLoop class.

Monad m => Category (Kleisli m) 

returnA :: Arrow a => a b b

The identity arrow, which plays the role of return in arrow notation.

(^>>) :: Arrow a => (b -> c) -> a c d -> a b d

Precomposition with a pure function.

(>>^) :: Arrow a => a b c -> (c -> d) -> a b d

Postcomposition with a pure function.

(>>>) :: Category cat => cat a b -> cat b c -> cat a c

Left-to-right composition

(<<<) :: Category cat => cat b c -> cat a b -> cat a c

Right-to-left composition

(<<^) :: Arrow a => a c d -> (b -> c) -> a b d

Precomposition with a pure function (right-to-left variant).

(^<<) :: Arrow a => (c -> d) -> a b c -> a b d

Postcomposition with a pure function (right-to-left variant).

class Arrow a => ArrowZero a where

Methods

zeroArrow :: a b c

Instances

class ArrowZero a => ArrowPlus a where

A monoid on arrows.

Methods

(<+>) :: a b c -> a b c -> a b c

An associative operation with identity zeroArrow.

Instances

class Arrow a => ArrowChoice a where

Choice, for arrows that support it. This class underlies the if and case constructs in arrow notation. Minimal complete definition: left, satisfying the laws

where

 assocsum (Left (Left x)) = Left x
 assocsum (Left (Right y)) = Right (Left y)
 assocsum (Right z) = Right (Right z)

The other combinators have sensible default definitions, which may be overridden for efficiency.

Methods

left :: a b c -> a (Either b d) (Either c d)

Feed marked inputs through the argument arrow, passing the rest through unchanged to the output.

right :: a b c -> a (Either d b) (Either d c)

A mirror image of left.

The default definition may be overridden with a more efficient version if desired.

(+++) :: a b c -> a b' c' -> a (Either b b') (Either c c')

Split the input between the two argument arrows, retagging and merging their outputs. Note that this is in general not a functor.

The default definition may be overridden with a more efficient version if desired.

(|||) :: a b d -> a c d -> a (Either b c) d

Fanin: Split the input between the two argument arrows and merge their outputs.

The default definition may be overridden with a more efficient version if desired.

Instances

class Arrow a => ArrowApply a where

Some arrows allow application of arrow inputs to other inputs. Instances should satisfy the following laws:

Such arrows are equivalent to monads (see ArrowMonad).

Methods

app :: a (a b c, b) c

Instances

newtype ArrowMonad a b

The ArrowApply class is equivalent to Monad: any monad gives rise to a Kleisli arrow, and any instance of ArrowApply defines a monad.

Constructors

ArrowMonad (a () b) 

leftApp :: ArrowApply a => a b c -> a (Either b d) (Either c d)

Any instance of ArrowApply can be made into an instance of ArrowChoice by defining left = leftApp.

class Arrow a => ArrowLoop a where

The loop operator expresses computations in which an output value is fed back as input, although the computation occurs only once. It underlies the rec value recursion construct in arrow notation. loop should satisfy the following laws:

extension
loop (arr f) = arr (\ b -> fst (fix (\ (c,d) -> f (b,d))))
left tightening
loop (first h >>> f) = h >>> loop f
right tightening
loop (f >>> first h) = loop f >>> h
sliding
loop (f >>> arr (id *** k)) = loop (arr (id *** k) >>> f)
vanishing
loop (loop f) = loop (arr unassoc >>> f >>> arr assoc)
superposing
second (loop f) = loop (arr assoc >>> second f >>> arr unassoc)

where

 assoc ((a,b),c) = (a,(b,c))
 unassoc (a,(b,c)) = ((a,b),c)

Methods

loop :: a (b, d) (c, d) -> a b c

Instances

ArrowLoop (->) 
MonadFix m => ArrowLoop (Kleisli m)

Beware that for many monads (those for which the >>= operation is strict) this instance will not satisfy the right-tightening law required by the ArrowLoop class.

map :: Functor f => (a -> b) -> f a -> f bSource

(++) :: [a] -> [a] -> [a]

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.

(!!) :: [a] -> Int -> a

List index (subscript) operator, starting from 0. It is an instance of the more general genericIndex, which takes an index of any integral type.

reverse :: [a] -> [a]

reverse xs returns the elements of xs in reverse order. xs must be finite.

filter :: (a -> Bool) -> [a] -> [a]

filter, applied to a predicate and a list, returns the list of those elements that satisfy the predicate; i.e.,

 filter p xs = [ x | x <- xs, p x]

head :: [a] -> a

Extract the first element of a list, which must be non-empty.

last :: [a] -> a

Extract the last element of a list, which must be finite and non-empty.

tail :: [a] -> [a]

Extract the elements after the head of a list, which must be non-empty.

init :: [a] -> [a]

Return all the elements of a list except the last one. The list must be non-empty.

null :: [a] -> Bool

Test whether a list is empty.

length :: [a] -> Int

O(n). length returns the length of a finite list as an Int. It is an instance of the more general genericLength, the result type of which may be any kind of number.

class (Functor t, Foldable t) => Traversable t where

Functors representing data structures that can be traversed from left to right.

Minimal complete definition: traverse or sequenceA.

Instances are similar to Functor, e.g. given a data type

 data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)

a suitable instance would be

 instance Traversable Tree where
    traverse f Empty = pure Empty
    traverse f (Leaf x) = Leaf <$> f x
    traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r

This is suitable even for abstract types, as the laws for <*> imply a form of associativity.

The superclass instances should satisfy the following:

Methods

traverse :: Applicative f => (a -> f b) -> t a -> f (t b)

Map each element of a structure to an action, evaluate these actions from left to right, and collect the results.

sequenceA :: Applicative f => t (f a) -> f (t a)

Evaluate each action in the structure from left to right, and collect the results.

Instances

class Foldable t where

Data structures that can be folded.

Minimal complete definition: foldMap or foldr.

For example, given a data type

 data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)

a suitable instance would be

 instance Foldable Tree where
    foldMap f Empty = mempty
    foldMap f (Leaf x) = f x
    foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r

This is suitable even for abstract types, as the monoid is assumed to satisfy the monoid laws. Alternatively, one could define foldr:

 instance Foldable Tree where
    foldr f z Empty = z
    foldr f z (Leaf x) = f x z
    foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l

Methods

fold :: Monoid m => t m -> m

Combine the elements of a structure using a monoid.

foldMap :: Monoid m => (a -> m) -> t a -> m

Map each element of the structure to a monoid, and combine the results.

foldr :: (a -> b -> b) -> b -> t a -> b

Right-associative fold of a structure.

foldr f z = foldr f z . toList

foldr' :: (a -> b -> b) -> b -> t a -> b

Right-associative fold of a structure, but with strict application of the operator.

foldl :: (a -> b -> a) -> a -> t b -> a

Left-associative fold of a structure.

foldl f z = foldl f z . toList

foldl' :: (a -> b -> a) -> a -> t b -> a

Left-associative fold of a structure. but with strict application of the operator.

foldl f z = foldl' f z . toList

foldr1 :: (a -> a -> a) -> t a -> a

A variant of foldr that has no base case, and thus may only be applied to non-empty structures.

foldr1 f = foldr1 f . toList

foldl1 :: (a -> a -> a) -> t a -> a

A variant of foldl that has no base case, and thus may only be applied to non-empty structures.

foldl1 f = foldl1 f . toList

Instances

Foldable [] 
Foldable Maybe 
Ix i => Foldable (Array i) 

foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b

Monadic fold over the elements of a structure, associating to the right, i.e. from right to left.

foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a

Monadic fold over the elements of a structure, associating to the left, i.e. from left to right.

traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()

Map each element of a structure to an action, evaluate these actions from left to right, and ignore the results.

for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()

for_ is traverse_ with its arguments flipped.

sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()

Evaluate each action in the structure from left to right, and ignore the results.

asum :: (Foldable t, Alternative f) => t (f a) -> f a

The sum of a collection of actions, generalizing concat.

foldl' :: Foldable t => forall a b. (a -> b -> a) -> a -> t b -> a

Left-associative fold of a structure. but with strict application of the operator.

foldl f z = foldl' f z . toList

foldr' :: Foldable t => forall a b. (a -> b -> b) -> b -> t a -> b

Right-associative fold of a structure, but with strict application of the operator.

toList :: Foldable t => t a -> [a]

List of elements of a structure.

find :: Foldable t => (a -> Bool) -> t a -> Maybe a

The find function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or Nothing if there is no such element.

and :: Foldable t => t Bool -> Bool

and returns the conjunction of a container of Bools. For the result to be True, the container must be finite; False, however, results from a False value finitely far from the left end.

or :: Foldable t => t Bool -> Bool

or returns the disjunction of a container of Bools. For the result to be False, the container must be finite; True, however, results from a True value finitely far from the left end.

any :: Foldable t => (a -> Bool) -> t a -> Bool

Determines whether any element of the structure satisfies the predicate.

all :: Foldable t => (a -> Bool) -> t a -> Bool

Determines whether all elements of the structure satisfy the predicate.

sum :: (Foldable t, Num a) => t a -> a

The sum function computes the sum of the numbers of a structure.

product :: (Foldable t, Num a) => t a -> a

The product function computes the product of the numbers of a structure.

concat :: Foldable t => t [a] -> [a]

The concatenation of all the elements of a container of lists.

concatMap :: Foldable t => (a -> [b]) -> t a -> [b]

Map a function over all the elements of a container and concatenate the resulting lists.

maximum :: (Foldable t, Ord a) => t a -> a

The largest element of a non-empty structure.

minimum :: (Foldable t, Ord a) => t a -> a

The least element of a non-empty structure.

scanl :: (a -> b -> a) -> a -> [b] -> [a]

scanl is similar to foldl, but returns a list of successive reduced values from the left:

 scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]

Note that

 last (scanl f z xs) == foldl f z xs.

scanl1 :: (a -> a -> a) -> [a] -> [a]

scanl1 is a variant of scanl that has no starting value argument:

 scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]

scanr :: (a -> b -> b) -> b -> [a] -> [b]

scanr is the right-to-left dual of scanl. Note that

 head (scanr f z xs) == foldr f z xs.

scanr1 :: (a -> a -> a) -> [a] -> [a]

scanr1 is a variant of scanr that has no starting value argument.

iterate :: (a -> a) -> a -> [a]

iterate f x returns an infinite list of repeated applications of f to x:

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

repeat :: a -> [a]

repeat x is an infinite list, with x the value of every element.

replicate :: Int -> a -> [a]

replicate n x is a list of length n with x the value of every element. It is an instance of the more general genericReplicate, in which n may be of any integral type.

cycle :: [a] -> [a]

cycle ties a finite list into a circular one, or equivalently, the infinite repetition of the original list. It is the identity on infinite lists.

take :: Int -> [a] -> [a]

take n, applied to a list xs, returns the prefix of xs of length n, or xs itself if n > length xs:

 take 5 "Hello World!" == "Hello"
 take 3 [1,2,3,4,5] == [1,2,3]
 take 3 [1,2] == [1,2]
 take 3 [] == []
 take (-1) [1,2] == []
 take 0 [1,2] == []

It is an instance of the more general genericTake, in which n may be of any integral type.

drop :: Int -> [a] -> [a]

drop n xs returns the suffix of xs after the first n elements, or [] if n > length xs:

 drop 6 "Hello World!" == "World!"
 drop 3 [1,2,3,4,5] == [4,5]
 drop 3 [1,2] == []
 drop 3 [] == []
 drop (-1) [1,2] == [1,2]
 drop 0 [1,2] == [1,2]

It is an instance of the more general genericDrop, in which n may be of any integral type.

splitAt :: Int -> [a] -> ([a], [a])

splitAt n xs returns a tuple where first element is xs prefix of length n and second element is the remainder of the list:

 splitAt 6 "Hello World!" == ("Hello ","World!")
 splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
 splitAt 1 [1,2,3] == ([1],[2,3])
 splitAt 3 [1,2,3] == ([1,2,3],[])
 splitAt 4 [1,2,3] == ([1,2,3],[])
 splitAt 0 [1,2,3] == ([],[1,2,3])
 splitAt (-1) [1,2,3] == ([],[1,2,3])

It is equivalent to (take n xs, drop n xs) when n is not _|_ (splitAt _|_ xs = _|_). splitAt is an instance of the more general genericSplitAt, in which n may be of any integral type.

takeWhile :: (a -> Bool) -> [a] -> [a]

takeWhile, applied to a predicate p and a list xs, returns the longest prefix (possibly empty) of xs of elements that satisfy p:

 takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
 takeWhile (< 9) [1,2,3] == [1,2,3]
 takeWhile (< 0) [1,2,3] == []

dropWhile :: (a -> Bool) -> [a] -> [a]

dropWhile p xs returns the suffix remaining after takeWhile p xs:

 dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
 dropWhile (< 9) [1,2,3] == []
 dropWhile (< 0) [1,2,3] == [1,2,3]

span :: (a -> Bool) -> [a] -> ([a], [a])

span, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that satisfy p and second element is the remainder of the list:

 span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
 span (< 9) [1,2,3] == ([1,2,3],[])
 span (< 0) [1,2,3] == ([],[1,2,3])

span p xs is equivalent to (takeWhile p xs, dropWhile p xs)

break :: (a -> Bool) -> [a] -> ([a], [a])

break, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that do not satisfy p and second element is the remainder of the list:

 break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
 break (< 9) [1,2,3] == ([],[1,2,3])
 break (> 9) [1,2,3] == ([1,2,3],[])

break p is equivalent to span (not . p).

elem :: (Foldable t, Eq a) => a -> t a -> Bool

Does the element occur in the structure?

notElem :: (Foldable t, Eq a) => a -> t a -> Bool

notElem is the negation of elem.

lookup :: Eq a => a -> [(a, b)] -> Maybe b

lookup key assocs looks up a key in an association list.

intersperse :: a -> [a] -> [a]

The intersperse function takes an element and a list and `intersperses' that element between the elements of the list. For example,

 intersperse ',' "abcde" == "a,b,c,d,e"

intercalate :: [a] -> [[a]] -> [a]

intercalate xs xss is equivalent to (concat (intersperse xs xss)). It inserts the list xs in between the lists in xss and concatenates the result.

transpose :: [[a]] -> [[a]]

The transpose function transposes the rows and columns of its argument. For example,

 transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]

subsequences :: [a] -> [[a]]

The subsequences function returns the list of all subsequences of the argument.

 subsequences "abc" == ["","a","b","ab","c","ac","bc","abc"]

permutations :: [a] -> [[a]]

The permutations function returns the list of all permutations of the argument.

 permutations "abc" == ["abc","bac","cba","bca","cab","acb"]

mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

The mapAccumL function behaves like a combination of fmap and foldl; it applies a function to each element of a structure, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new structure.

mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

The mapAccumR function behaves like a combination of fmap and foldr; it applies a function to each element of a structure, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new structure.

unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

The unfoldr function is a `dual' to foldr: while foldr reduces a list to a summary value, unfoldr builds a list from a seed value. The function takes the element and returns Nothing if it is done producing the list or returns Just (a,b), in which case, a is a prepended to the list and b is used as the next element in a recursive call. For example,

 iterate f == unfoldr (\x -> Just (x, f x))

In some cases, unfoldr can undo a foldr operation:

 unfoldr f' (foldr f z xs) == xs

if the following holds:

 f' (f x y) = Just (x,y)
 f' z       = Nothing

A simple use of unfoldr:

 unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10
  [10,9,8,7,6,5,4,3,2,1]

stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]

The stripPrefix function drops the given prefix from a list. It returns Nothing if the list did not start with the prefix given, or Just the list after the prefix, if it does.

 stripPrefix "foo" "foobar" == Just "bar"
 stripPrefix "foo" "foo" == Just ""
 stripPrefix "foo" "barfoo" == Nothing
 stripPrefix "foo" "barfoobaz" == Nothing

group :: Eq a => [a] -> [[a]]

The group function takes a list and returns a list of lists such that the concatenation of the result is equal to the argument. Moreover, each sublist in the result contains only equal elements. For example,

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

It is a special case of groupBy, which allows the programmer to supply their own equality test.

inits :: [a] -> [[a]]

The inits function returns all initial segments of the argument, shortest first. For example,

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

Note that inits has the following strictness property: inits _|_ = [] : _|_

tails :: [a] -> [[a]]

The tails function returns all final segments of the argument, longest first. For example,

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

Note that tails has the following strictness property: tails _|_ = _|_ : _|_

isPrefixOf :: Eq a => [a] -> [a] -> Bool

The isPrefixOf function takes two lists and returns True iff the first list is a prefix of the second.

isSuffixOf :: Eq a => [a] -> [a] -> Bool

The isSuffixOf function takes two lists and returns True iff the first list is a suffix of the second. Both lists must be finite.

isInfixOf :: Eq a => [a] -> [a] -> Bool

The isInfixOf function takes two lists and returns True iff the first list is contained, wholly and intact, anywhere within the second.

Example:

isInfixOf "Haskell" "I really like Haskell." == True
isInfixOf "Ial" "I really like Haskell." == False

partition :: (a -> Bool) -> [a] -> ([a], [a])

The partition function takes a predicate a list and returns the pair of lists of elements which do and do not satisfy the predicate, respectively; i.e.,

 partition p xs == (filter p xs, filter (not . p) xs)

elemIndex :: Eq a => a -> [a] -> Maybe Int

The elemIndex function returns the index of the first element in the given list which is equal (by ==) to the query element, or Nothing if there is no such element.

elemIndices :: Eq a => a -> [a] -> [Int]

The elemIndices function extends elemIndex, by returning the indices of all elements equal to the query element, in ascending order.

findIndex :: (a -> Bool) -> [a] -> Maybe Int

The findIndex function takes a predicate and a list and returns the index of the first element in the list satisfying the predicate, or Nothing if there is no such element.

findIndices :: (a -> Bool) -> [a] -> [Int]

The findIndices function extends findIndex, by returning the indices of all elements satisfying the predicate, in ascending order.

zip :: [a] -> [b] -> [(a, b)]

zip takes two lists and returns a list of corresponding pairs. If one input list is short, 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, analogous to zip.

zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]

The zip4 function takes four lists and returns a list of quadruples, analogous to zip.

zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]

The zip5 function takes five lists and returns a list of five-tuples, analogous to zip.

zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]

The zip6 function takes six lists and returns a list of six-tuples, analogous to zip.

zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]

The zip7 function takes seven lists and returns a list of seven-tuples, analogous to zip.

zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

zipWith generalises zip by zipping with the function given as the first argument, instead of a tupling function. For example, zipWith (+) is applied to two lists to produce the list of corresponding sums.

zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]

The zipWith3 function takes a function which combines three elements, as well as three lists and returns a list of their point-wise combination, analogous to zipWith.

zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]

The zipWith4 function takes a function which combines four elements, as well as four lists and returns a list of their point-wise combination, analogous to zipWith.

zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]

The zipWith5 function takes a function which combines five elements, as well as five lists and returns a list of their point-wise combination, analogous to zipWith.

zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]

The zipWith6 function takes a function which combines six elements, as well as six lists and returns a list of their point-wise combination, analogous to zipWith.

zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]

The zipWith7 function takes a function which combines seven elements, as well as seven lists and returns a list of their point-wise combination, analogous to zipWith.

unzip :: [(a, b)] -> ([a], [b])

unzip transforms a list of pairs into a list of first components and a list of second components.

unzip3 :: [(a, b, c)] -> ([a], [b], [c])

The unzip3 function takes a list of triples and returns three lists, analogous to unzip.

unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])

The unzip4 function takes a list of quadruples and returns four lists, analogous to unzip.

unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])

The unzip5 function takes a list of five-tuples and returns five lists, analogous to unzip.

unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])

The unzip6 function takes a list of six-tuples and returns six lists, analogous to unzip.

unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])

The unzip7 function takes a list of seven-tuples and returns seven lists, analogous to unzip.

nub :: Eq a => [a] -> [a]

O(n^2). The nub function removes duplicate elements from a list. In particular, it keeps only the first occurrence of each element. (The name nub means `essence'.) It is a special case of nubBy, which allows the programmer to supply their own equality test.

delete :: Eq a => a -> [a] -> [a]

delete x removes the first occurrence of x from its list argument. For example,

 delete 'a' "banana" == "bnana"

It is a special case of deleteBy, which allows the programmer to supply their own equality test.

union :: Eq a => [a] -> [a] -> [a]

The union function returns the list union of the two lists. For example,

 "dog" `union` "cow" == "dogcw"

Duplicates, and elements of the first list, are removed from the the second list, but if the first list contains duplicates, so will the result. It is a special case of unionBy, which allows the programmer to supply their own equality test.

intersect :: Eq a => [a] -> [a] -> [a]

The intersect function takes the list intersection of two lists. For example,

 [1,2,3,4] `intersect` [2,4,6,8] == [2,4]

If the first list contains duplicates, so will the result.

 [1,2,2,3,4] `intersect` [6,4,4,2] == [2,2,4]

It is a special case of intersectBy, which allows the programmer to supply their own equality test. If the element is found in both the first and the second list, the element from the first list will be used.

sort :: Ord a => [a] -> [a]

The sort function implements a stable sorting algorithm. It is a special case of sortBy, which allows the programmer to supply their own comparison function.

insert :: Ord a => a -> [a] -> [a]

The insert function takes an element and a list and inserts the element into the list at the first position where it is less than or equal to the next element. In particular, if the list is sorted before the call, the result will also be sorted. It is a special case of insertBy, which allows the programmer to supply their own comparison function.

nubBy :: (a -> a -> Bool) -> [a] -> [a]

The nubBy function behaves just like nub, except it uses a user-supplied equality predicate instead of the overloaded == function.

deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]

The deleteBy function behaves like delete, but takes a user-supplied equality predicate.

deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

The deleteFirstsBy function takes a predicate and two lists and returns the first list with the first occurrence of each element of the second list removed.

unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

The unionBy function is the non-overloaded version of union.

intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

The intersectBy function is the non-overloaded version of intersect.

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

The groupBy function is the non-overloaded version of group.

sortBy :: (a -> a -> Ordering) -> [a] -> [a]

The sortBy function is the non-overloaded version of sort.

insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]

The non-overloaded version of insert.

maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

The largest element of a non-empty structure with respect to the given comparison function.

minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

The least element of a non-empty structure with respect to the given comparison function.

lines :: String -> [String]

lines breaks a string up into a list of strings at newline characters. The resulting strings do not contain newlines.

words :: String -> [String]

words breaks a string up into a list of words, which were delimited by white space.

unlines :: [String] -> String

unlines is an inverse operation to lines. It joins lines, after appending a terminating newline to each.

unwords :: [String] -> String

unwords is an inverse operation to words. It joins words with separating spaces.

type ShowS = String -> String

The shows functions return a function that prepends the output String to an existing String. This allows constant-time concatenation of results using function composition.

class Show a where

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 Read:

  • The result of show is 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 showsPrec will produce infix applications of the constructor.
  • the representation will be enclosed in parentheses if the precedence of the top-level constructor in x is less than d (associativity is ignored). Thus, if d is 0 then the result is never surrounded in parentheses; if d is 11 it is always surrounded in parentheses, unless it is an atomic expression.
  • If the constructor is defined using record syntax, then show will 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,

  • show (Leaf 1 :^: Leaf 2 :^: Leaf 3) produces the string "Leaf 1 :^: (Leaf 2 :^: Leaf 3)".

Methods

showsPrec

Arguments

:: Int

the operator precedence of the enclosing context (a number from 0 to 11). Function application has precedence 10.

-> a

the value to be converted to a String

-> 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 Read and Show satisfy the following:

That is, readsPrec parses the string produced by showsPrec, and delivers the value that showsPrec started with.

show :: a -> String

A specialised variant of showsPrec, using precedence context zero, and returning an ordinary String.

showList :: [a] -> ShowS

The method showList is provided to allow the programmer to give a specialised way of showing lists of values. For example, this is used by the predefined Show instance of the Char type, where values of type String should be shown in double quotes, rather than between square brackets.

Instances

Show Bool 
Show Char 
Show Double 
Show Float 
Show Int 
Show Int8 
Show Int16 
Show Int32 
Show Int64 
Show Integer 
Show Ordering 
Show Word 
Show Word8 
Show Word16 
Show Word32 
Show Word64 
Show () 
Show DataType 
Show Constr 
Show DataRep 
Show ConstrRep 
Show Fixity 
Show PatternMatchFail 
Show RecSelError 
Show RecConError 
Show RecUpdError 
Show NoMethodError 
Show NonTermination 
Show NestedAtomically 
Show ThreadId 
Show BlockReason 
Show ThreadStatus 
Show BlockedIndefinitelyOnMVar 
Show BlockedIndefinitelyOnSTM 
Show Deadlock 
Show AssertionFailed 
Show AsyncException 
Show ArrayException 
Show ExitCode 
Show IOErrorType 
Show All 
Show Any 
Show GeneralCategory 
Show MaskingState 
Show IOException 
Show SomeException 
Show ErrorCall 
Show ArithException 
Show TypeRep 
Show TyCon 
Show Version 
Show a => Show [a] 
(Integral a, Show a) => Show (Ratio a) 
Show a => Show (Complex a) 
Show a => Show (Dual a) 
Show a => Show (Sum a) 
Show a => Show (Product a) 
Show a => Show (First a) 
Show a => Show (Last a) 
Show a => Show (Maybe a) 
(Show a, Show b) => Show (Either a b) 
(Show a, Show b) => Show (a, b) 
(Show a, Show b, Show c) => Show (a, b, c) 
(Show a, Show b, Show c, Show d) => Show (a, b, c, d) 
(Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) 
(Show a, Show b, Show c, Show d, Show e, Show f) => Show (a, b, c, d, e, f) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g) => Show (a, b, c, d, e, f, g) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h) => Show (a, b, c, d, e, f, g, h) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i) => Show (a, b, c, d, e, f, g, h, i) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j) => Show (a, b, c, d, e, f, g, h, i, j) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k) => Show (a, b, c, d, e, f, g, h, i, j, k) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l) => Show (a, b, c, d, e, f, g, h, i, j, k, l) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m) => Show (a, b, c, d, e, f, g, h, i, j, k, l, m) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n) => Show (a, b, c, d, e, f, g, h, i, j, k, l, m, n) 
(Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n, Show o) => Show (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) 

shows :: Show a => a -> ShowS

equivalent to showsPrec with a precedence of 0.

showChar :: Char -> ShowS

utility function converting a Char to a show function that simply prepends the character unchanged.

showString :: String -> ShowS

utility function converting a String to a show function that simply prepends the string unchanged.

showParen :: Bool -> ShowS -> ShowS

utility function that surrounds the inner show function with parentheses when the Bool parameter is True.

type ReadS a = String -> [(a, String)]

A parser for a type a, represented as a function that takes a String and returns a list of possible parses as (a,String) pairs.

Note that this kind of backtracking parser is very inefficient; reading a large structure may be quite slow (cf ReadP).

class Read a where

Parsing of Strings, producing values.

Minimal complete definition: readsPrec (or, for GHC only, readPrec)

Derived instances of Read make the following assumptions, which derived instances of Show obey:

  • If the constructor is defined to be an infix operator, then the derived Read instance will parse only infix applications of the constructor (not the prefix form).
  • Associativity is not used to reduce the occurrence of parentheses, although precedence may be.
  • If the constructor is defined using record syntax, the derived Read will parse only the record-syntax form, and furthermore, the fields must be given in the same order as the original declaration.
  • The derived Read instance allows arbitrary Haskell whitespace between tokens of the input string. Extra parentheses are also allowed.

For example, given the declarations

 infixr 5 :^:
 data Tree a =  Leaf a  |  Tree a :^: Tree a

the derived instance of Read in Haskell 98 is equivalent to

 instance (Read a) => Read (Tree a) where

         readsPrec d r =  readParen (d > app_prec)
                          (\r -> [(Leaf m,t) |
                                  ("Leaf",s) <- lex r,
                                  (m,t) <- readsPrec (app_prec+1) s]) r

                       ++ readParen (d > up_prec)
                          (\r -> [(u:^:v,w) |
                                  (u,s) <- readsPrec (up_prec+1) r,
                                  (":^:",t) <- lex s,
                                  (v,w) <- readsPrec (up_prec+1) t]) r

           where app_prec = 10
                 up_prec = 5

Note that right-associativity of :^: is unused.

The derived instance in GHC is equivalent to

 instance (Read a) => Read (Tree a) where

         readPrec = parens $ (prec app_prec $ do
                                  Ident "Leaf" <- lexP
                                  m <- step readPrec
                                  return (Leaf m))

                      +++ (prec up_prec $ do
                                  u <- step readPrec
                                  Symbol ":^:" <- lexP
                                  v <- step readPrec
                                  return (u :^: v))

           where app_prec = 10
                 up_prec = 5

         readListPrec = readListPrecDefault

Methods

readsPrec

Arguments

:: Int

the operator precedence of the enclosing context (a number from 0 to 11). Function application has precedence 10.

-> ReadS a 

attempts to parse a value from the front of the string, returning a list of (parsed value, remaining string) pairs. If there is no successful parse, the returned list is empty.

Derived instances of Read and Show satisfy the following:

That is, readsPrec parses the string produced by showsPrec, and delivers the value that showsPrec started with.

readList :: ReadS [a]

The method readList is provided to allow the programmer to give a specialised way of parsing lists of values. For example, this is used by the predefined Read instance of the Char type, where values of type String should be are expected to use double quotes, rather than square brackets.

Instances

Read Bool 
Read Char 
Read Double 
Read Float 
Read Int 
Read Int8 
Read Int16 
Read Int32 
Read Int64 
Read Integer 
Read Ordering 
Read Word 
Read Word8 
Read Word16 
Read Word32 
Read Word64 
Read () 
Read ExitCode 
Read All 
Read Any 
Read GeneralCategory 
Read Lexeme 
Read Version 
Read a => Read [a] 
(Integral a, Read a) => Read (Ratio a) 
Read a => Read (Complex a) 
Read a => Read (Dual a) 
Read a => Read (Sum a) 
Read a => Read (Product a) 
Read a => Read (First a) 
Read a => Read (Last a) 
Read a => Read (Maybe a) 
(Read a, Read b) => Read (Either a b) 
(Read a, Read b) => Read (a, b) 
(Ix a, Read a, Read b) => Read (Array a b) 
(Read a, Read b, Read c) => Read (a, b, c) 
(Read a, Read b, Read c, Read d) => Read (a, b, c, d) 
(Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) 
(Read a, Read b, Read c, Read d, Read e, Read f) => Read (a, b, c, d, e, f) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g) => Read (a, b, c, d, e, f, g) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h) => Read (a, b, c, d, e, f, g, h) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i) => Read (a, b, c, d, e, f, g, h, i) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i, Read j) => Read (a, b, c, d, e, f, g, h, i, j) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i, Read j, Read k) => Read (a, b, c, d, e, f, g, h, i, j, k) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i, Read j, Read k, Read l) => Read (a, b, c, d, e, f, g, h, i, j, k, l) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i, Read j, Read k, Read l, Read m) => Read (a, b, c, d, e, f, g, h, i, j, k, l, m) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i, Read j, Read k, Read l, Read m, Read n) => Read (a, b, c, d, e, f, g, h, i, j, k, l, m, n) 
(Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i, Read j, Read k, Read l, Read m, Read n, Read o) => Read (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) 

reads :: Read a => ReadS a

equivalent to readsPrec with a precedence of 0.

readParen :: Bool -> ReadS a -> ReadS a

readParen True p parses what p parses, but surrounded with parentheses.

readParen False p parses what p parses, but optionally surrounded with parentheses.

read :: Read a => String -> a

The read function reads input from a string, which must be completely consumed by the input process.

lex :: ReadS String

The lex function reads a single lexeme from the input, discarding initial white space, and returning the characters that constitute the lexeme. If the input string contains only white space, lex returns a single successful `lexeme' consisting of the empty string. (Thus lex "" = [("","")].) If there is no legal lexeme at the beginning of the input string, lex fails (i.e. returns []).

This lexer is not completely faithful to the Haskell lexical syntax in the following respects:

  • Qualified names are not handled properly
  • Octal and hexadecimal numerics are not recognized as a single token
  • Comments are not treated properly

data IO a

A value of type IO a is a computation which, when performed, does some I/O before returning a value of type a.

There is really only one way to "perform" an I/O action: bind it to Main.main in your program. When your program is run, the I/O will be performed. It isn't possible to perform I/O from an arbitrary function, unless that function is itself in the IO monad and called at some point, directly or indirectly, from Main.main.

IO is a monad, so IO actions can be combined using either the do-notation or the >> and >>= operations from the Monad class.

putChar :: Char -> IO ()

Write a character to the standard output device (same as hPutChar stdout).

putStr :: String -> IO ()

Write a string to the standard output device (same as hPutStr stdout).

putStrLn :: String -> IO ()

The same as putStr, but adds a newline character.

print :: Show a => a -> IO ()

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

getChar :: IO Char

Read a character from the standard input device (same as hGetChar stdin).

getLine :: IO String

Read a line from the standard input device (same as hGetLine stdin).

getContents :: IO String

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

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.

readFile :: FilePath -> IO String

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

The computation writeFile file str function writes the string str, to the file file.

appendFile :: FilePath -> String -> IO ()

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

readIO :: Read a => String -> IO a

The readIO function is similar to read except that it signals parse failure to the IO monad instead of terminating the program.

readLn :: Read a => IO a

The readLn function combines getLine and readIO.

(->>) :: a -> (a -> b) -> bSource

flip ($), fixity is infixl 1 (like >>= but for non-monadic functions)

data SomeException

The SomeException type is the root of the exception type hierarchy. When an exception of type e is thrown, behind the scenes it is encapsulated in a SomeException.

class (Typeable e, Show e) => Exception e where

Any type that you wish to throw or catch as an exception must be an instance of the Exception class. The simplest case is a new exception type directly below the root:

 data MyException = ThisException | ThatException
     deriving (Show, Typeable)

 instance Exception MyException

The default method definitions in the Exception class do what we need in this case. You can now throw and catch ThisException and ThatException as exceptions:

*Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
Caught ThisException

In more complicated examples, you may wish to define a whole hierarchy of exceptions:

 ---------------------------------------------------------------------
 -- Make the root exception type for all the exceptions in a compiler

 data SomeCompilerException = forall e . Exception e => SomeCompilerException e
     deriving Typeable

 instance Show SomeCompilerException where
     show (SomeCompilerException e) = show e

 instance Exception SomeCompilerException

 compilerExceptionToException :: Exception e => e -> SomeException
 compilerExceptionToException = toException . SomeCompilerException

 compilerExceptionFromException :: Exception e => SomeException -> Maybe e
 compilerExceptionFromException x = do
     SomeCompilerException a <- fromException x
     cast a

 ---------------------------------------------------------------------
 -- Make a subhierarchy for exceptions in the frontend of the compiler

 data SomeFrontendException = forall e . Exception e => SomeFrontendException e
     deriving Typeable

 instance Show SomeFrontendException where
     show (SomeFrontendException e) = show e

 instance Exception SomeFrontendException where
     toException = compilerExceptionToException
     fromException = compilerExceptionFromException

 frontendExceptionToException :: Exception e => e -> SomeException
 frontendExceptionToException = toException . SomeFrontendException

 frontendExceptionFromException :: Exception e => SomeException -> Maybe e
 frontendExceptionFromException x = do
     SomeFrontendException a <- fromException x
     cast a

 ---------------------------------------------------------------------
 -- Make an exception type for a particular frontend compiler exception

 data MismatchedParentheses = MismatchedParentheses
     deriving (Typeable, Show)

 instance Exception MismatchedParentheses where
     toException   = frontendExceptionToException
     fromException = frontendExceptionFromException

We can now catch a MismatchedParentheses exception as MismatchedParentheses, SomeFrontendException or SomeCompilerException, but not other types, e.g. IOException:

*Main> throw MismatchedParentheses catch e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses catch e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses catch e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses catch e -> putStrLn ("Caught " ++ show (e :: IOException))
*** Exception: MismatchedParentheses

data IOException

Exceptions that occur in the IO monad. An IOException records a more specific error type, a descriptive string and maybe the handle that was used when the error was flagged.

ioError :: IOError -> IO a

Raise an IOError in the IO monad.

userError :: String -> IOError

Construct an IOError value with a string describing the error. The fail method of the IO instance of the Monad class raises a userError, thus:

 instance Monad IO where 
   ...
   fail s = ioError (userError s)

throw :: Exception e => e -> a

Throw an exception. Exceptions may be thrown from purely functional code, but may only be caught within the IO monad.

throwIO :: Exception e => e -> IO a

A variant of throw that can only be used within the IO monad.

Although throwIO has a type that is an instance of the type of throw, the two functions are subtly different:

 throw e   `seq` x  ===> throw e
 throwIO e `seq` x  ===> x

The first example will cause the exception e to be raised, whereas the second one won't. In fact, throwIO will only cause an exception to be raised when it is used within the IO monad. The throwIO variant should be used in preference to throw to raise an exception within the IO monad because it guarantees ordering with respect to other IO operations, whereas throw does not.

throwTo :: Exception e => ThreadId -> e -> IO ()

throwTo raises an arbitrary exception in the target thread (GHC only).

throwTo does not return until the exception has been raised in the target thread. The calling thread can thus be certain that the target thread has received the exception. This is a useful property to know when dealing with race conditions: eg. if there are two threads that can kill each other, it is guaranteed that only one of the threads will get to kill the other.

Whatever work the target thread was doing when the exception was raised is not lost: the computation is suspended until required by another thread.

If the target thread is currently making a foreign call, then the exception will not be raised (and hence throwTo will not return) until the call has completed. This is the case regardless of whether the call is inside a mask or not. However, in GHC a foreign call can be annotated as interruptible, in which case a throwTo will cause the RTS to attempt to cause the call to return; see the GHC documentation for more details.

Important note: the behaviour of throwTo differs from that described in the paper "Asynchronous exceptions in Haskell" (http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm). In the paper, throwTo is non-blocking; but the library implementation adopts a more synchronous design in which throwTo does not return until the exception is received by the target thread. The trade-off is discussed in Section 9 of the paper. Like any blocking operation, throwTo is therefore interruptible (see Section 5.3 of the paper). Unlike other interruptible operations, however, throwTo is always interruptible, even if it does not actually block.

There is no guarantee that the exception will be delivered promptly, although the runtime will endeavour to ensure that arbitrary delays don't occur. In GHC, an exception can only be raised when a thread reaches a safe point, where a safe point is where memory allocation occurs. Some loops do not perform any memory allocation inside the loop and therefore cannot be interrupted by a throwTo.

If the target of throwTo is the calling thread, then the behaviour is the same as throwIO, except that the exception is thrown as an asynchronous exception. This means that if there is an enclosing pure computation, which would be the case if the current IO operation is inside unsafePerformIO or unsafeInterleaveIO, that computation is not permanently replaced by the exception, but is suspended as if it had received an asynchronous exception.

Note that if throwTo is called with the current thread as the target, the exception will be thrown even if the thread is currently inside mask or uninterruptibleMask.

catch

Arguments

:: Exception e 
=> IO a

The computation to run

-> (e -> IO a)

Handler to invoke if an exception is raised

-> IO a 

This is the simplest of the exception-catching functions. It takes a single argument, runs it, and if an exception is raised the "handler" is executed, with the value of the exception passed as an argument. Otherwise, the result is returned as normal. For example:

   catch (readFile f)
         (\e -> do let err = show (e :: IOException)
                   hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
                   return "")

Note that we have to give a type signature to e, or the program will not typecheck as the type is ambiguous. While it is possible to catch exceptions of any type, see the section "Catching all exceptions" (in Control.Exception) for an explanation of the problems with doing so.

For catching exceptions in pure (non-IO) expressions, see the function evaluate.

Note that due to Haskell's unspecified evaluation order, an expression may throw one of several possible exceptions: consider the expression (error "urk") + (1 `div` 0). Does the expression throw ErrorCall "urk", or DivideByZero?

The answer is "it might throw either"; the choice is non-deterministic. If you are catching any type of exception then you might catch either. If you are calling catch with type IO Int -> (ArithException -> IO Int) -> IO Int then the handler may get run with DivideByZero as an argument, or an ErrorCall "urk" exception may be propogated further up. If you call it again, you might get a the opposite behaviour. This is ok, because catch is an IO computation.

catches :: IO a -> [Handler a] -> IO a

Sometimes you want to catch two different sorts of exception. You could do something like

 f = expr `catch` \ (ex :: ArithException) -> handleArith ex
          `catch` \ (ex :: IOException)    -> handleIO    ex

However, there are a couple of problems with this approach. The first is that having two exception handlers is inefficient. However, the more serious issue is that the second exception handler will catch exceptions in the first, e.g. in the example above, if handleArith throws an IOException then the second exception handler will catch it.

Instead, we provide a function catches, which would be used thus:

 f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),
                     Handler (\ (ex :: IOException)    -> handleIO    ex)]

data Handler a where

You need this when using catches.

Constructors

Handler :: Exception e => (e -> IO a) -> Handler a 

Instances

catchJust

Arguments

:: Exception e 
=> (e -> Maybe b)

Predicate to select exceptions

-> IO a

Computation to run

-> (b -> IO a)

Handler

-> IO a 

The function catchJust is like catch, but it takes an extra argument which is an exception predicate, a function which selects which type of exceptions we're interested in.

 catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
           (readFile f)
           (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
                     return "")

Any other exceptions which are not matched by the predicate are re-raised, and may be caught by an enclosing catch, catchJust, etc.

handle :: Exception e => (e -> IO a) -> IO a -> IO a

A version of catch with the arguments swapped around; useful in situations where the code for the handler is shorter. For example:

   do handle (\NonTermination -> exitWith (ExitFailure 1)) $
      ...

handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a

A version of catchJust with the arguments swapped around (see handle).

try :: Exception e => IO a -> IO (Either e a)

Similar to catch, but returns an Either result which is (Right a) if no exception of type e was raised, or (Left ex) if an exception of type e was raised and its value is ex. If any other type of exception is raised than it will be propogated up to the next enclosing exception handler.

  try a = catch (Right `liftM` a) (return . Left)

Note that System.IO.Error also exports a function called try with a similar type to try, except that it catches only the IO and user families of exceptions (as required by the Haskell 98 IO module).

tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)

A variant of try that takes an exception predicate to select which exceptions are caught (c.f. catchJust). If the exception does not match the predicate, it is re-thrown.

evaluate :: a -> IO a

Forces its argument to be evaluated to weak head normal form when the resultant IO action is executed. It can be used to order evaluation with respect to other IO operations; its semantics are given by

   evaluate x `seq` y    ==>  y
   evaluate x `catch` f  ==>  (return $! x) `catch` f
   evaluate x >>= f      ==>  (return $! x) >>= f

Note: the first equation implies that (evaluate x) is not the same as (return $! x). A correct definition is

   evaluate x = (return $! x) >>= return

mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a

This function maps one exception into another as proposed in the paper "A semantics for imprecise exceptions".

mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b

Executes an IO computation with asynchronous exceptions masked. That is, any thread which attempts to raise an exception in the current thread with throwTo will be blocked until asynchronous exceptions are unmasked again.

The argument passed to mask is a function that takes as its argument another function, which can be used to restore the prevailing masking state within the context of the masked computation. For example, a common way to use mask is to protect the acquisition of a resource:

 mask $ \restore -> do
     x <- acquire
     restore (do_something_with x) `onException` release
     release

This code guarantees that acquire is paired with release, by masking asynchronous exceptions for the critical parts. (Rather than write this code yourself, it would be better to use bracket which abstracts the general pattern).

Note that the restore action passed to the argument to mask does not necessarily unmask asynchronous exceptions, it just restores the masking state to that of the enclosing context. Thus if asynchronous exceptions are already masked, mask cannot be used to unmask exceptions again. This is so that if you call a library function with exceptions masked, you can be sure that the library call will not be able to unmask exceptions again. If you are writing library code and need to use asynchronous exceptions, the only way is to create a new thread; see forkIOWithUnmask.

Asynchronous exceptions may still be received while in the masked state if the masked thread blocks in certain ways; see Control.Exception.

Threads created by forkIO inherit the masked state from the parent; that is, to start a thread in blocked mode, use mask_ $ forkIO .... This is particularly useful if you need to establish an exception handler in the forked thread before any asynchronous exceptions are received. To create a a new thread in an unmasked state use forkIOUnmasked.

mask_ :: IO a -> IO a

Like mask, but does not pass a restore action to the argument.

uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b

Like mask, but the masked computation is not interruptible (see Control.Exception). THIS SHOULD BE USED WITH GREAT CARE, because if a thread executing in uninterruptibleMask blocks for any reason, then the thread (and possibly the program, if this is the main thread) will be unresponsive and unkillable. This function should only be necessary if you need to mask exceptions around an interruptible operation, and you can guarantee that the interruptible operation will only block for a short period of time.

uninterruptibleMask_ :: IO a -> IO a

Like uninterruptibleMask, but does not pass a restore action to the argument.

getMaskingState :: IO MaskingState

Returns the MaskingState for the current thread.

allowInterrupt :: IO ()

When invoked inside mask, this function allows a blocked asynchronous exception to be raised, if one exists. It is equivalent to performing an interruptible operation (see ), but does not involve any actual blocking.

When called outside mask, or inside uninterruptibleMask, this function has no effect.

assert :: Bool -> a -> a

If the first argument evaluates to True, then the result is the second argument. Otherwise an AssertionFailed exception is raised, containing a String with the source file and line number of the call to assert.

Assertions can normally be turned on or off with a compiler flag (for GHC, assertions are normally on unless optimisation is turned on with -O or the -fignore-asserts option is given). When assertions are turned off, the first argument to assert is ignored, and the second argument is returned as the result.

bracket

Arguments

:: IO a

computation to run first ("acquire resource")

-> (a -> IO b)

computation to run last ("release resource")

-> (a -> IO c)

computation to run in-between

-> IO c 

When you want to acquire a resource, do some work with it, and then release the resource, it is a good idea to use bracket, because bracket will install the necessary exception handler to release the resource in the event that an exception is raised during the computation. If an exception is raised, then bracket will re-raise the exception (after performing the release).

A common example is opening a file:

 bracket
   (openFile "filename" ReadMode)
   (hClose)
   (\fileHandle -> do { ... })

The arguments to bracket are in this order so that we can partially apply it, e.g.:

 withFile name mode = bracket (openFile name mode) hClose

bracket_ :: IO a -> IO b -> IO c -> IO c

A variant of bracket where the return value from the first computation is not required.

bracketOnError

Arguments

:: IO a

computation to run first ("acquire resource")

-> (a -> IO b)

computation to run last ("release resource")

-> (a -> IO c)

computation to run in-between

-> IO c 

Like bracket, but only performs the final action if there was an exception raised by the in-between computation.

finally

Arguments

:: IO a

computation to run first

-> IO b

computation to run afterward (even if an exception was raised)

-> IO a 

A specialised variant of bracket with just a computation to run afterward.

onException :: IO a -> IO b -> IO a

Like finally, but only performs the final action if there was an exception raised by the computation.

class Typeable a => Data a where

The Data class comprehends a fundamental primitive gfoldl for folding over constructor applications, say terms. This primitive can be instantiated in several ways to map over the immediate subterms of a term; see the gmap combinators later in this class. Indeed, a generic programmer does not necessarily need to use the ingenious gfoldl primitive but rather the intuitive gmap combinators. The gfoldl primitive is completed by means to query top-level constructors, to turn constructor representations into proper terms, and to list all possible datatype constructors. This completion allows us to serve generic programming scenarios like read, show, equality, term generation.

The combinators gmapT, gmapQ, gmapM, etc are all provided with default definitions in terms of gfoldl, leaving open the opportunity to provide datatype-specific definitions. (The inclusion of the gmap combinators as members of class Data allows the programmer or the compiler to derive specialised, and maybe more efficient code per datatype. Note: gfoldl is more higher-order than the gmap combinators. This is subject to ongoing benchmarking experiments. It might turn out that the gmap combinators will be moved out of the class Data.)

Conceptually, the definition of the gmap combinators in terms of the primitive gfoldl requires the identification of the gfoldl function arguments. Technically, we also need to identify the type constructor c for the construction of the result type from the folded term type.

In the definition of gmapQx combinators, we use phantom type constructors for the c in the type of gfoldl because the result type of a query does not involve the (polymorphic) type of the term argument. In the definition of gmapQl we simply use the plain constant type constructor because gfoldl is left-associative anyway and so it is readily suited to fold a left-associative binary operation over the immediate subterms. In the definition of gmapQr, extra effort is needed. We use a higher-order accumulation trick to mediate between left-associative constructor application vs. right-associative binary operation (e.g., (:)). When the query is meant to compute a value of type r, then the result type withing generic folding is r -> r. So the result of folding is a function to which we finally pass the right unit.

With the -XDeriveDataTypeable option, GHC can generate instances of the Data class automatically. For example, given the declaration

 data T a b = C1 a b | C2 deriving (Typeable, Data)

GHC will generate an instance that is equivalent to

 instance (Data a, Data b) => Data (T a b) where
     gfoldl k z (C1 a b) = z C1 `k` a `k` b
     gfoldl k z C2       = z C2

     gunfold k z c = case constrIndex c of
                         1 -> k (k (z C1))
                         2 -> z C2

     toConstr (C1 _ _) = con_C1
     toConstr C2       = con_C2

     dataTypeOf _ = ty_T

 con_C1 = mkConstr ty_T "C1" [] Prefix
 con_C2 = mkConstr ty_T "C2" [] Prefix
 ty_T   = mkDataType "Module.T" [con_C1, con_C2]

This is suitable for datatypes that are exported transparently.

Methods

gfoldl

Arguments

:: (forall d b. Data d => c (d -> b) -> d -> c b)

defines how nonempty constructor applications are folded. It takes the folded tail of the constructor application and its head, i.e., an immediate subterm, and combines them in some way.

-> (forall g. g -> c g)

defines how the empty constructor application is folded, like the neutral / start element for list folding.

-> a

structure to be folded.

-> c a

result, with a type defined in terms of a, but variability is achieved by means of type constructor c for the construction of the actual result type.

Left-associative fold operation for constructor applications.

The type of gfoldl is a headache, but operationally it is a simple generalisation of a list fold.

The default definition for gfoldl is const id, which is suitable for abstract datatypes with no substructures.

gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a

Unfolding constructor applications

toConstr :: a -> Constr

Obtaining the constructor from a given datum. For proper terms, this is meant to be the top-level constructor. Primitive datatypes are here viewed as potentially infinite sets of values (i.e., constructors).

dataTypeOf :: a -> DataType

The outer type constructor of the type

dataCast1 :: Typeable1 t => (forall d. Data d => c (t d)) -> Maybe (c a)

Mediate types and unary type constructors. In Data instances of the form T a, dataCast1 should be defined as gcast1.

The default definition is const Nothing, which is appropriate for non-unary type constructors.

dataCast2 :: Typeable2 t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a)

Mediate types and binary type constructors. In Data instances of the form T a b, dataCast2 should be defined as gcast2.

The default definition is const Nothing, which is appropriate for non-binary type constructors.

gmapT :: (forall b. Data b => b -> b) -> a -> a

A generic transformation that maps over the immediate subterms

The default definition instantiates the type constructor c in the type of gfoldl to an identity datatype constructor, using the isomorphism pair as injection and projection.

gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r

A generic query with a left-associative binary operator

gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r

A generic query with a right-associative binary operator

gmapQ :: (forall d. Data d => d -> u) -> a -> [u]

A generic query that processes the immediate subterms and returns a list of results. The list is given in the same order as originally specified in the declaratoin of the data constructors.

gmapQi :: Int -> (forall d. Data d => d -> u) -> a -> u

A generic query that processes one child by index (zero-based)

gmapM :: Monad m => (forall d. Data d => d -> m d) -> a -> m a

A generic monadic transformation that maps over the immediate subterms

The default definition instantiates the type constructor c in the type of gfoldl to the monad datatype constructor, defining injection and projection using return and >>=.

gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a

Transformation of at least one immediate subterm does not fail

gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a

Transformation of one immediate subterm with success

Instances

Data Bool 
Data Char 
Data Double 
Data Float 
Data Int 
Data Int8 
Data Int16 
Data Int32 
Data Int64 
Data Integer 
Data Ordering 
Data Word 
Data Word8 
Data Word16 
Data Word32 
Data Word64 
Data () 
Data a => Data [a] 
(Data a, Integral a) => Data (Ratio a) 
Typeable a => Data (Ptr a) 
Data a => Data (Complex a) 
Typeable a => Data (ForeignPtr a) 
Data a => Data (Maybe a) 
(Data a, Data b) => Data (Either a b) 
(Data a, Data b) => Data (a, b) 
(Typeable a, Data b, Ix a) => Data (Array a b) 
(Data a, Data b, Data c) => Data (a, b, c) 
(Data a, Data b, Data c, Data d) => Data (a, b, c, d) 
(Data a, Data b, Data c, Data d, Data e) => Data (a, b, c, d, e) 
(Data a, Data b, Data c, Data d, Data e, Data f) => Data (a, b, c, d, e, f) 
(Data a, Data b, Data c, Data d, Data e, Data f, Data g) => Data (a, b, c, d, e, f, g) 

exhaustively :: Eq a => (a -> a) -> a -> aSource

Apply a function exhaustively.

exhaustivelyM :: (Eq a, Monad m) => (a -> m a) -> a -> m aSource

Apply a monadic function exhaustively.

exhaustivelyBy :: (a -> a -> Bool) -> (a -> a) -> a -> aSource

Apply a function exhaustively.

exhaustivelyByM :: Monad m => (a -> a -> Bool) -> (a -> m a) -> a -> m aSource

Apply a monadic function exhaustively.

uniqSort :: Ord a => [a] -> [a]Source

Sort a list and leave out duplicates. Like nub . sort but faster.

aggregate :: Ord a => [a] -> [[a]]Source

Sort, then group

aggregateBy :: (a -> a -> Ordering) -> [a] -> [[a]]Source

Sort, then group

aggregateAL :: Ord a => [(a, b)] -> [(a, [b])]Source

Aggregate an association list, such that keys become unique.

(c)

tr :: Eq a => a -> a -> [a] -> [a]Source

Replace all occurences of a specific thing in a list of things another thing.

segment2 :: Int -> [[a]] -> [[a]]Source

Segments the elements of a 2 levels deep list such that the segments contain at least the specified amount of elements, without breaking apart any subsegments.

segment3 :: Int -> [[[a]]] -> [[a]]Source

Segments the elements of a 3 levels deep list such that the segments contain at least the specified amount of elements, without breaking apart any subsegments.

count2 :: [[a]] -> IntSource

Counts how many elements there are in a 2 levels deep list.

count3 :: [[[a]]] -> IntSource

Counts how many elements there are in a 3 levels deep list.

count4 :: [[[[a]]]] -> IntSource

Counts how many elements there are in a 4 levels deep list.