HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

  • Packagerio-0.1.22.0
  • Exports295
  • LanguageHaskell2010
  • LicenceMIT
  • SourceClasses.hs

Bool

5 declarations

Re-exported from Data.Bool:

value(||) :: Bool -> Bool -> Bool
#

Boolean "or", lazy in the second argument

value(&&) :: Bool -> Bool -> Bool
#

Boolean "and", lazy in the second argument

valueotherwise :: Bool
#

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

 f x | x < 0     = ...
     | otherwise = ...
valuebool :: a -> a -> Bool -> a
#

Case analysis for the Bool type. bool f t p evaluates to f when p is False, and evaluates to t when p is True.

This is equivalent to if p then t else f; that is, one can think of it as an if-then-else construct with its arguments reordered.

Examples

Basic usage:

Example2 expressions
bool "foo" "bar" True"bar"bool "foo" "bar" False"foo"

Confirm that bool f t p and if p then t else f are equivalent:

Example4 expressions
let p = True; f = "bar"; t = "foo"bool f t p == if p then t else fTruelet p = Falsebool f t p == if p then t else fTrue

Maybe

13 declarations

Re-exported from Data.Maybe:

valuemaybe :: b -> (a -> b) -> Maybe a -> b
#

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

Examples

Basic usage:

Example1 expression
maybe False odd (Just 3)True
Example1 expression
maybe False odd NothingFalse

Read an integer from a string using readMaybe. If we succeed, return twice the integer; that is, apply (*2) to it. If instead we fail to parse an integer, return 0 by default:

Example3 expressions
import GHC.Internal.Text.Read ( readMaybe )maybe 0 (*2) (readMaybe "5")10maybe 0 (*2) (readMaybe "")0

Apply show to a Maybe Int. If we have Just n, we want to show the underlying Int n. But if we have Nothing, we return the empty string instead of (for example) "Nothing":

Example2 expressions
maybe "" show (Just 5)"5"maybe "" show Nothing""
valuefromMaybe :: a -> Maybe a -> a
#

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

Examples

Basic usage:

Example1 expression
fromMaybe "" (Just "Hello, World!")"Hello, World!"
Example1 expression
fromMaybe "" Nothing""

Read an integer from a string using readMaybe. If we fail to parse an integer, we want to return 0 by default:

Example3 expressions
import GHC.Internal.Text.Read ( readMaybe )fromMaybe 0 (readMaybe "5")5fromMaybe 0 (readMaybe "")0
valueisJust :: Maybe a -> Bool
#

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

Examples

Basic usage:

Example1 expression
isJust (Just 3)True
Example1 expression
isJust (Just ())True
Example1 expression
isJust NothingFalse

Only the outer constructor is taken into consideration:

Example1 expression
isJust (Just Nothing)True
valueisNothing :: Maybe a -> Bool
#

The isNothing function returns True iff its argument is Nothing.

Examples

Basic usage:

Example1 expression
isNothing (Just 3)False
Example1 expression
isNothing (Just ())False
Example1 expression
isNothing NothingTrue

Only the outer constructor is taken into consideration:

Example1 expression
isNothing (Just Nothing)False
valuelistToMaybe :: [a] -> Maybe a
#

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

Examples

Basic usage:

Example1 expression
listToMaybe []Nothing
Example1 expression
listToMaybe [9]Just 9
Example1 expression
listToMaybe [1,2,3]Just 1

Composing maybeToList with listToMaybe should be the identity on singleton/empty lists:

Example2 expressions
maybeToList $ listToMaybe [5][5]maybeToList $ listToMaybe [][]

But not on lists with more than one element:

Example1 expression
maybeToList $ listToMaybe [1,2,3][1]
valuemaybeToList :: Maybe a -> [a]
#

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

Examples

Basic usage:

Example1 expression
maybeToList (Just 7)[7]
Example1 expression
maybeToList Nothing[]

One can use maybeToList to avoid pattern matching when combined with a function that (safely) works on lists:

Example3 expressions
import GHC.Internal.Text.Read ( readMaybe )sum $ maybeToList (readMaybe "3")3sum $ maybeToList (readMaybe "")0
valuecatMaybes :: [Maybe a] -> [a]
#

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

Examples

Basic usage:

Example1 expression
catMaybes [Just 1, Nothing, Just 3][1,3]

When constructing a list of Maybe values, catMaybes can be used to return all of the "success" results (if the list is the result of a map, then mapMaybe would be more appropriate):

Example3 expressions
import GHC.Internal.Text.Read ( readMaybe )[readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ][Just 1,Nothing,Just 3]catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ][1,3]
valuemapMaybe :: (a -> Maybe b) -> [a] -> [b]
#

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

Examples

Using mapMaybe f x is a shortcut for catMaybes $ map f x in most cases:

Example4 expressions
import GHC.Internal.Text.Read ( readMaybe )let readMaybeInt = readMaybe :: String -> Maybe IntmapMaybe readMaybeInt ["1", "Foo", "3"][1,3]catMaybes $ map readMaybeInt ["1", "Foo", "3"][1,3]

If we map the Just constructor, the entire list should be returned:

Example1 expression
mapMaybe Just [1,2,3][1,2,3]

Either

9 declarations

Re-exported from Data.Either:

valueeither :: (a -> c) -> (b -> c) -> Either a b -> c
#

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

Examples

We create two values of type Either String Int, one using the Left constructor and another using the Right constructor. Then we apply "either" the length function (if we have a String) or the "times-two" function (if we have an Int):

Example4 expressions
let s = Left "foo" :: Either String Intlet n = Right 3 :: Either String Inteither length (*2) s3either length (*2) n6
valuefromLeft :: a -> Either a b -> a
#

Return the contents of a Left-value or a default value otherwise.

Examples

Basic usage:

Example2 expressions
fromLeft 1 (Left 3)3fromLeft 1 (Right "foo")1
valuefromRight :: b -> Either a b -> b
#

Return the contents of a Right-value or a default value otherwise.

Examples

Basic usage:

Example2 expressions
fromRight 1 (Right 3)3fromRight 1 (Left "foo")1
valueisLeft :: Either a b -> Bool
#

Return True if the given value is a Left-value, False otherwise.

Examples

Basic usage:

Example2 expressions
isLeft (Left "foo")TrueisLeft (Right 3)False

Assuming a Left value signifies some sort of error, we can use isLeft to write a very simple error-reporting function that does absolutely nothing in the case of success, and outputs "ERROR" if any error occurred.

This example shows how isLeft might be used to avoid pattern matching when one does not care about the value contained in the constructor:

Example4 expressions
import Control.Monad ( when )let report e = when (isLeft e) $ putStrLn "ERROR"report (Right 1)report (Left "parse error")ERROR
valueisRight :: Either a b -> Bool
#

Return True if the given value is a Right-value, False otherwise.

Examples

Basic usage:

Example2 expressions
isRight (Left "foo")FalseisRight (Right 3)True

Assuming a Left value signifies some sort of error, we can use isRight to write a very simple reporting function that only outputs "SUCCESS" when a computation has succeeded.

This example shows how isRight might be used to avoid pattern matching when one does not care about the value contained in the constructor:

Example4 expressions
import Control.Monad ( when )let report e = when (isRight e) $ putStrLn "SUCCESS"report (Left "parse error")report (Right 1)SUCCESS
valuelefts :: [Either a b] -> [a]
#

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

Examples

Basic usage:

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]lefts list["foo","bar","baz"]
valuepartitionEithers :: [Either a b] -> ([a], [b])
#

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

Examples

Basic usage:

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]partitionEithers list(["foo","bar","baz"],[3,7])

The pair returned by partitionEithers x should be the same pair as (lefts x, rights x):

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]partitionEithers list == (lefts list, rights list)True
valuerights :: [Either a b] -> [b]
#

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

Examples

Basic usage:

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]rights list[3,7]

Tuples

4 declarations

Re-exported from Data.Tuple:

valuefst :: (a, b) -> a
#

Extract the first component of a pair.

valuesnd :: (a, b) -> b
#

Extract the second component of a pair.

valuecurry :: ((a, b) -> c) -> a -> b -> c
#

Convert an uncurried function to a curried function.

Examples
Example1 expression
curry fst 1 21
valueuncurry :: (a -> b -> c) -> (a, b) -> c
#

uncurry converts a curried function to a function on pairs.

Examples
Example1 expression
uncurry (+) (1,2)3
Example1 expression
uncurry ($) (show, 1)"1"
Example1 expression
map (uncurry max) [(1,2), (3,4), (6,8)][2,4,8]

Eq

2 declarations

Re-exported from Data.Eq:

Ord

9 declarations

Re-exported from Data.Ord:

method(<) :: a -> a -> Bool
#
method(>) :: a -> a -> Bool
#
methodmax :: a -> a -> a
#
methodmin :: a -> a -> a
#
valuecomparing :: Ord a => (b -> a) -> b -> b -> Ordering
#
comparing p x y = compare (p x) (p y)

Useful combinator for use in conjunction with the xxxBy family of functions from Data.List, for example:

  ... sortBy (comparing fst) ...
newtypenewtype Down a
#

The Down type allows you to reverse sort order conveniently. A value of type Down a contains a value of type a (represented as Down a).

If a has an Ord instance associated with it then comparing two values thus wrapped will give you the opposite of their normal sort order. This is particularly useful when sorting in generalised list comprehensions, as in: then sortWith by Down x.

Example1 expression
compare True FalseGT
Example1 expression
compare (Down True) (Down False)LT

If a has a Bounded instance then the wrapped instance also respects the reversed ordering by exchanging the values of minBound and maxBound.

Example1 expression
minBound :: Int-9223372036854775808
Example1 expression
minBound :: Down IntDown 9223372036854775807

All other instances of Down a behave as they do for a.

Constructors

Instances43Monad, Functor, MonadFix, Applicative, Foldable, Traversable, …

Enum

1 declaration

Re-exported from Prelude:

methodfromEnum :: a -> Int
#

Convert to an Int. It is implementation-dependent what fromEnum returns when applied to a value that is too large to fit in an Int.

Bounded

2 declarations

Re-exported from Prelude:

Num

9 declarations

Re-exported from Prelude:

method(+) :: a -> a -> a
#
method(-) :: a -> a -> a
#
method(*) :: a -> a -> a
#
value(^) :: (Num a, Integral b) => a -> b -> a
#

raise a number to a non-negative integral power

methodnegate :: a -> a
#

Unary negation.

methodabs :: a -> a
#

Absolute value.

methodsignum :: 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).

valuesubtract :: Num a => a -> a -> a
#

