Safe Haskell | Safe |
---|
- data Bool
- (&&) :: Bool -> Bool -> Bool
- (||) :: Bool -> Bool -> Bool
- not :: Bool -> Bool
- otherwise :: Bool
- data Maybe a
- maybe :: b -> (a -> b) -> Maybe a -> b
- isJust :: Maybe a -> Bool
- isNothing :: Maybe a -> Bool
- fromJust :: Maybe a -> a
- fromMaybe :: a -> Maybe a -> a
- listToMaybe :: [a] -> Maybe a
- maybeToList :: Maybe a -> [a]
- catMaybes :: [Maybe a] -> [a]
- mapMaybe :: (a -> Maybe b) -> [a] -> [b]
- data Either a b
- either :: (a -> c) -> (b -> c) -> Either a b -> c
- lefts :: [Either a b] -> [a]
- rights :: [Either a b] -> [b]
- partitionEithers :: [Either a b] -> ([a], [b])
- uneither :: Either a a -> a
- data Ordering
- data Char
- isControl :: Char -> Bool
- isSpace :: Char -> Bool
- isLower :: Char -> Bool
- isUpper :: Char -> Bool
- isAlpha :: Char -> Bool
- isAlphaNum :: Char -> Bool
- isPrint :: Char -> Bool
- isDigit :: Char -> Bool
- isOctDigit :: Char -> Bool
- isHexDigit :: Char -> Bool
- isLetter :: Char -> Bool
- isMark :: Char -> Bool
- isNumber :: Char -> Bool
- isPunctuation :: Char -> Bool
- isSymbol :: Char -> Bool
- isSeparator :: Char -> Bool
- isAscii :: Char -> Bool
- isLatin1 :: Char -> Bool
- isAsciiUpper :: Char -> Bool
- isAsciiLower :: Char -> Bool
- class IsString a where
- fromString :: String -> a
- toUpper :: Char -> Char
- toLower :: Char -> Char
- toTitle :: Char -> Char
- digitToInt :: Char -> Int
- intToDigit :: Int -> Char
- ord :: Char -> Int
- chr :: Int -> Char
- class AtLeastPair a where
- curry :: ((a, b) -> c) -> a -> b -> c
- uncurry :: (a -> b -> c) -> (a, b) -> c
- swap :: (a, b) -> (b, a)
- class Eq a where
- class Eq a => Ord a where
- class Enum a where
- succ :: a -> a
- pred :: a -> a
- toEnum :: Int -> a
- fromEnum :: a -> Int
- enumFrom :: a -> [a]
- enumFromThen :: a -> a -> [a]
- enumFromTo :: a -> a -> [a]
- enumFromThenTo :: a -> a -> a -> [a]
- class Bounded a where
- data Int
- data Integer
- data Float
- data Double
- data Int8
- data Int16
- data Int32
- data Int64
- data Word8
- data Word16
- data Word32
- data Word64
- type Rational = Ratio Integer
- data Ratio a
- class Num a where
- class (Num a, Ord a) => Real a where
- toRational :: a -> Rational
- class (Real a, Enum a) => Integral a where
- class Num a => Fractional a where
- (/) :: a -> a -> a
- recip :: a -> a
- fromRational :: Rational -> a
- class Fractional a => Floating a where
- class (Real a, Fractional a) => RealFrac a where
- class (RealFrac a, Floating a) => RealFloat a where
- floatRadix :: a -> Integer
- floatDigits :: a -> Int
- floatRange :: a -> (Int, Int)
- decodeFloat :: a -> (Integer, Int)
- encodeFloat :: Integer -> Int -> a
- exponent :: a -> Int
- significand :: a -> a
- scaleFloat :: Int -> a -> a
- isNaN :: a -> Bool
- isInfinite :: a -> Bool
- isDenormalized :: a -> Bool
- isNegativeZero :: a -> Bool
- isIEEE :: a -> Bool
- atan2 :: a -> a -> a
- data Complex a
- realPart :: RealFloat a => Complex a -> a
- imagPart :: RealFloat a => Complex a -> a
- mkPolar :: RealFloat a => a -> a -> Complex a
- cis :: RealFloat a => a -> Complex a
- polar :: RealFloat a => Complex a -> (a, a)
- magnitude :: RealFloat a => Complex a -> a
- phase :: RealFloat a => Complex a -> a
- conjugate :: RealFloat a => Complex a -> Complex a
- subtract :: Num a => a -> a -> a
- even :: Integral a => a -> Bool
- odd :: Integral a => a -> Bool
- gcd :: Integral a => a -> a -> a
- lcm :: Integral a => a -> a -> a
- (^) :: (Num a, Integral b) => a -> b -> a
- (^^) :: (Fractional a, Integral b) => a -> b -> a
- fromIntegral :: (Integral a, Num b) => a -> b
- realToFrac :: (Real a, Fractional b) => a -> b
- class Functor f where
- id :: Category cat => forall a. cat a a
- const :: a -> b -> a
- (.) :: Category cat => forall b c a. cat b c -> cat a b -> cat a c
- flip :: (a -> b -> c) -> b -> a -> c
- ($) :: (a -> b) -> a -> b
- fix :: (a -> a) -> a
- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
- until :: (a -> Bool) -> (a -> a) -> a -> a
- asTypeOf :: a -> a -> a
- error :: [Char] -> a
- undefined :: a
- seq :: a -> b -> b
- ($!) :: (a -> b) -> a -> b
- class Functor f => Applicative f where
- class Monad m where
- (=<<) :: Monad m => (a -> m b) -> m a -> m b
- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
- forever :: Monad m => m a -> m b
- void :: Functor f => f a -> f ()
- join :: Monad m => m (m a) -> m a
- class Monad m => MonadPlus m where
- mapM :: Monad m => (a -> m b) -> [a] -> m [b]
- mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
- forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
- forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
- sequence :: Monad m => [m a] -> m [a]
- sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
- msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
- mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
- filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]
- mapAndUnzipM :: Monad m => (a -> m (b, c)) -> [a] -> m ([b], [c])
- zipWithM :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m [c]
- zipWithM_ :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m ()
- foldM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
- foldM_ :: Monad m => (a -> b -> m a) -> a -> [b] -> m ()
- replicateM :: Monad m => Int -> m a -> m [a]
- replicateM_ :: Monad m => Int -> m a -> m ()
- guard :: MonadPlus m => Bool -> m ()
- when :: Monad m => Bool -> m () -> m ()
- unless :: Monad m => Bool -> m () -> m ()
- liftM :: Monad m => (a1 -> r) -> m a1 -> m r
- liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
- liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
- liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
- liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
- ap :: Monad m => m (a -> b) -> m a -> m b
- class Monoid a where
- (<>) :: Monoid m => m -> m -> m
- newtype Dual a = Dual {
- getDual :: a
- newtype Endo a = Endo {
- appEndo :: a -> a
- newtype All = All {}
- newtype Any = Any {}
- newtype Sum a = Sum {
- getSum :: a
- newtype Product a = Product {
- getProduct :: a
- newtype First a = First {}
- newtype Last a = Last {}
- class Applicative f => Alternative f where
- newtype Const a b = Const {
- getConst :: a
- newtype WrappedMonad m a = WrapMonad {
- unwrapMonad :: m a
- newtype WrappedArrow a b c = WrapArrow {
- unwrapArrow :: a b c
- newtype ZipList a = ZipList {
- getZipList :: [a]
- (<$>) :: Functor f => (a -> b) -> f a -> f b
- (<**>) :: Applicative f => f a -> f (a -> b) -> f b
- liftA :: Applicative f => (a -> b) -> f a -> f b
- liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
- liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
- optional :: Alternative f => f a -> f (Maybe a)
- class Category a => Arrow a where
- newtype Kleisli m a b = Kleisli {
- runKleisli :: a -> m b
- returnA :: Arrow a => a b b
- (^>>) :: Arrow a => (b -> c) -> a c d -> a b d
- (>>^) :: Arrow a => a b c -> (c -> d) -> a b d
- (>>>) :: Category cat => cat a b -> cat b c -> cat a c
- (<<<) :: Category cat => cat b c -> cat a b -> cat a c
- (<<^) :: Arrow a => a c d -> (b -> c) -> a b d
- (^<<) :: Arrow a => (c -> d) -> a b c -> a b d
- class Arrow a => ArrowZero a where
- zeroArrow :: a b c
- class ArrowZero a => ArrowPlus a where
- (<+>) :: a b c -> a b c -> a b c
- class Arrow a => ArrowChoice a where
- class Arrow a => ArrowApply a where
- app :: a (a b c, b) c
- newtype ArrowMonad a b = ArrowMonad (a () b)
- leftApp :: ArrowApply a => a b c -> a (Either b d) (Either c d)
- class Arrow a => ArrowLoop a where
- loop :: a (b, d) (c, d) -> a b c
- map :: Functor f => (a -> b) -> f a -> f b
- (++) :: [a] -> [a] -> [a]
- (!!) :: [a] -> Int -> a
- reverse :: [a] -> [a]
- filter :: (a -> Bool) -> [a] -> [a]
- head :: [a] -> a
- last :: [a] -> a
- tail :: [a] -> [a]
- init :: [a] -> [a]
- null :: [a] -> Bool
- length :: [a] -> Int
- class (Functor t, Foldable t) => Traversable t where
- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
- sequenceA :: Applicative f => t (f a) -> f (t a)
- class Foldable t where
- foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b
- foldlM :: (Foldable t, Monad m) => (a -> b -> m a) -> a -> t b -> m a
- traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
- for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()
- sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
- asum :: (Foldable t, Alternative f) => t (f a) -> f a
- foldl' :: Foldable t => forall a b. (a -> b -> a) -> a -> t b -> a
- foldr' :: Foldable t => forall a b. (a -> b -> b) -> b -> t a -> b
- toList :: Foldable t => t a -> [a]
- find :: Foldable t => (a -> Bool) -> t a -> Maybe a
- and :: Foldable t => t Bool -> Bool
- or :: Foldable t => t Bool -> Bool
- any :: Foldable t => (a -> Bool) -> t a -> Bool
- all :: Foldable t => (a -> Bool) -> t a -> Bool
- sum :: (Foldable t, Num a) => t a -> a
- product :: (Foldable t, Num a) => t a -> a
- concat :: Foldable t => t [a] -> [a]
- concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
- maximum :: (Foldable t, Ord a) => t a -> a
- minimum :: (Foldable t, Ord a) => t a -> a
- scanl :: (a -> b -> a) -> a -> [b] -> [a]
- scanl1 :: (a -> a -> a) -> [a] -> [a]
- scanr :: (a -> b -> b) -> b -> [a] -> [b]
- scanr1 :: (a -> a -> a) -> [a] -> [a]
- iterate :: (a -> a) -> a -> [a]
- repeat :: a -> [a]
- replicate :: Int -> a -> [a]
- cycle :: [a] -> [a]
- take :: Int -> [a] -> [a]
- drop :: Int -> [a] -> [a]
- splitAt :: Int -> [a] -> ([a], [a])
- takeWhile :: (a -> Bool) -> [a] -> [a]
- dropWhile :: (a -> Bool) -> [a] -> [a]
- span :: (a -> Bool) -> [a] -> ([a], [a])
- break :: (a -> Bool) -> [a] -> ([a], [a])
- elem :: (Foldable t, Eq a) => a -> t a -> Bool
- notElem :: (Foldable t, Eq a) => a -> t a -> Bool
- lookup :: Eq a => a -> [(a, b)] -> Maybe b
- intersperse :: a -> [a] -> [a]
- intercalate :: [a] -> [[a]] -> [a]
- transpose :: [[a]] -> [[a]]
- subsequences :: [a] -> [[a]]
- permutations :: [a] -> [[a]]
- mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
- mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
- stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
- group :: Eq a => [a] -> [[a]]
- inits :: [a] -> [[a]]
- tails :: [a] -> [[a]]
- isPrefixOf :: Eq a => [a] -> [a] -> Bool
- isSuffixOf :: Eq a => [a] -> [a] -> Bool
- isInfixOf :: Eq a => [a] -> [a] -> Bool
- partition :: (a -> Bool) -> [a] -> ([a], [a])
- elemIndex :: Eq a => a -> [a] -> Maybe Int
- elemIndices :: Eq a => a -> [a] -> [Int]
- findIndex :: (a -> Bool) -> [a] -> Maybe Int
- findIndices :: (a -> Bool) -> [a] -> [Int]
- zip :: [a] -> [b] -> [(a, b)]
- zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
- zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
- zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]
- zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]
- zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]
- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
- zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
- zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]
- zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]
- zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]
- unzip :: [(a, b)] -> ([a], [b])
- unzip3 :: [(a, b, c)] -> ([a], [b], [c])
- unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])
- unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])
- unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])
- unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])
- nub :: Eq a => [a] -> [a]
- delete :: Eq a => a -> [a] -> [a]
- union :: Eq a => [a] -> [a] -> [a]
- intersect :: Eq a => [a] -> [a] -> [a]
- sort :: Ord a => [a] -> [a]
- insert :: Ord a => a -> [a] -> [a]
- nubBy :: (a -> a -> Bool) -> [a] -> [a]
- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
- deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
- sortBy :: (a -> a -> Ordering) -> [a] -> [a]
- insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
- maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
- minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
- lines :: String -> [String]
- words :: String -> [String]
- unlines :: [String] -> String
- unwords :: [String] -> String
- type ShowS = String -> String
- class Show a where
- shows :: Show a => a -> ShowS
- showChar :: Char -> ShowS
- showString :: String -> ShowS
- showParen :: Bool -> ShowS -> ShowS
- type ReadS a = String -> [(a, String)]
- class Read a where
- reads :: Read a => ReadS a
- readParen :: Bool -> ReadS a -> ReadS a
- read :: Read a => String -> a
- lex :: ReadS String
- data IO a
- putChar :: Char -> IO ()
- putStr :: String -> IO ()
- putStrLn :: String -> IO ()
- print :: Show a => a -> IO ()
- getChar :: IO Char
- getLine :: IO String
- getContents :: IO String
- interact :: (String -> String) -> IO ()
- readFile :: FilePath -> IO String
- writeFile :: FilePath -> String -> IO ()
- appendFile :: FilePath -> String -> IO ()
- readIO :: Read a => String -> IO a
- readLn :: Read a => IO a
- (->>) :: a -> (a -> b) -> b
- data SomeException
- class (Typeable e, Show e) => Exception e where
- toException :: e -> SomeException
- fromException :: SomeException -> Maybe e
- data IOException
- ioError :: IOError -> IO a
- userError :: String -> IOError
- throw :: Exception e => e -> a
- throwIO :: Exception e => e -> IO a
- throwTo :: Exception e => ThreadId -> e -> IO ()
- catch :: Exception e => IO a -> (e -> IO a) -> IO a
- catches :: IO a -> [Handler a] -> IO a
- data Handler a where
- catchJust :: Exception e => (e -> Maybe b) -> IO a -> (b -> IO a) -> IO a
- handle :: Exception e => (e -> IO a) -> IO a -> IO a
- handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
- try :: Exception e => IO a -> IO (Either e a)
- tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
- evaluate :: a -> IO a
- mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
- mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
- mask_ :: IO a -> IO a
- uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
- uninterruptibleMask_ :: IO a -> IO a
- getMaskingState :: IO MaskingState
- allowInterrupt :: IO ()
- assert :: Bool -> a -> a
- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
- bracket_ :: IO a -> IO b -> IO c -> IO c
- bracketOnError :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
- finally :: IO a -> IO b -> IO a
- onException :: IO a -> IO b -> IO a
- class Typeable a => Data a where
- gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> a -> c a
- gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a
- toConstr :: a -> Constr
- dataTypeOf :: a -> DataType
- dataCast1 :: Typeable1 t => (forall d. Data d => c (t d)) -> Maybe (c a)
- dataCast2 :: Typeable2 t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a)
- gmapT :: (forall b. Data b => b -> b) -> a -> a
- gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
- gmapQr :: (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
- gmapQ :: (forall d. Data d => d -> u) -> a -> [u]
- gmapQi :: Int -> (forall d. Data d => d -> u) -> a -> u
- gmapM :: Monad m => (forall d. Data d => d -> m d) -> a -> m a
- gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a
- gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a
- class Typeable a where
- exhaustively :: Eq a => (a -> a) -> a -> a
- exhaustivelyM :: (Eq a, Monad m) => (a -> m a) -> a -> m a
- exhaustivelyBy :: (a -> a -> Bool) -> (a -> a) -> a -> a
- exhaustivelyByM :: Monad m => (a -> a -> Bool) -> (a -> m a) -> a -> m a
- uniqSort :: Ord a => [a] -> [a]
- aggregate :: Ord a => [a] -> [[a]]
- aggregateBy :: (a -> a -> Ordering) -> [a] -> [[a]]
- aggregateAL :: Ord a => [(a, b)] -> [(a, [b])]
- tr :: Eq a => a -> a -> [a] -> [a]
- segment2 :: Int -> [[a]] -> [[a]]
- segment3 :: Int -> [[[a]]] -> [[a]]
- count2 :: [[a]] -> Int
- count3 :: [[[a]]] -> Int
- count4 :: [[[[a]]]] -> Int
Documentation
data Bool
data Maybe a
The Maybe
type encapsulates an optional value. A value of type
either contains a value of type Maybe
aa
(represented as
),
or it is empty (represented as Just
aNothing
). Using Maybe
is a good way to
deal with errors or exceptional cases without resorting to drastic
measures such as error
.
The Maybe
type is also a monad. It is a simple kind of error
monad, where all errors are represented by Nothing
. A richer
error monad can be built using the Either
type.
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 |
listToMaybe :: [a] -> Maybe a
The listToMaybe
function returns Nothing
on an empty list
or
where Just
aa
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
.
data Either a b
The Either
type represents values with two possibilities: a value of
type
is either Either
a b
or Left
a
.
Right
b
The Either
type is sometimes used to represent a value which is
either correct or an error; by convention, the Left
constructor is
used to hold an error value and the Right
constructor is used to
hold a correct value (mnemonic: "right" also means "correct").
partitionEithers :: [Either a b] -> ([a], [b])
uneither :: Either a a -> aSource
If an Either contains the same types in Left and Right, unify it by dropping the Either wrapper.
data Ordering
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
).
Selects control characters, which are the non-printing characters of the Latin-1 subset of Unicode.
Returns True
for any Unicode space character, and the control
characters \t
, \n
, \r
, \f
, \v
.
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.
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.
Selects printable Unicode characters (letters, numbers, marks, punctuation, symbols and spaces).
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'
.
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
.
Selects Unicode mark characters, e.g. accents and the like, which combine with preceding letters.
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.
Selects Unicode symbol characters, including mathematical and currency symbols.
isSeparator :: Char -> Bool
Selects Unicode space and separator characters.
Selects the first 128 characters of the Unicode character set, corresponding to the ASCII character set.
Selects the first 256 characters of the Unicode character set, corresponding to the ISO 8859-1 (Latin-1) character set.
isAsciiUpper :: Char -> Bool
isAsciiLower :: Char -> Bool
class IsString a where
Class for string-like datastructures; used by the overloaded string extension (-foverloaded-strings in GHC).
fromString :: String -> a
Convert a letter to the corresponding upper-case letter, if any. Any other character is returned unchanged.
Convert a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged.
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
class AtLeastPair a whereSource
AtLeastPair (a, b) | |
AtLeastPair (a, b, c) | |
AtLeastPair (a, b, c, d) | |
AtLeastPair (a, b, c, d, e) |
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
.
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) |
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.
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:
- The calls
andsucc
maxBound
should result in a runtime error.pred
minBound
-
fromEnum
andtoEnum
should give a runtime error if the result value is not representable in the result type. For example,
is an error.toEnum
7 ::Bool
-
enumFrom
andenumFromThen
should be defined with an implicit bound, thus:
enumFrom x = enumFromTo x maxBound enumFromThen x y = enumFromThenTo x y bound where bound | fromEnum y >= fromEnum x = maxBound | otherwise = minBound
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.
Convert from an Int
.
Convert to an Int
.
It is implementation-dependent what fromEnum
returns when
applied to a value that is too large to fit in an Int
.
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
.
data Int
data Integer
Arbitrary-precision integers.
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
data Int16
16-bit signed integer type
data Int32
32-bit signed integer type
data Int64
64-bit signed integer type
data Word8
8-bit unsigned integer type
data Word16
16-bit unsigned integer type
data Word32
32-bit unsigned integer type
data Word64
64-bit unsigned integer type
data Ratio a
Rational numbers, with numerator and denominator of some Integral
type.
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 (-)
(+) :: 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
toRational :: a -> Rational
the rational equivalent of its real argument with full precision
class (Real a, Enum a) => Integral a where
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)
divMod :: a -> a -> (a, a)
conversion to Integer
class Num a => Fractional a where
Fractional numbers, supporting real division.
Minimal complete definition: fromRational
and (recip
or (
)
/
)
(/) :: a -> a -> a
fractional division
recip :: a -> a
reciprocal fraction
fromRational :: Rational -> a
Conversion from a Rational
(that is
).
A floating literal stands for an application of Ratio
Integer
fromRational
to a value of type Rational
, so such literals have type
(
.
Fractional
a) => a
Fractional Double | |
Fractional Float | |
Integral a => Fractional (Ratio a) | |
RealFloat a => Fractional (Complex 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
class (Real a, Fractional a) => RealFrac a where
Extracting components of fractions.
Minimal complete definition: properFraction
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 asx
; and -
f
is a fraction with the same type and sign asx
, and with absolute value less than1
.
The default definitions of the ceiling
, floor
, truncate
and round
functions are in terms of properFraction
.
truncate :: Integral b => a -> b
returns the integer nearest truncate
xx
between zero and x
returns the nearest integer to round
xx
;
the even integer if x
is equidistant between two integers
ceiling :: Integral b => a -> b
returns the least integer not less than ceiling
xx
returns the greatest integer not greater than floor
xx
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
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
yields decodeFloat
x(m,n)
, then x
is equal in value to m*b^^n
, where b
is the floating-point radix, and furthermore, either m
and n
are both zero or else b^(d-1) <=
, where abs
m < b^dd
is
the value of
.
In particular, floatDigits
x
. If the type
contains a negative zero, also decodeFloat
0 = (0,0)
.
The result of decodeFloat
(-0.0) = (0,0)
is unspecified if either of
decodeFloat
x
or isNaN
x
is isInfinite
xTrue
.
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
is one of the two closest representable
floating-point numbers to encodeFloat
m nm*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
corresponds to the second component of decodeFloat
.
and for finite nonzero exponent
0 = 0x
,
.
If exponent
x = snd (decodeFloat
x) + floatDigits
xx
is a finite floating-point number, it is equal in value to
, where significand
x * b ^^ exponent
xb
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
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
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
,
computes the angle
(from the positive x-axis) of the vector from the origin to the
point atan2
y x(x,y)
.
returns a value in the range [atan2
y x-pi
,
pi
]. It follows the Common Lisp semantics for the origin when
signed zeroes are supported.
, with atan2
y 1y
in a type
that is RealFloat
, should return the same value as
.
A default definition of atan
yatan2
is provided, but implementors
can provide a more accurate implementation.
data Complex a
mkPolar :: RealFloat a => a -> a -> Complex a
Form a complex number from polar components of magnitude and phase.
gcd :: Integral a => a -> a -> a
is the non-negative factor of both gcd
x yx
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 44
.
= gcd
0 00
.
(That is, the common divisor that is "greatest" in the divisibility
preordering.)
Note: Since for signed fixed-width integer types,
,
the result may be negative if one of the arguments is abs
minBound
< 0
(and
necessarily is if the other is minBound
0
or
) for such types.
minBound
(^^) :: (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.
Functor [] | |
Functor IO | |
Functor Id | |
Functor ZipList | |
Functor Handler | |
Functor STM | |
Functor ReadPrec | |
Functor ReadP | |
Functor Maybe | |
Functor ((->) r) | |
Functor (Either a) | |
Functor ((,) a) | |
Functor (StateL s) | |
Functor (StateR s) | |
Functor (Const m) | |
Monad m => Functor (WrappedMonad m) | |
Arrow a => Functor (ArrowMonad a) | |
Arrow a => Functor (WrappedArrow a b) |
const :: a -> b -> a
Constant function.
flip :: (a -> b -> c) -> b -> a -> c
takes its (first) two arguments in the reverse order of flip
ff
.
($) :: (a -> b) -> a -> b
Application operator. This operator is redundant, since ordinary
application (f x)
means the same as (f
. However, $
x)$
has
low, right-associative binding precedence, so it sometimes allows
parentheses to be omitted; for example:
f $ g $ h x = f (g (h x))
It is also useful in higher-order situations, such as
,
or map
($
0) xs
.
zipWith
($
) fs xs
fix :: (a -> a) -> a
is the least fixed point of the function fix
ff
,
i.e. the least defined x
such that f x = x
.
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
asTypeOf :: a -> a -> a
undefined :: a
seq :: a -> b -> b
Evaluates its first argument to head normal form, and then returns its second argument as the result.
class Functor f => Applicative f where
A functor with application, providing operations to
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
and
pure
= return
(
(which implies that <*>
) = ap
pure
and <*>
satisfy the
applicative functor laws).
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.
Applicative [] | |
Applicative IO | |
Applicative Id | |
Applicative ZipList | |
Applicative STM | |
Applicative ReadPrec | |
Applicative ReadP | |
Applicative Maybe | |
Applicative ((->) a) | |
Applicative (Either e) | |
Monoid a => Applicative ((,) a) | |
Applicative (StateL s) | |
Applicative (StateR s) | |
Monoid m => Applicative (Const m) | |
Monad m => Applicative (WrappedMonad m) | |
Applicative (ST s) | |
Arrow a => Applicative (ArrowMonad a) | |
Applicative (ST s) | |
Arrow a => Applicative (WrappedArrow a b) |
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.
(>>=) :: 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 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) -> (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
>=>
)
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.
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)
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
.
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.
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.
replicateM :: Monad m => Int -> m a -> m [a]
performs the action replicateM
n actn
times,
gathering the results.
replicateM_ :: Monad m => Int -> m a -> m ()
Like replicateM
, but discards the result.
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.
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
).
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 newtype
s and make those instances
of Monoid
, e.g. Sum
and Product
.
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.
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 |
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) |
newtype Endo a
The monoid of endomorphisms under composition.
newtype All
Boolean monoid under conjunction.
newtype Any
Boolean monoid under disjunction.
newtype Sum a
Monoid under addition.
newtype First a
Maybe monoid returning the leftmost non-Nothing value.
newtype Last a
Maybe monoid returning the rightmost non-Nothing value.
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:
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.
Alternative [] | |
Alternative STM | |
Alternative ReadPrec | |
Alternative ReadP | |
Alternative Maybe | |
MonadPlus m => Alternative (WrappedMonad m) | |
ArrowPlus a => Alternative (ArrowMonad a) | |
(ArrowZero a, ArrowPlus a) => Alternative (WrappedArrow a b) |
newtype WrappedMonad m a
WrapMonad | |
|
Monad m => Functor (WrappedMonad m) | |
Monad m => Applicative (WrappedMonad m) | |
MonadPlus m => Alternative (WrappedMonad m) |
newtype WrappedArrow a b c
WrapArrow | |
|
Arrow a => Functor (WrappedArrow a b) | |
Arrow a => Applicative (WrappedArrow a b) | |
(ArrowZero a, ArrowPlus a) => Alternative (WrappedArrow a b) |
newtype ZipList a
Lists, but with an Applicative
functor based on zipping, so that
f<$>
ZipList
xs1<*>
...<*>
ZipList
xsn =ZipList
(zipWithn f xs1 ... xsn)
ZipList | |
|
(<**>) :: 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
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
arr
id =id
arr
(f >>> g) =arr
f >>>arr
gfirst
(arr
f) =arr
(first
f)first
(f >>> g) =first
f >>>first
gfirst
f >>>arr
fst
=arr
fst
>>> ffirst
f >>>arr
(id
*** g) =arr
(id
*** g) >>>first
ffirst
(first
f) >>>arr
assoc
=arr
assoc
>>>first
f
where
assoc ((a,b),c) = (a,(b,c))
The other combinators have sensible default definitions, which may be overridden for efficiency.
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.
newtype Kleisli m a b
Kleisli arrows of a monad.
Kleisli | |
|
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 |
Monad m => Category (Kleisli m) |
(<<^) :: 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 => 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
left
(arr
f) =arr
(left
f)left
(f >>> g) =left
f >>>left
gf >>>
arr
Left
=arr
Left
>>>left
fleft
f >>>arr
(id
+++ g) =arr
(id
+++ g) >>>left
fleft
(left
f) >>>arr
assocsum
=arr
assocsum
>>>left
f
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.
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.
ArrowChoice (->) | |
Monad m => ArrowChoice (Kleisli m) |
class Arrow a => ArrowApply a where
Some arrows allow application of arrow inputs to other inputs. Instances should satisfy the following laws:
first
(arr
(\x ->arr
(\y -> (x,y)))) >>>app
=id
first
(arr
(g >>>)) >>>app
=second
g >>>app
first
(arr
(>>> h)) >>>app
=app
>>> h
Such arrows are equivalent to monads (see ArrowMonad
).
app :: a (a b c, b) c
ArrowApply (->) | |
Monad m => ArrowApply (Kleisli m) |
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.
ArrowMonad (a () b) |
ArrowApply a => Monad (ArrowMonad a) | |
Arrow a => Functor (ArrowMonad a) | |
(ArrowApply a, ArrowPlus a) => MonadPlus (ArrowMonad a) | |
Arrow a => Applicative (ArrowMonad a) | |
ArrowPlus a => Alternative (ArrowMonad a) |
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)
loop :: a (b, d) (c, d) -> a b c
(++) :: [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.
List index (subscript) operator, starting from 0.
It is an instance of the more general genericIndex
,
which takes an index of any integral type.
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.
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:
- In the
Functor
instance,fmap
should be equivalent to traversal with the identity applicative functor (fmapDefault
). - In the
Foldable
instance,foldMap
should be equivalent to traversal with a constant applicative functor (foldMapDefault
).
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.
Traversable [] | |
Traversable Maybe | |
Ix i => Traversable (Array i) |
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
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
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
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
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 ()
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
.
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.
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.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
Map a function over all the elements of a container and concatenate the resulting lists.
scanl :: (a -> b -> a) -> a -> [b] -> [a]
scanl1 :: (a -> a -> a) -> [a] -> [a]
scanr :: (a -> b -> b) -> b -> [a] -> [b]
scanr1 :: (a -> a -> a) -> [a] -> [a]
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), ...]
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
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
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 (
when take
n xs, drop
n xs)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] == []
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])
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],[])
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 (
.
It inserts the list concat
(intersperse
xs xss))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)
mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
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
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]]
tails :: [a] -> [[a]]
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.
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)
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.
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)]
zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]
zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]
zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]
zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]
zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]
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])
unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])
unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])
unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])
unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])
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.
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.
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.
intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
The intersectBy
function is the non-overloaded version of intersect
.
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
breaks a string up into a list of strings at newline
characters. The resulting strings do not contain newlines.
words
breaks a string up into a list of words, which were delimited
by white space.
class Show a where
Conversion of values to readable String
s.
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 thand
(associativity is ignored). Thus, ifd
is0
then the result is never surrounded in parentheses; ifd
is11
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,
-
produces the stringshow
(Leaf 1 :^: Leaf 2 :^: Leaf 3)"Leaf 1 :^: (Leaf 2 :^: Leaf 3)"
.
:: Int | the operator precedence of the enclosing
context (a number from |
-> a | the value to be converted to a |
-> ShowS |
Convert a value to a readable String
.
showsPrec
should satisfy the law
showsPrec d x r ++ s == showsPrec d x (r ++ s)
Derived instances of Read
and Show
satisfy the following:
That is, readsPrec
parses the string produced by
showsPrec
, and delivers the value that showsPrec
started with.
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.
class Read a where
Parsing of String
s, 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
:: Int | the operator precedence of the enclosing
context (a number from |
-> 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.
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) |
The read
function reads input from a string, which must be
completely consumed by the input process.
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
.) If there is no legal lexeme at the
beginning of the input string, lex
"" = [("","")]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
is a computation which, when performed,
does some I/O before returning a value of type IO
aa
.
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.
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]])
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]])
(->>) :: 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 MismatchedParenthesescatch
e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatch
e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatch
e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatch
e -> putStrLn ("Caught " ++ show (e :: IOException)) *** Exception: MismatchedParentheses
toException :: e -> SomeException
fromException :: SomeException -> Maybe e
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.
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
.
:: 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)]
:: 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)) $ ...
try :: Exception e => IO a -> IO (Either e a)
Similar to catch
, but returns an Either
result which is
(
if no exception of type Right
a)e
was raised, or (
if an exception of type Left
ex)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).
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
.
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.
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.
:: 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.
:: 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.
:: 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 gmapQ
x 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.
:: (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 |
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
, which is
suitable for abstract datatypes with no substructures.
const
id
gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c a
Unfolding constructor applications
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
, which is appropriate
for non-unary type constructors.
const
Nothing
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
, which is appropriate
for non-binary type constructors.
const
Nothing
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
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) |
class Typeable a where
The class Typeable
allows a concrete representation of a type to
be calculated.
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.
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.