the same as flip (-).

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

Real

1 declaration

Re-exported from Prelude:

methodtoRational :: a -> Rational
#

Rational equivalent of its real argument with full precision.

Integral

12 declarations

Re-exported from Prelude:

methodquot :: a -> a -> a
#

Integer division truncated toward zero.

WARNING: This function is partial (because it throws when 0 is passed as the divisor) for all the integer types in base.

methodrem :: a -> a -> a
#

Integer remainder, satisfying

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

WARNING: This function is partial (because it throws when 0 is passed as the divisor) for all the integer types in base.

methoddiv :: a -> a -> a
#

Integer division truncated toward negative infinity.

WARNING: This function is partial (because it throws when 0 is passed as the divisor) for all the integer types in base.

methodmod :: a -> a -> a
#

Integer modulus, satisfying

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

WARNING: This function is partial (because it throws when 0 is passed as the divisor) for all the integer types in base.

methodquotRem :: a -> a -> (a, a)
#

Simultaneous quot and rem.

WARNING: This function is partial (because it throws when 0 is passed as the divisor) for all the integer types in base.

methoddivMod :: a -> a -> (a, a)
#

simultaneous div and mod.

WARNING: This function is partial (because it throws when 0 is passed as the divisor) for all the integer types in base.

valuegcd :: Integral a => a -> a -> a
#

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

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

valuelcm :: Integral a => a -> a -> a
#

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

valuefromIntegral :: (Integral a, Num b) => a -> b
#

General coercion from Integral types.

WARNING: This function performs silent truncation if the result type is not at least as big as the argument's type.

Fractional

5 declarations

Re-exported from Prelude:

method(/) :: a -> a -> a
#

Fractional division.

methodrecip :: a -> a
#

Reciprocal fraction.

valuerealToFrac :: (Real a, Fractional b) => a -> b
#

General coercion to Fractional types.

WARNING: This function goes through the Rational type, which does not have values for NaN for example. This means it does not round-trip.

For Double it also behaves differently with or without -O0:

Prelude> realToFrac nan -- With -O0
-Infinity
Prelude> realToFrac nan
NaN

Floating

18 declarations

Re-exported from Prelude:

methodpi :: a
#
methodexp :: a -> a
#
methodlog :: a -> a
#
methodsqrt :: a -> a
#
method(**) :: a -> a -> a
#
methodsin :: a -> a
#
methodcos :: a -> a
#
methodtan :: a -> a
#
methodasin :: a -> a
#
methodacos :: a -> a
#
methodatan :: a -> a
#
methodsinh :: a -> a
#
methodcosh :: a -> a
#
methodtanh :: a -> a
#

RealFrac

5 declarations

Re-exported from Prelude:

methodproperFraction :: Integral b => a -> (b, a)
#

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

  • n is an integral number with the same sign as x; and

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

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

methodround :: Integral b => a -> b
#

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

methodfloor :: Integral b => a -> b
#

floor x returns the greatest integer not greater than x

RealFloat

14 declarations

Re-exported from Prelude:

methodfloatRadix :: a -> Integer
#

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

methodfloatRange :: a -> (Int, Int)
#

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

methoddecodeFloat :: a -> (Integer, Int)
#

The function decodeFloat applied to a real floating-point number returns the significand expressed as an Integer and an appropriately scaled exponent (an Int). If decodeFloat x yields (m,n), then x is equal in value to m*b^^n, where b is the floating-point radix, and furthermore, either m and n are both zero or else b^(d-1) <= abs m < b^d, where d is the value of floatDigits x. In particular, decodeFloat 0 = (0,0). If the type contains a negative zero, also decodeFloat (-0.0) = (0,0). The result of decodeFloat x is unspecified if either of isNaN x or isInfinite x is True.

methodencodeFloat :: Integer -> Int -> a
#

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

methodsignificand :: 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.

methodscaleFloat :: Int -> a -> a
#

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

methodisNaN :: a -> Bool
#

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

methodisInfinite :: a -> Bool
#

True if the argument is an IEEE infinity or negative infinity

methodisIEEE :: a -> Bool
#

True if the argument is an IEEE floating point number

methodatan2 :: a -> a -> a
#

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

Word

3 declarations

Re-exported from Data.Word:

Semigroup

2 declarations

Re-exported from Data.Semigroup:

method(<>) :: a -> a -> a
#

An associative operation.

Examples
Example1 expression
[1,2,3] <> [4,5,6][1,2,3,4,5,6]
Example1 expression
Just [1, 2, 3] <> Just [4, 5, 6]Just [1,2,3,4,5,6]
Example1 expression
putStr "Hello, " <> putStrLn "World!"Hello, World!

Monoid

3 declarations

Re-exported from Data.Monoid:

methodmempty :: a
#

Identity of mappend

Examples
Example1 expression
"Hello world" <> mempty"Hello world"
Example1 expression
mempty <> [1, 2, 3][1,2,3]
methodmappend :: a -> a -> a
#

An associative operation

NOTE: This method is redundant and has the default implementation mappend = (<>) since base-4.11.0.0. Should it be implemented manually, since mappend is a synonym for (<>), it is expected that the two functions are defined the same way. In a future GHC release mappend will be removed from Monoid.

methodmconcat :: [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.

Example1 expression
mconcat ["Hello", " ", "Haskell", "!"]"Hello Haskell!"

Functor

6 declarations

Re-exported from Data.Functor:

methodfmap :: (a -> b) -> f a -> f b
#

fmap is used to apply a function of type (a -> b) to a value of type f a, where f is a functor, to produce a value of type f b. Note that for any type constructor with more than one parameter (e.g., Either), only the last type parameter can be modified with fmap (e.g., b in `Either a b`).

Some type constructors with two parameters or more have a Data.Bifunctor instance that allows both the last and the penultimate parameters to be mapped over.

Examples

Convert from a Maybe Int to a Maybe String using show:

Example2 expressions
fmap show NothingNothingfmap show (Just 3)Just "3"

Convert from an Either Int Int to an Either Int String using show:

Example2 expressions
fmap show (Left 17)Left 17fmap show (Right 17)Right "17"

Double each element of a list:

Example1 expression
fmap (*2) [1,2,3][2,4,6]

Apply even to the second element of a pair:

Example1 expression
fmap even (2,2)(2,True)

It may seem surprising that the function is only applied to the last element of the tuple compared to the list example above which applies it to every element in the list. To understand, remember that tuples are type constructors with multiple type parameters: a tuple of 3 elements (a,b,c) can also be written (,,) a b c and its Functor instance is defined for Functor ((,,) a b) (i.e., only the third parameter is free to be mapped over with fmap).

It explains why fmap can be used with tuples containing values of different types as in the following example:

Example1 expression
fmap even ("hello", 1.0, 4)("hello",1.0,True)
value(<$>) :: Functor f => (a -> b) -> f a -> f b
#

An infix synonym for fmap.

The name of this operator is an allusion to $. Note the similarities between their types:

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

Whereas $ is function application, <$> is function application lifted over a Functor.

Examples

Convert from a Maybe Int to a Maybe String using show:

Example1 expression
show <$> NothingNothing
Example1 expression
show <$> Just 3Just "3"

Convert from an Either Int Int to an Either Int String using show:

Example1 expression
show <$> Left 17Left 17
Example1 expression
show <$> Right 17Right "17"

Double each element of a list:

Example1 expression
(*2) <$> [1,2,3][2,4,6]

Apply even to the second element of a pair:

Example1 expression
even <$> (2,2)(2,True)
method(<$) :: a -> f b -> f a
#

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

Examples

Perform a computation with Maybe and replace the result with a constant value if it is Just:

Example2 expressions
'a' <$ Just 2Just 'a''a' <$ NothingNothing
value($>) :: Functor f => f a -> b -> f b
#

Flipped version of <$.

Examples

Replace the contents of a Maybe Int with a constant String:

Example1 expression
Nothing $> "foo"Nothing
Example1 expression
Just 90210 $> "foo"Just "foo"

Replace the contents of an Either Int Int with a constant String, resulting in an Either Int String:

Example1 expression
Left 8675309 $> "foo"Left 8675309
Example1 expression
Right 8675309 $> "foo"Right "foo"

Replace each element of a list with a constant String:

Example1 expression
[1,2,3] $> "foo"["foo","foo","foo"]

Replace the second element of a pair with a constant String:

Example1 expression
(1,2) $> "foo"(1,"foo")
valuevoid :: Functor f => f a -> f ()
#

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

Examples

Replace the contents of a Maybe Int with unit:

Example1 expression
void NothingNothing
Example1 expression
void (Just 3)Just ()

Replace the contents of an Either Int Int with unit, resulting in an Either Int ():

Example1 expression
void (Left 8675309)Left 8675309
Example1 expression
void (Right 8675309)Right ()

Replace every element of a list with unit:

Example1 expression
void [1,2,3][(),(),()]

Replace the second element of a pair with unit:

Example1 expression
void (1,2)(1,())

Discard the result of an System.IO.IO action:

Example1 expression
mapM print [1,2]12[(),()]
Example1 expression
void $ mapM print [1,2]12
value(<&>) :: Functor f => f a -> (a -> b) -> f b
#

Flipped version of <$>.

(<&>) = flip fmap
Examples

Apply (+1) to a list, a Just and a Right:

Example1 expression
Just 2 <&> (+1)Just 3
Example1 expression
[1,2,3] <&> (+1)[2,3,4]
Example1 expression
Right 3 <&> (+1)Right 4

Applicative

15 declarations

Re-exported from Control.Applicative:

methodpure :: a -> f a
#

Lift a value into the Structure.

Examples
Example1 expression
pure 1 :: Maybe IntJust 1
Example1 expression
pure 'z' :: [Char]"z"
Example1 expression
pure (pure ":D") :: Maybe [String]Just [":D"]
method(<*>) :: f (a -> b) -> f a -> f b
#

Sequential application.

A few functors support an implementation of <*> that is more efficient than the default one.

Example

Used in combination with (Data.Functor.<$>), (<*>) can be used to build a record.

Example1 expression
data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
Example3 expressions
produceFoo :: Applicative f => f FooproduceBar :: Applicative f => f BarproduceBaz :: Applicative f => f Baz
Example2 expressions
mkState :: Applicative f => f MyStatemkState = MyState <$> produceFoo <*> produceBar <*> produceBaz
method(<*) :: f a -> f b -> f a
#

Sequence actions, discarding the value of the second argument.

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

Sequence actions, discarding the value of the first argument.

Examples

If used in conjunction with the Applicative instance for Maybe, you can chain Maybe computations, with a possible "early return" in case of Nothing.

Example1 expression
Just 2 *> Just 3Just 3
Example1 expression
Nothing *> Just 3Nothing

Of course a more interesting use case would be to have effectful computations instead of just returning pure values.

Example4 expressions
import Data.Charimport GHC.Internal.Text.ParserCombinators.ReadPlet p = string "my name is " *> munch1 isAlpha <* eofreadP_to_S p "my name is Simon"[("Simon","")]
valueliftA :: Applicative f => (a -> b) -> f a -> f b
#

Lift a function to actions. Equivalent to Functor's fmap but implemented using only Applicative's methods: liftA f a = pure f <*> a

As such this function may be used to implement a Functor instance from an Applicative one.

Examples

Using the Applicative instance for Lists:

Example1 expression
liftA (+1) [1, 2][2,3]

Or the Applicative instance for Maybe

Example1 expression
liftA (+1) (Just 3)Just 4
methodliftA2 :: (a -> b -> c) -> f a -> f b -> f c
#

Lift a binary function to actions.

Some functors support an implementation of liftA2 that is more efficient than the default one. In particular, if fmap is an expensive operation, it is likely better to use liftA2 than to fmap over the structure and then use <*>.

This became a typeclass method in 4.10.0.0. Prior to that, it was a function defined in terms of <*> and fmap.

Example
Example1 expression
liftA2 (,) (Just 3) (Just 5)Just (3,5)
Example1 expression
liftA2 (+) [1, 2, 3] [4, 5, 6][5,6,7,6,7,8,7,8,9]
valueliftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
#

Lift a ternary function to actions.

valueforever :: Applicative f => f a -> f b
#

Repeat an action indefinitely.

Examples

A common use of forever is to process input from network sockets, System.IO.Handles, and channels (e.g. Control.Concurrent.MVar.MVar and Chan).

For example, here is how we might implement an echo server, using forever both to listen for client connections on a network socket and to echo client input on client connection handles:

echoServer :: Socket -> IO ()
echoServer socket = forever $ do
  client <- accept socket
  forkFinally (echo client) (\_ -> hClose client)
  where
    echo :: Handle -> IO ()
    echo client = forever $
      hGetLine client >>= hPutStrLn client

Note that "forever" isn't necessarily non-terminating. If the action is in a MonadPlus and short-circuits after some number of iterations. then forever actually returns mzero, effectively short-circuiting its caller.

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

Map each element of a structure to an Applicative action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see traverse.

traverse_ is just like mapM_, but generalised to Applicative actions.

Examples

Basic usage:

Example1 expression
traverse_ print ["Hello", "world", "!"]"Hello""world""!"
valuesequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()
#

Evaluate each action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results see sequenceA.

sequenceA_ is just like sequence_, but generalised to Applicative actions.

Examples

Basic usage:

Example1 expression
sequenceA_ [print "Hello", print "world", print "!"]"Hello""world""!"
valuefilterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
#

This generalizes the list-based filter function.

runIdentity (filterM (Identity . p) xs) == filter p xs
Examples
Example1 expression
filterM (\x -> do      putStrLn ("Keep: " ++ show x ++ "?")      answer <- getLine      pure (answer == "y"))    [1, 2, 3]Keep: 1?yKeep: 2?nKeep: 3?y[1,3]
Example1 expression
filterM (\x -> do      putStr (show x)      x' <- readLn      pure (x == x'))    [1, 2, 3]122233[2,3]

Monad

18 declarations

Re-exported from Control.Monad:

methodreturn :: a -> m a
#

Inject a value into the monadic type. This function should not be different from its default implementation as pure. The justification for the existence of this function is merely historic.

valuejoin :: 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.

'join bss' can be understood as the do expression

do bs <- bss
   bs
Examples
Example1 expression
join [[1, 2, 3], [4, 5, 6], [7, 8, 9]][1,2,3,4,5,6,7,8,9]
Example1 expression
join (Just (Just 3))Just 3

A common use of join is to run an IO computation returned from an GHC.Conc.STM transaction, since GHC.Conc.STM transactions can't perform IO directly. Recall that

GHC.Internal.Conc.atomically :: STM a -> IO a

is used to run GHC.Conc.STM transactions atomically. So, by specializing the types of GHC.Internal.Conc.atomically and join to

GHC.Internal.Conc.atomically :: STM (IO b) -> IO (IO b)
join       :: IO (IO b)  -> IO b

we can compose them as

join . GHC.Internal.Conc.atomically :: STM (IO b) -> IO b

to run an GHC.Conc.STM transaction and the IO action it returns.

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

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

'as >>= bs' can be understood as the do expression

do a <- as
   bs a

An alternative name for this function is 'bind', but some people may refer to it as 'flatMap', which results from it being equivialent to

\x f -> join (fmap f x) :: Monad m => m a -> (a -> m b) -> m b

which can be seen as mapping a value with Monad m => m a -> m (m b) and then 'flattening' m (m b) to m b using join.

method(>>) :: 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.

'as >> bs' can be understood as the do expression

do as
   bs

or in terms of (>>=) as

as >>= const bs
value(=<<) :: Monad m => (a -> m b) -> m a -> m b
#

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

as >>= f == f =<< as
value(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
#

Left-to-right composition of Kleisli arrows.

'(bs >=> cs) a' can be understood as the do expression

do b <- bs a
   cs b

or in terms of (>>=) as

bs a >>= cs
value(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
#

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

Note how this operator resembles function composition (.):

(.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
value(<$!>) :: Monad m => (a -> b) -> m a -> m b
#

Strict version of Data.Functor.<$>.

valueliftM :: Monad m => (a1 -> r) -> m a1 -> m r
#

Promote a function to a monad. This is equivalent to fmap but specialised to Monads.

valueliftM2 :: 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.

Examples
Example1 expression
liftM2 (+) [0,1] [0,2][0,2,1,3]
Example1 expression
liftM2 (+) (Just 1) NothingNothing
Example1 expression
liftM2 (+) (+ 3) (* 2) 518
valuewhenM :: Monad m => m Bool -> m () -> m ()
#

Run the second value if the first value returns True

valuemapM_ :: (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. For a version that doesn't ignore the results see Data.Traversable.mapM.

mapM_ is just like traverse_, but specialised to monadic actions.

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

forM_ is mapM_ with its arguments flipped. For a version that doesn't ignore the results see Data.Traversable.forM.

forM_ is just like for_, but specialised to monadic actions.

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

Evaluate each monadic action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results see Data.Traversable.sequence.

sequence_ is just like sequenceA_, but specialised to monadic actions.

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

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.

Note: foldM is the same as foldlM

Foldable

18 declarations

Re-exported from Data.Foldable:

methodfoldr :: (a -> b -> b) -> b -> t a -> b
#

Right-associative fold of a structure, lazy in the accumulator.

In the case of lists, foldr, when applied to a binary operator, a starting value (typically the right-identity of the operator), and a list, reduces the list using the binary operator, from right to left:

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

Note that since the head of the resulting expression is produced by an application of the operator to the first element of the list, given an operator lazy in its right argument, foldr can produce a terminating expression from an unbounded list.

For a general Foldable structure this should be semantically identical to,

foldr f z = foldr f z . toList
Examples

Basic usage:

Example1 expression
foldr (||) False [False, True, False]True
Example1 expression
foldr (||) False []False
Example1 expression
foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']"foodcba"
Infinite structures

⚠️ Applying foldr to infinite structures usually doesn't terminate.

It may still terminate under one of the following conditions:

  • the folding function is short-circuiting

  • the folding function is lazy on its second argument

Short-circuiting

(||) short-circuits on True values, so the following terminates because there is a True value finitely far from the left side:

Example1 expression
foldr (||) False (True : repeat False)True

But the following doesn't terminate:

Example1 expression
foldr (||) False (repeat False ++ [True])* Hangs forever *
Laziness in the second argument

Applying foldr to infinite structures terminates when the operator is lazy in its second argument (the initial accumulator is never used in this case, and so could be left undefined, but [] is more clear):

Example1 expression
take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
methodfoldl' :: (b -> a -> b) -> b -> t a -> b
#

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

This ensures that each step of the fold is forced to Weak Head Normal Form before being applied, avoiding the collection of thunks that would otherwise occur. This is often what you want to strictly reduce a finite structure to a single strict result (e.g. sum).

For a general Foldable structure this should be semantically identical to,

foldl' f z = foldl' f z . toList
methodfold :: Monoid m => t m -> m
#

Given a structure with elements whose type is a Monoid, combine them via the monoid's (<>) operator. This fold is right-associative and lazy in the accumulator. When you need a strict left-associative fold, use foldMap' instead, with id as the map.

Examples

Basic usage:

Example1 expression
fold [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
Example1 expression
fold $ Node (Leaf (Sum 1)) (Sum 3) (Leaf (Sum 5))Sum {getSum = 9}

Folds of unbounded structures do not terminate when the monoid's (<>) operator is strict:

Example1 expression
fold (repeat Nothing)* Hangs forever *

Lazy corecursive folds of unbounded structures are fine:

Example2 expressions
take 12 $ fold $ map (\i -> [i..i+2]) [0..][0,1,2,1,2,3,2,3,4,3,4,5]sum $ take 4000000 $ fold $ map (\i -> [i..i+2]) [0..]2666668666666
methodfoldMap :: Monoid m => (a -> m) -> t a -> m
#

Map each element of the structure into a monoid, and combine the results with (<>). This fold is right-associative and lazy in the accumulator. For strict left-associative folds consider foldMap' instead.

Examples

Basic usage:

Example1 expression
foldMap Sum [1, 3, 5]Sum {getSum = 9}
Example1 expression
foldMap Product [1, 3, 5]Product {getProduct = 15}
Example1 expression
foldMap (replicate 3) [1, 2, 3][1,1,1,2,2,2,3,3,3]

When a Monoid's (<>) is lazy in its second argument, foldMap can return a result even from an unbounded structure. For example, lazy accumulation enables Data.ByteString.Builder to efficiently serialise large data structures and produce the output incrementally:

Example5 expressions
import qualified Data.ByteString.Lazy as Limport qualified Data.ByteString.Builder as Blet bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20let lbs = B.toLazyByteString $ foldMap bld [0..]L.take 64 lbs"0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24"
methodelem :: Eq a => a -> t a -> Bool
#

Does the element occur in the structure?

Note: elem is often used in infix form.

Examples

Basic usage:

Example1 expression
3 `elem` []False
Example1 expression
3 `elem` [1,2]False
Example1 expression
3 `elem` [1,2,3,4,5]True

For infinite structures, the default implementation of elem terminates if the sought-after value exists at a finite distance from the left side of the structure:

Example1 expression
3 `elem` [1..]True
Example1 expression
3 `elem` ([4..] ++ [3])* Hangs forever *
valuenotElem :: (Foldable t, Eq a) => a -> t a -> Bool
#

notElem is the negation of elem.

Examples

Basic usage:

Example1 expression
3 `notElem` []True
Example1 expression
3 `notElem` [1,2]True
Example1 expression
3 `notElem` [1,2,3,4,5]False

For infinite structures, notElem terminates if the value exists at a finite distance from the left side of the structure:

Example1 expression
3 `notElem` [1..]False
Example1 expression
3 `notElem` ([4..] ++ [3])* Hangs forever *
methodnull :: t a -> Bool
#

Test whether the structure is empty. The default implementation is Left-associative and lazy in both the initial element and the accumulator. Thus optimised for structures where the first element can be accessed in constant time. Structures where this is not the case should have a non-default implementation.

Examples

Basic usage:

Example1 expression
null []True
Example1 expression
null [1]False

null is expected to terminate even for infinite structures. The default implementation terminates provided the structure is bounded on the left (there is a leftmost element).

Example1 expression
null [1..]False
methodlength :: t a -> Int
#

Returns the size/length of a finite structure as an Int. The default implementation just counts elements starting with the leftmost. Instances for structures that can compute the element count faster than via element-by-element counting, should provide a specialised implementation.

Examples

Basic usage:

Example1 expression
length []0
Example2 expressions
length ['a', 'b', 'c']3length [1..]* Hangs forever *
methodsum :: Num a => t a -> a
#

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

Examples

Basic usage:

Example1 expression
sum []0
Example1 expression
sum [42]42
Example1 expression
sum [1..10]55
Example1 expression
sum [4.1, 2.0, 1.7]7.8
Example1 expression
sum [1..]* Hangs forever *
methodproduct :: Num a => t a -> a
#

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

Examples

Basic usage:

Example1 expression
product []1
Example1 expression
product [42]42
Example1 expression
product [1..10]3628800
Example1 expression
product [4.1, 2.0, 1.7]13.939999999999998
Example1 expression
product [1..]* Hangs forever *
valueall :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether all elements of the structure satisfy the predicate.

Examples

Basic usage:

Example1 expression
all (> 3) []True
Example1 expression
all (> 3) [1,2]False
Example1 expression
all (> 3) [1,2,3,4,5]False
Example1 expression
all (> 3) [1..]False
Example1 expression
all (> 3) [4..]* Hangs forever *
valueany :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether any element of the structure satisfies the predicate.

Examples

Basic usage:

Example1 expression
any (> 3) []False
Example1 expression
any (> 3) [1,2]False
Example1 expression
any (> 3) [1,2,3,4,5]True
Example1 expression
any (> 3) [1..]True
Example1 expression
any (> 3) [0, -1..]* Hangs forever *
valueand :: Foldable t => t Bool -> Bool
#

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

Examples

Basic usage:

Example1 expression
and []True
Example1 expression
and [True]True
Example1 expression
and [False]False
Example1 expression
and [True, True, False]False
Example1 expression
and (False : repeat True) -- Infinite list [False,True,True,True,...False
Example1 expression
and (repeat True)* Hangs forever *
valueor :: Foldable t => t Bool -> Bool
#

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

Examples

Basic usage:

Example1 expression
or []False
Example1 expression
or [True]True
Example1 expression
or [False]False
Example1 expression
or [True, True, False]True
Example1 expression
or (True : repeat False) -- Infinite list [True,False,False,False,...True
Example1 expression
or (repeat False)* Hangs forever *
methodtoList :: t a -> [a]
#

List of elements of a structure, from left to right. If the entire list is intended to be reduced via a fold, just fold the structure directly bypassing the list.

Examples

Basic usage:

Example1 expression
toList Nothing[]
Example1 expression
toList (Just 42)[42]
Example1 expression
toList (Left "foo")[]
Example1 expression
toList (Node (Leaf 5) 17 (Node Empty 12 (Leaf 8)))[5,17,12,8]

For lists, toList is the identity:

Example1 expression
toList [1, 2, 3][1,2,3]
valueconcat :: Foldable t => t [a] -> [a]
#

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

Examples

Basic usage:

Example1 expression
concat (Just [1, 2, 3])[1,2,3]
Example1 expression
concat (Left 42)[]
Example1 expression
concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
valueconcatMap :: Foldable t => (a -> [b]) -> t a -> [b]
#

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

Examples

Basic usage:

Example1 expression
concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
Example1 expression
concatMap (take 3) (Just [1..])[1,2,3]

Traversable

6 declarations

Re-exported from Data.Traversable:

methodtraverse :: 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. For a version that ignores the results see traverse_.

Examples

Basic usage:

In the first two examples we show each evaluated action mapping to the output structure.

Example1 expression
traverse Just [1,2,3,4]Just [1,2,3,4]
Example1 expression
traverse id [Right 1, Right 2, Right 3, Right 4]Right [1,2,3,4]

In the next examples, we show that Nothing and Left values short circuit the created structure.

Example1 expression
traverse (const Nothing) [1,2,3,4]Nothing
Example1 expression
traverse (\x -> if odd x then Just x else Nothing)  [1,2,3,4]Nothing
Example1 expression
traverse id [Right 1, Right 2, Right 3, Right 4, Left 0]Left 0
methodsequenceA :: Applicative f => t (f a) -> f (t a)
#

Evaluate each action in the structure from left to right, and collect the results. For a version that ignores the results see sequenceA_.

Examples

Basic usage:

For the first two examples we show sequenceA fully evaluating a a structure and collecting the results.

Example1 expression
sequenceA [Just 1, Just 2, Just 3]Just [1,2,3]
Example1 expression
sequenceA [Right 1, Right 2, Right 3]Right [1,2,3]

The next two example show Nothing and Just will short circuit the resulting structure if present in the input. For more context, check the Traversable instances for Either and Maybe.

Example1 expression
sequenceA [Just 1, Just 2, Just 3, Nothing]Nothing
Example1 expression
sequenceA [Right 1, Right 2, Right 3, Left 4]Left 4
methodmapM :: Monad m => (a -> m b) -> t a -> m (t b)
#

Map each element of a structure to a monadic action, evaluate these actions from left to right, and collect the results. For a version that ignores the results see Data.Foldable.mapM_.

Examples

mapM is literally a traverse with a type signature restricted to Monad. Its implementation may be more efficient due to additional power of Monad.

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

forM is mapM with its arguments flipped. For a version that ignores the results see Data.Foldable.forM_.

methodsequence :: Monad m => t (m a) -> m (t a)
#

Evaluate each monadic action in the structure from left to right, and collect the results. For a version that ignores the results see Data.Foldable.sequence_.

Examples

Basic usage:

The first two examples are instances where the input and and output of sequence are isomorphic.

Example1 expression
sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
Example1 expression
sequence $ [Right 1,Right 2,Right 3,Right 4]Right [1,2,3,4]

The following examples demonstrate short circuit behavior for sequence.

Example1 expression
sequence $ Left [1,2,3,4]Left [1,2,3,4]
Example1 expression
sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]Left 0

Alternative

8 declarations

Re-exported from Control.Applicative:

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

An associative binary operation

methodsome :: f a -> f [a]
#

One or more.

Examples
Example1 expression
some (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
some Nothingnothing
Example1 expression
take 5 <$> some (Just 1)* hangs forever *

Note that this function can be used with Parsers based on Applicatives. In that case some parser will attempt to parse parser one or more times until it fails.

methodmany :: f a -> f [a]
#

Zero or more.

Examples
Example1 expression
many (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
many NothingJust []
Example1 expression
take 5 <$> many (Just 1)* hangs forever *

Note that this function can be used with Parsers based on Applicatives. In that case many parser will attempt to parse parser zero or more times until it fails.

valueoptional :: Alternative f => f a -> f (Maybe a)
#

One or none.

It is useful for modelling any computation that is allowed to fail.

Examples

Using the Alternative instance of Control.Monad.Except, the following functions:

Example1 expression
import Control.Monad.Except
Example2 expressions
canFail = throwError "it failed" :: Except String Intfinal = return 42                :: Except String Int

Can be combined by allowing the first function to fail:

Example1 expression
runExcept $ canFail *> finalLeft "it failed"
Example1 expression
runExcept $ optional canFail *> finalRight 42
valueasum :: (Foldable t, Alternative f) => t (f a) -> f a
#

The sum of a collection of actions using (<|>), generalizing concat.

asum is just like msum, but generalised to Alternative.

Examples

Basic usage:

Example1 expression
asum [Just "Hello", Nothing, Just "World"]Just "Hello"
valueguard :: Alternative f => Bool -> f ()
#

Conditional failure of Alternative computations. Defined by

guard True  = pure ()
guard False = empty
Examples

Common uses of guard include conditionally signalling an error in an error monad and conditionally rejecting the current choice in an Alternative-based parser.

As an example of signalling an error in the error monad Maybe, consider a safe division function safeDiv x y that returns Nothing when the denominator y is zero and Just (x `div` y) otherwise. For example:

Example1 expression
safeDiv 4 0Nothing
Example1 expression
safeDiv 4 2Just 2

A definition of safeDiv using guards, but not guard:

safeDiv :: Int -> Int -> Maybe Int
safeDiv x y | y /= 0    = Just (x `div` y)
            | otherwise = Nothing

A definition of safeDiv using guard and Monad do-notation:

safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
  guard (y /= 0)
  return (x `div` y)
valuewhen :: Applicative f => Bool -> f () -> f ()
#

Conditional execution of Applicative expressions. For example,

Examples
when debug (putStrLn "Debugging")

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

Example1 expression
putStr "pi:" >> when False (print 3.14159)pi:
valueunless :: Applicative f => Bool -> f () -> f ()
#

The reverse of when.

Examples
Example1 expression
do x <- getLine       unless (x == "hi") (putStrLn "hi!")comingupwithexamplesisdifficulthi!
Example1 expression
unless (pi > exp 1) NothingJust ()

Bifunctor

3 declarations

Re-exported from Data.Bifunctor:

methodbimap :: (a -> b) -> (c -> d) -> p a c -> p b d
#

Map over both arguments at the same time.

bimap f g ≡ first f . second g
Examples
Example1 expression
bimap toUpper (+1) ('j', 3)('J',4)
Example1 expression
bimap toUpper (+1) (Left 'j')Left 'J'
Example1 expression
bimap toUpper (+1) (Right 3)Right 4
methodfirst :: (a -> b) -> p a c -> p b c
#

Map covariantly over the first argument.

first f ≡ bimap f id
Examples
Example1 expression
first toUpper ('j', 3)('J',3)
Example1 expression
first toUpper (Left 'j')Left 'J'
methodsecond :: (b -> c) -> p a b -> p a c
#

Map covariantly over the second argument.

second ≡ bimap id
Examples
Example1 expression
second (+1) ('j', 3)('j',4)
Example1 expression
second (+1) (Right 3)Right 4

Bifoldable

32 declarations

Re-exported from Data.Bifoldable:

methodbifold :: Monoid m => p m m -> m
#

Combines the elements of a structure using a monoid.

bifold ≡ bifoldMap id id
Examples

Basic usage:

Example1 expression
bifold (Right [1, 2, 3])[1,2,3]
Example1 expression
bifold (Left [5, 6])[5,6]
Example1 expression
bifold ([1, 2, 3], [4, 5])[1,2,3,4,5]
Example1 expression
bifold (Product 6, Product 7)Product {getProduct = 42}
Example1 expression
bifold (Sum 6, Sum 7)Sum {getSum = 13}
methodbifoldMap :: Monoid m => (a -> m) -> (b -> m) -> p a b -> m
#

Combines the elements of a structure, given ways of mapping them to a common monoid.

bifoldMap f g ≡ bifoldr (mappend . f) (mappend . g) mempty
Examples

Basic usage:

Example1 expression
bifoldMap (take 3) (fmap digitToInt) ([1..], "89")[1,2,3,8,9]
Example1 expression
bifoldMap (take 3) (fmap digitToInt) (Left [1..])[1,2,3]
Example1 expression
bifoldMap (take 3) (fmap digitToInt) (Right "89")[8,9]
methodbifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c
#

Combines the elements of a structure in a right associative manner. Given a hypothetical function toEitherList :: p a b -> [Either a b] yielding a list of all elements of a structure in order, the following would hold:

bifoldr f g z ≡ foldr (either f g) z . toEitherList
Examples

Basic usage:

> bifoldr (+) (*) 3 (5, 7)
26 -- 5 + (7 * 3)

> bifoldr (+) (*) 3 (7, 5)
22 -- 7 + (5 * 3)

> bifoldr (+) (*) 3 (Right 5)
15 -- 5 * 3

> bifoldr (+) (*) 3 (Left 5)
8 -- 5 + 3
methodbifoldl :: (c -> a -> c) -> (c -> b -> c) -> c -> p a b -> c
#

Combines the elements of a structure in a left associative manner. Given a hypothetical function toEitherList :: p a b -> [Either a b] yielding a list of all elements of a structure in order, the following would hold:

bifoldl f g z
     ≡ foldl (acc -> either (f acc) (g acc)) z . toEitherList

Note that if you want an efficient left-fold, you probably want to use bifoldl' instead of bifoldl. The reason is that the latter does not force the "inner" results, resulting in a thunk chain which then must be evaluated from the outside-in.

Examples

Basic usage:

> bifoldl (+) (*) 3 (5, 7)
56 -- (5 + 3) * 7

> bifoldl (+) (*) 3 (7, 5)
50 -- (7 + 3) * 5

> bifoldl (+) (*) 3 (Right 5)
15 -- 5 * 3

> bifoldl (+) (*) 3 (Left 5)
8 -- 5 + 3
valuebifoldr'
  1. :: Bifoldable t
  2. => a -> c -> c
  3. -> b -> c -> c
  4. -> c
  5. -> t a b
  6. -> c
#

As bifoldr, but strict in the result of the reduction functions at each step.

valuebifoldr1 :: Bifoldable t => (a -> a -> a) -> t a a -> a
#

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

Examples

Basic usage:

Example1 expression
bifoldr1 (+) (5, 7)12
Example1 expression
bifoldr1 (+) (Right 7)7
Example1 expression
bifoldr1 (+) (Left 5)5
> bifoldr1 (+) (BiList [1, 2] [3, 4])
10 -- 1 + (2 + (3 + 4))
Example1 expression
bifoldr1 (+) (BiList [1, 2] [])3

On empty structures, this function throws an exception:

Example1 expression
bifoldr1 (+) (BiList [] [])*** Exception: bifoldr1: empty structure...
valuebifoldrM
  1. :: (Bifoldable t, Monad m)
  2. => a -> c -> m c
  3. -> b -> c -> m c
  4. -> c
  5. -> t a b
  6. -> m c
#

Right associative monadic bifold over a structure.

valuebifoldl'
  1. :: Bifoldable t
  2. => a -> b -> a
  3. -> a -> c -> a
  4. -> a
  5. -> t b c
  6. -> a
#

As bifoldl, but strict in the result of the reduction functions at each step.

This ensures that each step of the bifold is forced to weak head normal form before being applied, avoiding the collection of thunks that would otherwise occur. This is often what you want to strictly reduce a finite structure to a single, monolithic result (e.g., bilength).

valuebifoldl1 :: Bifoldable t => (a -> a -> a) -> t a a -> a
#

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

Examples

Basic usage:

Example1 expression
bifoldl1 (+) (5, 7)12
Example1 expression
bifoldl1 (+) (Right 7)7
Example1 expression
bifoldl1 (+) (Left 5)5
> bifoldl1 (+) (BiList [1, 2] [3, 4])
10 -- ((1 + 2) + 3) + 4
Example1 expression
bifoldl1 (+) (BiList [1, 2] [])3

On empty structures, this function throws an exception:

Example1 expression
bifoldl1 (+) (BiList [] [])*** Exception: bifoldl1: empty structure...
valuebifoldlM
  1. :: (Bifoldable t, Monad m)
  2. => a -> b -> m a
  3. -> a -> c -> m a
  4. -> a
  5. -> t b c
  6. -> m a
#

Left associative monadic bifold over a structure.

Examples

Basic usage:

Example1 expression
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 ("Hello", True)"Hello""True"42
Example1 expression
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Right True)"True"42
Example1 expression
bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Left "Hello")"Hello"42
valuebitraverse_
  1. :: (Bifoldable t, Applicative f)
  2. => a -> f c
  3. -> b -> f d
  4. -> t a b
  5. -> f ()
#

Map each element of a structure using one of two actions, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results, see bitraverse.

Examples

Basic usage:

Example1 expression
bitraverse_ print (print . show) ("Hello", True)"Hello""True"
Example1 expression
bitraverse_ print (print . show) (Right True)"True"
Example1 expression
bitraverse_ print (print . show) (Left "Hello")"Hello"
valuebifor_
  1. :: (Bifoldable t, Applicative f)
  2. => t a b
  3. -> a -> f c
  4. -> b -> f d
  5. -> f ()
#

As bitraverse_, but with the structure as the primary argument. For a version that doesn't ignore the results, see bifor.

Examples

Basic usage:

Example1 expression
bifor_ ("Hello", True) print (print . show)"Hello""True"
Example1 expression
bifor_ (Right True) print (print . show)"True"
Example1 expression
bifor_ (Left "Hello") print (print . show)"Hello"
valuebisequence_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f ()
#

Evaluate each action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results, see bisequence.

Examples

Basic usage:

Example1 expression
bisequence_ (print "Hello", print "World")"Hello""World"
Example1 expression
bisequence_ (Left (print "Hello"))"Hello"
Example1 expression
bisequence_ (Right (print "World"))"World"
valuebiasum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a
#

The sum of a collection of actions, generalizing biconcat.

Examples

Basic usage:

Example1 expression
biasum (Nothing, Nothing)Nothing
Example1 expression
biasum (Nothing, Just 42)Just 42
Example1 expression
biasum (Just 18, Nothing)Just 18
Example1 expression
biasum (Just 18, Just 42)Just 18
valuebiList :: Bifoldable t => t a a -> [a]
#

Collects the list of elements of a structure, from left to right.

Examples

Basic usage:

Example1 expression
biList (18, 42)[18,42]
Example1 expression
biList (Left 18)[18]
valuebinull :: Bifoldable t => t a b -> Bool
#

Test whether the structure is empty.

Examples

Basic usage:

Example1 expression
binull (18, 42)False
Example1 expression
binull (Right 42)False
Example1 expression
binull (BiList [] [])True
valuebilength :: Bifoldable t => t a b -> Int
#

Returns the size/length of a finite structure as an Int.

Examples

Basic usage:

Example1 expression
bilength (True, 42)2
Example1 expression
bilength (Right 42)1
Example1 expression
bilength (BiList [1,2,3] [4,5])5
Example1 expression
bilength (BiList [] [])0

On infinite structures, this function hangs:

> bilength (BiList [1..] [])
* Hangs forever *
valuebielem :: (Bifoldable t, Eq a) => a -> t a a -> Bool
#

Does the element occur in the structure?

Examples

Basic usage:

Example1 expression
bielem 42 (17, 42)True
Example1 expression
bielem 42 (17, 43)False
Example1 expression
bielem 42 (Left 42)True
Example1 expression
bielem 42 (Right 13)False
Example1 expression
bielem 42 (BiList [1..5] [1..100])True
Example1 expression
bielem 42 (BiList [1..5] [1..41])False
valuebimaximum :: (Bifoldable t, Ord a) => t a a -> a
#

The largest element of a non-empty structure.

Examples

Basic usage:

Example1 expression
bimaximum (42, 17)42
Example1 expression
bimaximum (Right 42)42
Example1 expression
bimaximum (BiList [13, 29, 4] [18, 1, 7])29
Example1 expression
bimaximum (BiList [13, 29, 4] [])29

On empty structures, this function throws an exception:

Example1 expression
bimaximum (BiList [] [])*** Exception: bimaximum: empty structure...
valuebiminimum :: (Bifoldable t, Ord a) => t a a -> a
#

The least element of a non-empty structure.

Examples

Basic usage:

Example1 expression
biminimum (42, 17)17
Example1 expression
biminimum (Right 42)42
Example1 expression
biminimum (BiList [13, 29, 4] [18, 1, 7])1
Example1 expression
biminimum (BiList [13, 29, 4] [])4

On empty structures, this function throws an exception:

Example1 expression
biminimum (BiList [] [])*** Exception: biminimum: empty structure...
valuebisum :: (Bifoldable t, Num a) => t a a -> a
#

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

Examples

Basic usage:

Example1 expression
bisum (42, 17)59
Example1 expression
bisum (Right 42)42
Example1 expression
bisum (BiList [13, 29, 4] [18, 1, 7])72
Example1 expression
bisum (BiList [13, 29, 4] [])46
Example1 expression
bisum (BiList [] [])0
valuebiproduct :: (Bifoldable t, Num a) => t a a -> a
#

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

Examples

Basic usage:

Example1 expression
biproduct (42, 17)714
Example1 expression
biproduct (Right 42)42
Example1 expression
biproduct (BiList [13, 29, 4] [18, 1, 7])190008
Example1 expression
biproduct (BiList [13, 29, 4] [])1508
Example1 expression
biproduct (BiList [] [])1
valuebiconcat :: Bifoldable t => t [a] [a] -> [a]
#

Reduces a structure of lists to the concatenation of those lists.

Examples

Basic usage:

Example1 expression
biconcat ([1, 2, 3], [4, 5])[1,2,3,4,5]
Example1 expression
biconcat (Left [1, 2, 3])[1,2,3]
Example1 expression
biconcat (BiList [[1, 2, 3, 4, 5], [6, 7, 8]] [[9]])[1,2,3,4,5,6,7,8,9]
valuebiconcatMap :: Bifoldable t => (a -> [c]) -> (b -> [c]) -> t a b -> [c]
#

Given a means of mapping the elements of a structure to lists, computes the concatenation of all such lists in order.

Examples

Basic usage:

Example1 expression
biconcatMap (take 3) (fmap digitToInt) ([1..], "89")[1,2,3,8,9]
Example1 expression
biconcatMap (take 3) (fmap digitToInt) (Left [1..])[1,2,3]
Example1 expression
biconcatMap (take 3) (fmap digitToInt) (Right "89")[8,9]
valuebiand :: Bifoldable t => t Bool Bool -> Bool
#

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

Examples

Basic usage:

Example1 expression
biand (True, False)False
Example1 expression
biand (True, True)True
Example1 expression
biand (Left True)True

Empty structures yield True:

Example1 expression
biand (BiList [] [])True

A False value finitely far from the left end yields False (short circuit):

Example1 expression
biand (BiList [True, True, False, True] (repeat True))False

A False value infinitely far from the left end hangs:

> biand (BiList (repeat True) [False])
* Hangs forever *

An infinitely True value hangs:

> biand (BiList (repeat True) [])
* Hangs forever *
valuebior :: Bifoldable t => t Bool Bool -> Bool
#

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

Examples

Basic usage:

Example1 expression
bior (True, False)True
Example1 expression
bior (False, False)False
Example1 expression
bior (Left True)True

Empty structures yield False:

Example1 expression
bior (BiList [] [])False

A True value finitely far from the left end yields True (short circuit):

Example1 expression
bior (BiList [False, False, True, False] (repeat False))True

A True value infinitely far from the left end hangs:

> bior (BiList (repeat False) [True])
* Hangs forever *

An infinitely False value hangs:

> bior (BiList (repeat False) [])
* Hangs forever *
valuebiany :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
#

Determines whether any element of the structure satisfies its appropriate predicate argument. Empty structures yield False.

Examples

Basic usage:

Example1 expression
biany even isDigit (27, 't')False
Example1 expression
biany even isDigit (27, '8')True
Example1 expression
biany even isDigit (26, 't')True
Example1 expression
biany even isDigit (Left 27)False
Example1 expression
biany even isDigit (Left 26)True
Example1 expression
biany even isDigit (BiList [27, 53] ['t', '8'])True

Empty structures yield False:

Example1 expression
biany even isDigit (BiList [] [])False
valuebiall :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
#

Determines whether all elements of the structure satisfy their appropriate predicate argument. Empty structures yield True.

Examples

Basic usage:

Example1 expression
biall even isDigit (27, 't')False
Example1 expression
biall even isDigit (26, '8')True
Example1 expression
biall even isDigit (Left 27)False
Example1 expression
biall even isDigit (Left 26)True
Example1 expression
biall even isDigit (BiList [26, 52] ['3', '8'])True

Empty structures yield True:

Example1 expression
biall even isDigit (BiList [] [])True
valuebimaximumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a
#

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

Examples

Basic usage:

Example1 expression
bimaximumBy compare (42, 17)42
Example1 expression
bimaximumBy compare (Left 17)17
Example1 expression
bimaximumBy compare (BiList [42, 17, 23] [-5, 18])42

On empty structures, this function throws an exception:

Example1 expression
bimaximumBy compare (BiList [] [])*** Exception: bifoldr1: empty structure...
valuebiminimumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a
#

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

Examples

Basic usage:

Example1 expression
biminimumBy compare (42, 17)17
Example1 expression
biminimumBy compare (Left 17)17
Example1 expression
biminimumBy compare (BiList [42, 17, 23] [-5, 18])-5

On empty structures, this function throws an exception:

Example1 expression
biminimumBy compare (BiList [] [])*** Exception: bifoldr1: empty structure...
valuebinotElem :: (Bifoldable t, Eq a) => a -> t a a -> Bool
#

binotElem is the negation of bielem.

Examples

Basic usage:

Example1 expression
binotElem 42 (17, 42)False
Example1 expression
binotElem 42 (17, 43)True
Example1 expression
binotElem 42 (Left 42)False
Example1 expression
binotElem 42 (Right 13)True
Example1 expression
binotElem 42 (BiList [1..5] [1..100])False
Example1 expression
binotElem 42 (BiList [1..5] [1..41])True
valuebifind :: Bifoldable t => (a -> Bool) -> t a a -> Maybe a
#

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

Examples

Basic usage:

Example1 expression
bifind even (27, 53)Nothing
Example1 expression
bifind even (27, 52)Just 52
Example1 expression
bifind even (26, 52)Just 26

Empty structures always yield Nothing:

Example1 expression
bifind even (BiList [] [])Nothing

Bitraverse

5 declarations

Re-exported from Data.Bitraversable:

methodbitraverse
  1. :: Applicative f
  2. => a -> f c
  3. -> b -> f d
  4. -> t a b
  5. -> f (t c d)
#

Evaluates the relevant functions at each element in the structure, running the action, and builds a new structure with the same shape, using the results produced from sequencing the actions.

bitraverse f g ≡ bisequenceA . bimap f g

For a version that ignores the results, see bitraverse_.

Examples

Basic usage:

Example1 expression
bitraverse listToMaybe (find odd) (Left [])Nothing
Example1 expression
bitraverse listToMaybe (find odd) (Left [1, 2, 3])Just (Left 1)
Example1 expression
bitraverse listToMaybe (find odd) (Right [4, 5])Just (Right 5)
Example1 expression
bitraverse listToMaybe (find odd) ([1, 2, 3], [4, 5])Just (1,5)
Example1 expression
bitraverse listToMaybe (find odd) ([], [4, 5])Nothing
valuebisequence :: (Bitraversable t, Applicative f) => t (f a) (f b) -> f (t a b)
#

Sequences all the actions in a structure, building a new structure with the same shape using the results of the actions. For a version that ignores the results, see bisequence_.

bisequence ≡ bitraverse id id
Examples

Basic usage:

Example1 expression
bisequence (Just 4, Nothing)Nothing
Example1 expression
bisequence (Just 4, Just 5)Just (4,5)
Example1 expression
bisequence ([1, 2, 3], [4, 5])[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]
valuebifor
  1. :: (Bitraversable t, Applicative f)
  2. => t a b
  3. -> a -> f c
  4. -> b -> f d
  5. -> f (t c d)
#

bifor is bitraverse with the structure as the first argument. For a version that ignores the results, see bifor_.

Examples

Basic usage:

Example1 expression
bifor (Left []) listToMaybe (find even)Nothing
Example1 expression
bifor (Left [1, 2, 3]) listToMaybe (find even)Just (Left 1)
Example1 expression
bifor (Right [4, 5]) listToMaybe (find even)Just (Right 4)
Example1 expression
bifor ([1, 2, 3], [4, 5]) listToMaybe (find even)Just (1,4)
Example1 expression
bifor ([], [4, 5]) listToMaybe (find even)Nothing
valuebimapAccumL
  1. :: Bitraversable t
  2. => a -> b -> (a, c)
  3. -> a -> d -> (a, e)
  4. -> a
  5. -> t b d
  6. -> (a, t c e)
#

The bimapAccumL function behaves like a combination of bimap and bifoldl; it traverses a structure from left to right, threading a state of type a and using the given actions to compute new elements for the structure.

Examples

Basic usage:

Example1 expression
bimapAccumL (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo")(8,("True","oof"))
valuebimapAccumR
  1. :: Bitraversable t
  2. => a -> b -> (a, c)
  3. -> a -> d -> (a, e)
  4. -> a
  5. -> t b d
  6. -> (a, t c e)
#

The bimapAccumR function behaves like a combination of bimap and bifoldr; it traverses a structure from right to left, threading a state of type a and using the given actions to compute new elements for the structure.

Examples

Basic usage:

Example1 expression
bimapAccumR (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo")(7,("True","oof"))

MonadPlus

4 declarations

Re-exported from Control.Monad:

methodmzero :: m a
#

The identity of mplus. It should also satisfy the equations

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

The default definition is

mzero = empty
methodmplus :: m a -> m a -> m a
#

An associative operation. The default definition is

mplus = (<|>)
valuemsum :: (Foldable t, MonadPlus m) => t (m a) -> m a
#

The sum of a collection of actions using (<|>), generalizing concat.

msum is just like asum, but specialised to MonadPlus.

Examples

Basic usage, using the MonadPlus instance for Maybe:

Example1 expression
msum [Just "Hello", Nothing, Just "World"]Just "Hello"

Arrow

3 declarations

Re-exported from Control.Arrow and Control.Category:

method(&&&) :: 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.

method(***) :: 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.

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

Left-to-right composition

Function

8 declarations

Re-exported from Data.Function:

valueid :: a -> a
#

Identity function.

id x = x

This function might seem useless at first glance, but it can be very useful in a higher order context.

Examples
Example1 expression
length $ filter id [True, True, False, True]3
Example1 expression
Just (Just 3) >>= idJust 3
Example1 expression
foldr id 0 [(^3), (*5), (+2)]1000
valueconst :: a -> b -> a
#

const x y always evaluates to x, ignoring its second argument.

const x = \_ -> x

This function might seem useless at first glance, but it can be very useful in a higher order context.

Examples
Example1 expression
const 42 "hello"42
Example1 expression
map (const 42) [0..3][42,42,42,42]
value(.) :: (b -> c) -> (a -> b) -> a -> c
#

Right to left function composition.

Property
(f . g) x = f (g x)
Property
f . id = f = id . f
Examples
Example1 expression
map ((*2) . length) [[], [0, 1, 2], [0]][0,6,2]
Example1 expression
foldr (.) id [(+1), (*3), (^3)] 225
Example1 expression
let (...) = (.).(.) in ((*2)...(+)) 5 1030
value($) :: (a -> b) -> a -> b
#

($) is the function application operator.

Applying ($) to a function f and an argument x gives the same result as applying f to x directly. The definition is akin to this:

($) :: (a -> b) -> a -> b
($) f x = f x

This is id specialized from a -> a to (a -> b) -> (a -> b) which by the associativity of (->) is the same as (a -> b) -> a -> b.

On the face of it, this may appear pointless! But it's actually one of the most useful and important operators in Haskell.

The order of operations is very different between ($) and normal function application. Normal function application has precedence 10 - higher than any operator - and associates to the left. So these two definitions are equivalent:

expr = min 5 1 + 5
expr = ((min 5) 1) + 5

($) has precedence 0 (the lowest) and associates to the right, so these are equivalent:

expr = min 5 $ 1 + 5
expr = (min 5) (1 + 5)
Examples

A common use cases of ($) is to avoid parentheses in complex expressions.

For example, instead of using nested parentheses in the following Haskell function:

-- | Sum numbers in a string: strSum "100  5 -7" == 98
strSum :: String -> Int
strSum s = sum (mapMaybe readMaybe (words s))

we can deploy the function application operator:

-- | Sum numbers in a string: strSum "100  5 -7" == 98
strSum :: String -> Int
strSum s = sum $ mapMaybe readMaybe $ words s

($) is also used as a section (a partially applied operator), in order to indicate that we wish to apply some yet-unspecified function to a given value. For example, to apply the argument 5 to a list of functions:

applyFive :: [Int]
applyFive = map ($ 5) [(+1), (2^)]
>>> [6, 32]
Technical Remark (Representation Polymorphism)

($) is fully representation-polymorphic. This allows it to also be used with arguments of unlifted and even unboxed kinds, such as unboxed integers:

fastMod :: Int -> Int -> Int
fastMod (I# x) (I# m) = I# $ remInt# x m
value(&) :: a -> (a -> b) -> b
#

& is a reverse application operator. This provides notational convenience. Its precedence is one higher than that of the forward application operator $, which allows & to be nested in $.

This is a version of flip id, where id is specialized from a -> a to (a -> b) -> (a -> b) which by the associativity of (->) is (a -> b) -> a -> b. flipping this yields a -> (a -> b) -> b which is the type signature of &

Examples
Example1 expression
5 & (+1) & show"6"
Example1 expression
sqrt $ [1 / n^2 | n <- [1..1000]] & sum & (*6)3.1406380562059946
valueflip :: (a -> b -> c) -> b -> a -> c
#

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

Property
flip f x y = f y x
Property
flip . flip = id
Examples
Example1 expression
flip (++) "hello" "world""worldhello"
Example1 expression
let (.>) = flip (.) in (+1) .> show $ 5"6"
valuefix :: (a -> a) -> a
#

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

When f is strict, this means that because, by the definition of strictness, f ⊥ = ⊥ and such the least defined fixed point of any strict function is ⊥.

Examples

We can write the factorial function using direct recursion as

Example1 expression
let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5120

This uses the fact that Haskell’s let introduces recursive bindings. We can rewrite this definition using fix,

Instead of making a recursive call, we introduce a dummy parameter rec; when used within fix, this parameter then refers to fix’s argument, hence the recursion is reintroduced.

Example1 expression
fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5120

Using fix, we can implement versions of repeat as fix . (:) and cycle as fix . (++)

Example1 expression
take 10 $ fix (0:)[0,0,0,0,0,0,0,0,0,0]
Example1 expression
map (fix (\rec n -> if n < 2 then n else rec (n - 1) + rec (n - 2))) [1..10][1,1,2,3,5,8,13,21,34,55]
Implementation Details

The current implementation of fix uses structural sharing

fix f = let x = f x in x

A more straightforward but non-sharing version would look like

fix f = f (fix f)
valueon :: (b -> b -> c) -> (a -> b) -> a -> a -> c
#

on b u x y runs the binary function b on the results of applying unary function u to two arguments x and y. From the opposite perspective, it transforms two inputs and combines the outputs.

(op `on` f) x y = f x `op` f y
Examples
Example1 expression
sortBy (compare `on` length) [[0, 1, 2], [0, 1], [], [0]][[],[0],[0,1],[0,1,2]]
Example1 expression
((+) `on` length) [1, 2, 3] [-1]4
Example1 expression
((,) `on` (*2)) 2 3(4,6)
Algebraic properties
  • (*) `on` id = (*) -- (if (*) ∉ {⊥, const ⊥})
  • ((*) `on` f) `on` g = (*) `on` (f . g)
  • flip on f . flip on g = flip on (g . f)

Miscellaneous functions

6 declarations
value($!) :: (a -> b) -> a -> b
#

Strict (call-by-value) application operator. It takes a function and an argument, evaluates the argument to weak head normal form (WHNF), then calls the function with that value.

valueseq :: a -> b -> b
#

The value of seq a b is bottom if a is bottom, and otherwise equal to b. In other words, it evaluates the first argument a to weak head normal form (WHNF). seq is usually introduced to improve performance by avoiding unneeded laziness.

A note on evaluation order: the expression seq a b does not guarantee that a will be evaluated before b. The only guarantee given by seq is that the both a and b will be evaluated before seq returns a value. In particular, this means that b may be evaluated before a. If you need to guarantee a specific order of evaluation, you must use the function pseq from the "parallel" package.

valueundefined :: HasCallStack => a
#

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

valueasTypeOf :: a -> a -> a
#

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

valueasIO :: IO a -> IO a
#

Helper function to force an action to run in IO. Especially useful for overly general contexts, like hspec tests.

List

15 declarations

Re-exported from Data.List:

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

(++) appends 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.

Performance considerations

This function takes linear time in the number of elements of the first list. Thus it is better to associate repeated applications of (++) to the right (which is the default behaviour): xs ++ (ys ++ zs) or simply xs ++ ys ++ zs, but not (xs ++ ys) ++ zs. For the same reason GHC.Internal.Data.List.concat = GHC.Internal.Data.List.foldr (++) [] has linear performance, while GHC.Internal.Data.List.foldl (++) [] is prone to quadratic slowdown

Examples
Example1 expression
[1, 2, 3] ++ [4, 5, 6][1,2,3,4,5,6]
Example1 expression
[] ++ [1, 2, 3][1,2,3]
Example1 expression
[3, 2, 1] ++ [][3,2,1]
valuebreak :: (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 p is equivalent to span (not . p) and consequently to (takeWhile (not . p) xs, dropWhile (not . p) xs), even if p is _|_.

Laziness
Example1 expression
break undefined []([],[])
Example1 expression
fst (break (const True) undefined)*** Exception: Prelude.undefined
Example1 expression
fst (break (const True) (undefined : undefined))[]
Example1 expression
take 1 (fst (break (const False) (1 : undefined)))[1]

break produces the first component of the tuple lazily:

Example1 expression
take 10 (fst (break (const False) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
Example1 expression
break (> 3) [1,2,3,4,1,2,3,4]([1,2,3],[4,1,2,3,4])
Example1 expression
break (< 9) [1,2,3]([],[1,2,3])
Example1 expression
break (> 9) [1,2,3]([1,2,3],[])
valuedrop :: Int -> [a] -> [a]
#

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

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

Examples
Example1 expression
drop 6 "Hello World!""World!"
Example1 expression
drop 3 [1,2,3,4,5][4,5]
Example1 expression
drop 3 [1,2][]
Example1 expression
drop 3 [][]
Example1 expression
drop (-1) [1,2][1,2]
Example1 expression
drop 0 [1,2][1,2]
valuedropWhile :: (a -> Bool) -> [a] -> [a]
#

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

Examples
Example1 expression
dropWhile (< 3) [1,2,3,4,5,1,2,3][3,4,5,1,2,3]
Example1 expression
dropWhile (< 9) [1,2,3][]
Example1 expression
dropWhile (< 0) [1,2,3][1,2,3]
valuefilter :: (a -> Bool) -> [a] -> [a]
#

\mathcal{O}(n). 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]
Examples
Example1 expression
filter odd [1, 2, 3][1,3]
Example1 expression
filter (\l -> length l > 3) ["Hello", ", ", "World", "!"]["Hello","World"]
Example1 expression
filter (/= 3) [1, 2, 3, 4, 3, 2, 1][1,2,4,2,1]
valuelookup :: Eq a => a -> [(a, b)] -> Maybe b
#

\mathcal{O}(n). lookup key assocs looks up a key in an association list. For the result to be Nothing, the list must be finite.

Examples
Example1 expression
lookup 2 []Nothing
Example1 expression
lookup 2 [(1, "first")]Nothing
Example1 expression
lookup 2 [(1, "first"), (2, "second"), (3, "third")]Just "second"
valuemap :: (a -> b) -> [a] -> [b]
#

\mathcal{O}(n). map f xs is the list obtained by applying f to each element of xs, i.e.,

map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
map f [x1, x2, ...] == [f x1, f x2, ...]

this means that map id == id

Examples
Example1 expression
map (+1) [1, 2, 3][2,3,4]
Example1 expression
map id [1, 2, 3][1,2,3]
Example1 expression
map (\n -> 3 * n + 1) [1, 2, 3][4,7,10]
valuereplicate :: Int -> a -> [a]
#

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

Examples
Example1 expression
replicate 0 True[]
Example1 expression
replicate (-1) True[]
Example1 expression
replicate 4 True[True,True,True,True]
valuereverse :: [a] -> [a]
#

\mathcal{O}(n). reverse xs returns the elements of xs in reverse order. xs must be finite.

Laziness

reverse is lazy in its elements.

Example1 expression
head (reverse [undefined, 1])1
Example1 expression
reverse (1 : 2 : undefined)*** Exception: Prelude.undefined
Examples
Example1 expression
reverse [][]
Example1 expression
reverse [42][42]
Example1 expression
reverse [2,5,7][7,5,2]
Example1 expression
reverse [1..]* Hangs forever *
valuespan :: (a -> Bool) -> [a] -> ([a], [a])
#

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

span p xs is equivalent to (takeWhile p xs, dropWhile p xs), even if p is _|_.

Laziness
Example4 expressions
span undefined []([],[])fst (span (const False) undefined)*** Exception: Prelude.undefinedfst (span (const False) (undefined : undefined))[]take 1 (fst (span (const True) (1 : undefined)))[1]

span produces the first component of the tuple lazily:

Example1 expression
take 10 (fst (span (const True) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
Example1 expression
span (< 3) [1,2,3,4,1,2,3,4]([1,2],[3,4,1,2,3,4])
Example1 expression
span (< 9) [1,2,3]([1,2,3],[])
Example1 expression
span (< 0) [1,2,3]([],[1,2,3])
valuetake :: Int -> [a] -> [a]
#

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

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

Laziness
Example2 expressions
take 0 undefined[]take 2 (1 : 2 : undefined)[1,2]
Examples
Example1 expression
take 5 "Hello World!""Hello"
Example1 expression
take 3 [1,2,3,4,5][1,2,3]
Example1 expression
take 3 [1,2][1,2]
Example1 expression
take 3 [][]
Example1 expression
take (-1) [1,2][]
Example1 expression
take 0 [1,2][]
valuetakeWhile :: (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.

Laziness
Example1 expression
takeWhile (const False) undefined*** Exception: Prelude.undefined
Example1 expression
takeWhile (const False) (undefined : undefined)[]
Example1 expression
take 1 (takeWhile (const True) (1 : undefined))[1]
Examples
Example1 expression
takeWhile (< 3) [1,2,3,4,1,2,3,4][1,2]
Example1 expression
takeWhile (< 9) [1,2,3][1,2,3]
Example1 expression
takeWhile (< 0) [1,2,3][]
valuezip :: [a] -> [b] -> [(a, b)]
#

\mathcal{O}(\min(m,n)). zip takes two lists and returns a list of corresponding pairs.

zip is right-lazy:

Example2 expressions
zip [] undefined[]zip undefined []*** Exception: Prelude.undefined...

zip is capable of list fusion, but it is restricted to its first list argument and its resulting list.

Examples
Example1 expression
zip [1, 2, 3] ['a', 'b', 'c'][(1,'a'),(2,'b'),(3,'c')]

If one input list is shorter than the other, excess elements of the longer list are discarded, even if one of the lists is infinite:

Example1 expression
zip [1] ['a', 'b'][(1,'a')]
Example1 expression
zip [1, 2] ['a'][(1,'a')]
Example1 expression
zip [] [1..][]
Example1 expression
zip [1..] [][]
valuezipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
#

\mathcal{O}(\min(m,n)). zipWith generalises zip by zipping with the function given as the first argument, instead of a tupling function.

zipWith (,) xs ys == zip xs ys
zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]

zipWith is right-lazy:

Example2 expressions
let f = undefinedzipWith f [] undefined[]

zipWith is capable of list fusion, but it is restricted to its first list argument and its resulting list.

Examples

zipWith (+) can be applied to two lists to produce the list of corresponding sums:

Example1 expression
zipWith (+) [1, 2, 3] [4, 5, 6][5,7,9]
Example1 expression
zipWith (++) ["hello ", "foo"] ["world!", "bar"]["hello world!","foobar"]
valuenubOrd :: Ord a => [a] -> [a]
#

Strip out duplicates

String

5 declarations

Re-exported from Data.String:

valuelines :: String -> [String]
#

Splits the argument into a list of lines stripped of their terminating \n characters. The \n terminator is optional in a final non-empty line of the argument string.

When the argument string is empty, or ends in a \n character, it can be recovered by passing the result of lines to the unlines function. Otherwise, unlines appends the missing terminating \n. This makes unlines . lines idempotent:

(unlines . lines) . (unlines . lines) = (unlines . lines)
Examples
Example1 expression
lines ""           -- empty input contains no lines[]
Example1 expression
lines "\n"         -- single empty line[""]
Example1 expression
lines "one"        -- single unterminated line["one"]
Example1 expression
lines "one\n"      -- single non-empty line["one"]
Example1 expression
lines "one\n\n"    -- second line is empty["one",""]
Example1 expression
lines "one\ntwo"   -- second line is unterminated["one","two"]
Example1 expression
lines "one\ntwo\n" -- two non-empty lines["one","two"]
valueunlines :: [String] -> String
#

Appends a \n character to each input string, then concatenates the results. Equivalent to foldMap (s -> s ++ "\n").

Examples
Example1 expression
unlines ["Hello", "World", "!"]"Hello\nWorld\n!\n"

Note that unlines . lines /= id when the input is not \n-terminated:

Example1 expression
unlines . lines $ "foo\nbar""foo\nbar\n"
valueunwords :: [String] -> String
#

unwords joins words with separating spaces (U+0020 SPACE).

unwords is neither left nor right inverse of words:

Example2 expressions
words (unwords [" "])[]unwords (words "foo\nbar")"foo bar"
Examples
Example1 expression
unwords ["Lorem", "ipsum", "dolor"]"Lorem ipsum dolor"
Example1 expression
unwords ["foo", "bar", "", "baz"]"foo bar  baz"
valuewords :: String -> [String]
#

words breaks a string up into a list of words, which were delimited by white space (as defined by isSpace). This function trims any white spaces at the beginning and at the end.

Examples
Example1 expression
words "Lorem ipsum\ndolor"["Lorem","ipsum","dolor"]
Example1 expression
words " foo bar "["foo","bar"]

Show

Re-exported from Text.Show:

methodshow :: a -> String
#

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

Read

Re-exported from Text.Read:

valuereadMaybe :: Read a => String -> Maybe a
#

Parse a string using the Read instance. Succeeds if there is exactly one valid result.

Example1 expression
readMaybe "123" :: Maybe IntJust 123
Example1 expression
readMaybe "hello" :: Maybe IntNothing

NFData

4 declarations

Re-exported from Control.DeepSeq:

value($!!) :: NFData a => (a -> b) -> a -> b
#

the deep analogue of $!. In the expression f $!! x, x is fully evaluated before the function f is applied to it.

methodrnf :: a -> ()
#

rnf should reduce its argument to normal form (that is, fully evaluate all sub-components), and then return ().

Generic NFData deriving

Starting with GHC 7.2, you can automatically derive instances for types possessing a Generic instance.

Note: Generic1 can be auto-derived starting with GHC 7.4

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics (Generic, Generic1)
import Control.DeepSeq

data Foo a = Foo a String
             deriving (Eq, Generic, Generic1)

instance NFData a => NFData (Foo a)
instance NFData1 Foo

data Colour = Red | Green | Blue
              deriving Generic

instance NFData Colour

Starting with GHC 7.10, the example above can be written more concisely by enabling the new DeriveAnyClass extension:

{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}

import GHC.Generics (Generic)
import Control.DeepSeq

data Foo a = Foo a String
             deriving (Eq, Generic, Generic1, NFData, NFData1)

data Colour = Red | Green | Blue
              deriving (Generic, NFData)
Compatibility with previous deepseq versions

Prior to version 1.4.0.0, the default implementation of the rnf method was defined as

rnf a = seq a ()

However, starting with deepseq-1.4.0.0, the default implementation is based on DefaultSignatures allowing for more accurate auto-derived NFData instances. If you need the previously used exact default rnf method implementation semantics, use

instance NFData Colour where rnf x = seq x ()

or alternatively

instance NFData Colour where rnf = rwhnf

or

{-# LANGUAGE BangPatterns #-}
instance NFData Colour where rnf !_ = ()
valuedeepseq :: NFData a => a -> b -> b
#

deepseq: fully evaluates the first argument, before returning the second.

The name deepseq is used to illustrate the relationship to seq: where seq is shallow in the sense that it only evaluates the top level of its argument, deepseq traverses the entire data structure evaluating it completely.

deepseq can be useful for forcing pending exceptions, eradicating space leaks, or forcing lazy I/O to happen. It is also useful in conjunction with parallel Strategies (see the parallel package).

There is no guarantee about the ordering of evaluation. The implementation may evaluate the components of the structure in any order or in parallel. To impose an actual order on evaluation, use pseq from Control.Parallel in the parallel package.

valueforce :: NFData a => a -> a
#

a variant of deepseq that is useful in some circumstances:

force x = x `deepseq` x

force x fully evaluates x, and then returns it. Note that force x only performs evaluation when the value of force x itself is demanded, so essentially it turns shallow evaluation into deep evaluation.

force can be conveniently used in combination with ViewPatterns:

{-# LANGUAGE BangPatterns, ViewPatterns #-}
import Control.DeepSeq

someFun :: ComplexData -> SomeResult
someFun (force -> !arg) = {- 'arg' will be fully evaluated -}

Another useful application is to combine force with evaluate in order to force deep evaluation relative to other IO operations:

import Control.Exception (evaluate)
import Control.DeepSeq

main = do
  result <- evaluate $ force $ pureComputation
  {- 'result' will be fully evaluated at this point -}
  return ()

Finally, here's an exception safe variant of the readFile' example:

readFile' :: FilePath -> IO String
readFile' fn = bracket (openFile fn ReadMode) hClose $ \h ->
                       evaluate . force =<< hGetContents h

Void

1 declaration

Re-exported from Data.Void:

valueabsurd :: Void -> a
#

Since Void values logically don't exist, this witnesses the logical reasoning tool of "ex falso quodlibet".

Example2 expressions
let x :: Either Void Int; x = Right 5:{case x of    Right r -> r    Left l  -> absurd l:}5

Reader

6 declarations

Re-exported from Control.Monad.Reader:

methodlift :: Monad m => m a -> t m a
#

Lift a computation from the argument monad to the constructed monad.

methodask :: m r
#

Retrieves the monad environment.

valueasks
  1. :: MonadReader r m
  2. => (r -> a)

    The selector function to apply to the environment.

  3. -> m a
#

Retrieves a function of the current environment.

methodlocal :: (r -> r) -> m a -> m a
#

Executes a computation in a modified environment.

valuerunReader
  1. :: Reader r a

    A Reader to run.

  2. -> r

    An initial environment.

  3. -> a
#

Runs a Reader and extracts the final value from it. (The inverse of reader.)

ByteString

2 declarations

Helper synonyms for converting bewteen lazy and strict ByteStrings

ShortByteString

2 declarations

Re-exported from Data.ByteString.Short:

Text

7 declarations

Re-exported from Data.Text.Encoding:

PrimMonad

2 declarations

Re-exported from Control.Monad.Primitive:

Re-exported from Control.Monad.ST:

valuerunST :: (forall s. ST s a) -> a
#

Return the value computed by a state thread. The forall ensures that the internal state used by the ST computation is inaccessible to the rest of the program.