This is a Prelude, but, please, do not put things in here,
put them into Nix.Utils. This module is a pass-through-multiplexer,
between our custom code (Nix.Utils) that shadows over the outside prelude that is in use (Relude)
Prelude module has a problem of being imported & used by other projects.
Nix.Utils as a module with a regular name does not have that problem.
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.
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.
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).
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.
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.
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_.
If f is both Functor and Contravariant then by the time you factor
in the laws of each of those classes, it can't actually use its argument in
any meaningful capacity.
This method is surprisingly useful. Where both instances exist and are
lawful we have the following laws:
mtimesDefault n a = a <> a <> ... <> a -- using <> (n-1) times
In many cases, stimes 0 a for a Monoid will produce mempty.
However, there are situations when it cannot do so. In particular,
the following situation is fairly common:
data T a = ...
class Constraint1 a
class Constraint1 a => Constraint2 a
instance Constraint1 a => Semigroup (T a)
instance Constraint2 a => Monoid (T a)
Since Constraint1 is insufficient to implement mempty,
stimes for T a cannot do so.
When working with such a type, or when working polymorphically with
Semigroup instances, mtimesDefault should be used when the
multiplier might be zero. It is implemented using stimes when
the multiplier is nonzero and mempty when it is zero.
The deep analogue of $!. f $!! x fully evaluates x
before returning f x.
There is no guarantee about the ordering of evaluation.
f x may be evaluated before x is fully evaluated.
To impose an actual order on evaluation, use pseq from
Control.Parallel in the parallel package.
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.
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 (mapMaybereadMaybe (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$mapMaybereadMaybe$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:
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.
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
A variant of <*> with the types of the arguments reversed. It differs from
flip(<*>) in that the effects are resolved in the order the arguments are
presented.
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.
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.
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.
vvalueliftA3 :: Applicativef => (a -> b -> c -> d) -> fa -> fb -> fc -> fd
Attempt to convert an Integral type a to an Integral type b using
the size of the types as measured by Bits methods.
A simpler version of this function is:
toIntegral :: (Integral a, Integral b) => a -> Maybe b
toIntegral x
| toInteger x == toInteger y = Just y
| otherwise = Nothing
where
y = fromIntegral x
This version requires going through Integer, which can be inefficient.
However, toIntegralSized is optimized to allow GHC to statically determine
the relative type sizes (as measured by bitSizeMaybe and isSigned) and
avoid going through Integer for many types. (The implementation uses
fromIntegral, which is itself optimized with rules for base types but may
go through Integer for some type pairs.)
A common use of forever is to process input from network sockets,
System.IO.Handles, and channels
(e.g. 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:
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.
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 Monaddo-notation:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
guard (y /= 0)
return (x `div` y)
The mapAndUnzipM function maps its first argument over a list, returning
the result as a pair of lists. This function is mainly used with complicated
data structures or a state monad.
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 EitherStringInt, one using the
Left constructor and another using the Right constructor. Then
we apply "either" the Prelude.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 Int>>> let n = Right 3 :: Either String Int>>> either length (*2) s3>>> either length (*2) n6
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
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
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])
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
The find function takes a predicate and a structure and returns
the leftmost element of the structure matching the predicate, or
Nothing if there is no such element.
Left-to-right monadic fold over the elements of a structure.
Given a structure t with elements (a, b, ..., w, x, y), the result of
a fold with an operator function f is equivalent to:
foldlM f z t = do
aa <- f z a
bb <- f aa b
...
xx <- f ww x
yy <- f xx y
return yy -- Just @return z@ when the structure is empty
For a Monad m, given two functions f1 :: a -> m b and f2 :: b -> m c,
their Kleisli composition (f1 >=> f2) :: a -> m c is defined by:
(f1 >=> f2) a = f1 a >>= f2
Another way of thinking about foldlM is that it amounts to an application
to z of a Kleisli composition:
foldlM f z t =
flip f a >=> flip f b >=> ... >=> flip f x >=> flip f y $ z
The monadic effects of foldlM are sequenced from left to right.
If at some step the bind operator (>>=) short-circuits (as with, e.g.,
mzero in a MonadPlus), the evaluated effects will be from an initial
segment of the element sequence. If you want to evaluate the monadic
effects in right-to-left order, or perhaps be able to short-circuit after
processing a tail of the sequence of elements, you'll need to use foldrM
instead.
If the monadic effects don't short-circuit, the outermost application of
f is to the rightmost element y, so that, ignoring effects, the result
looks like a left fold:
((((z `f` a) `f` b) ... `f` w) `f` x) `f` y
Examples
Basic usage:
Example2 expressions
>>> let f a e = do { print e ; return $ e : a }>>> foldlM f [] [0..3]0123[3,2,1,0]
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.
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
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.
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.
& 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 flipid, 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
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
on b u x y runs the binary function bon 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.
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]
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.
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:
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:
Apply show to a Maybe Int. If we have Just n, we want to show
the underlying Intn. 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""
\mathcal{O}(n). The genericLength function is an overloaded version
of length. In particular, instead of returning an Int, it returns any
type which is an instance of Num. It is, however, less efficient than
length.
Users should take care to pick a return type that is wide enough to contain
the full length of the list. If the width is insufficient, the overflow
behaviour will depend on the (+) implementation in the selected Num
instance. The following example overflows because the actual list length
of 200 lies outside of the Int8 range of -128..127.
The group function takes a list and returns a list of lists such
that the concatenation of the result is equal to the argument. Moreover,
each sublist in the result is non-empty, all elements are equal to the
first one, and consecutive equal elements of the input end up in the
same element of the output list.
group is a special case of groupBy, which allows the programmer to supply
their own equality test.
It's often preferable to use Data.List.NonEmpty.group,
which provides type-level guarantees of non-emptiness of inner lists.
A common idiom to squash repeating elements maphead.group
is better served by
mapData.List.NonEmpty.head.Data.List.NonEmpty.group
because it avoids partial functions.
Examples
Example1 expression
>>> group "Mississippi"["M","i","ss","i","ss","i","pp","i"]
The permutations function is maximally lazy:
for each n, the value of permutations xs starts with those permutations
that permute take n xs and keep drop n xs.
The sort function implements a stable sorting algorithm.
It is a special case of sortBy, which allows the programmer to supply
their own comparison function.
Elements are arranged from lowest to highest, keeping duplicates in
the order they appeared in the input.
The sortBy function is the non-overloaded version of sort.
The argument must be finite.
The supplied comparison relation is supposed to be reflexive and antisymmetric,
otherwise, e. g., for _ _ -> GT, the ordered list simply does not exist.
The relation is also expected to be transitive: if it is not then sortBy
might fail to find an ordered permutation, even if it exists.
Examples
Example1 expression
>>> sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")][(1,"Hello"),(2,"world"),(4,"!")]
Sort a list by comparing the results of a key function applied to each
element. sortOn f is equivalent to sortBy (comparing f), but has the
performance advantage of only evaluating f once for each element in the
input list. This is called the decorate-sort-undecorate paradigm, or
Schwartzian transform.
Elements are arranged from lowest to highest, keeping duplicates in
the order they appeared in the input.
The unfoldr function is a `dual' to foldr: while foldr
reduces a list to a summary value, unfoldr builds a list from
a seed value. The function takes the element and returns Nothing
if it is done producing the list or returns Just(a,b), in which
case, a is a prepended to the list and b is used as the next
element in a recursive call. For example,
iterate f == unfoldr (\x -> Just (x, f x))
In some cases, unfoldr can undo a foldr operation:
unfoldr f' (foldr f z xs) == xs
if the following holds:
f' (f x y) = Just (x,y)
f' z = Nothing
Laziness
Example1 expression
>>> take 1 (unfoldr (\x -> Just (x, undefined)) 'a')"a"
Examples
Example1 expression
>>> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10[10,9,8,7,6,5,4,3,2,1]
Example1 expression
>>> take 10 $ unfoldr (\(x, y) -> Just (x, (y, x + y))) (0, 1)[0,1,1,2,3,5,8,13,21,54]
The mapAccumL function behaves like a combination of fmap
and foldl; it applies a function to each element of a structure,
passing an accumulating parameter from left to right, and returning
a final value of this accumulator together with the new structure.
Examples
Basic usage:
Example1 expression
>>> mapAccumL (\a b -> (a + b, a)) 0 [1..10](55,[0,1,3,6,10,15,21,28,36,45])
Example1 expression
>>> mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]("012345",["0","01","012","0123","01234"])
The mapAccumR function behaves like a combination of fmap
and foldr; it applies a function to each element of a structure,
passing an accumulating parameter from right to left, and returning
a final value of this accumulator together with the new structure.
Examples
Basic usage:
Example1 expression
>>> mapAccumR (\a b -> (a + b, a)) 0 [1..10](55,[54,52,49,45,40,34,27,19,10,0])
Example1 expression
>>> mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]("054321",["05432","0543","054","05","0"])
The sortWith function sorts a list of elements using the
user supplied function to project something out of each element
In general if the user supplied function is expensive to compute then
you should probably be using sortOn, as it only needs
to compute it once for each element. sortWith, on the other hand
must compute the mapping function for every comparison that it performs.
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 satisfyp and second element is the remainder of the list:
breakp is equivalent to span (not . p)
and consequently to (takeWhile (not . p) xs, dropWhile (not . p) xs),
even if p is _|_.
iteratef x returns an infinite list of repeated applications
of f to x:
iterate f x == [x, f x, f (f x), ...]
Laziness
Note that iterate is lazy, potentially leading to thunk build-up if
the consumer doesn't force each element. See iterate' for a strict
variant of this function.
Example3 expressions
>>> let xs = iterate (\x -> if x == 0 then undefined else x - 1) 2>>> xs[2,1,0,*** Exception: Prelude.undefined>>> length (take 10 xs)10
In xs every element following 0 is bottom, but the list itself is
infinitely long because it is generated without forcing its elements.
Examples
Example1 expression
>>> take 10 $ iterate not True[True,False,True,False,True,False,True,False,True,False]
Example1 expression
>>> take 10 $ iterate (+3) 42[42,45,48,51,54,57,60,63,66,69]
replicaten 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.
\mathcal{O}(n). scanr is the right-to-left dual of scanl. Note that the order of parameters on the accumulating function are reversed compared to scanl.
Also note that
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:
zip3 takes three lists and returns a list of triples, analogous to
zip.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
vvaluezipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
Because - is treated specially in the Haskell grammar,
(-e) is not a section, but an application of prefix negation.
However, (subtractexp) is equivalent to the disallowed section.
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, absminBound < 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.
catchSTM m f catches any exception thrown by m using throwSTM,
using the function f to handle the exception. If an exception is
thrown, any changes made by m are rolled back, but changes prior to
m persist.
A variant of throw that can only be used within the STM monad.
Throwing an exception in STM aborts the transaction and propagates the
exception. If the exception is caught via catchSTM, only the changes
enclosed by the catch are rolled back; changes made outside of catchSTM
persist.
If the exception is not caught inside of the STM, it is re-thrown by
atomically, and the entire STM is rolled back.
Although throwSTM has a type that is an instance of the type of throw, the
two functions are subtly different:
throw e `seq` x ===> throw e
throwSTM e `seq` x ===> x
The first example will cause the exception e to be raised,
whereas the second one won't. In fact, throwSTM will only cause
an exception to be raised when it is used within the STM monad.
The throwSTM variant should be used in preference to throw to
raise an exception within the STM monad because it guarantees
ordering with respect to other STM operations, whereas throw
does not.
Returns a [String] representing the current call stack. This
can be useful for debugging.
The implementation uses the call-stack simulation maintained by the
profiler, so it only works if the program was compiled with -prof
and contains suitable SCC annotations (e.g. by using -fprof-auto).
Otherwise, the list returned is likely to be empty or
uninformative.
It is lazy by the second argument (similar to (Data.Bool.||)), meaning that if
the first argument is False, the function will return False without evaluating
the second argument.
Example5 expressions
>>> Just False &&^ Just TrueJust False>>> Just True &&^ Just TrueJust True>>> Just True &&^ NothingNothing>>> Just False &&^ NothingJust False>>> Just False &&^ error "Shouldn't be evaluated"Just False
It is lazy by the second argument (similar to (Data.Bool.||)), meaning that if
the first argument is True, the function will return True without evaluating
the second argument.
Example5 expressions
>>> Just False ||^ Just TrueJust True>>> Just False ||^ Just FalseJust False>>> Just False ||^ NothingNothing>>> Just True ||^ NothingJust True>>> Just True ||^ error "Shouldn't be evaluated"Just True
Throw pure errors. Use this function only to when you are sure that this
branch of code execution is not possible. DO NOT USEerror as a normal
error handling mechanism.
⚠️CAUTION⚠️ Unlike Prelude version, error takes
Text as an argument. In case it used by mistake,
the user will see the following:
Example2 expressions
>>> error ("oops" :: String)...... 'error' expects 'Text' but was given 'String'. Possible fixes: * Make sure OverloadedStrings extension is enabled * Use 'error (toText msg)' instead of 'error msg'...>>> error False...... 'error' works with 'Text' But given: Bool...
inverseMap f creates a function that is the inverse of a given function
f. It does so by constructing Map internally for each value f a. The
implementation makes sure that the Map is constructed only once and then
shared for every call.
Memory usage note: don't inverse functions that have types like Int
as their input. In this case the created Map will have huge size.
The complexity of reversed mapping is \mathcal{O}(\log n).
Performance note: make sure to specialize monomorphic type of your functions
that use inverseMap to avoid Map reconstruction.
One of the common inverseMap use-case is inverting the show or a show-like
function.
Example4 expressions
>>> data Color = Red | Green | Blue deriving (Show, Enum, Bounded)>>> parse = inverseMap show :: String -> Maybe Color>>> parse "Red"Just Red>>> parse "Black"Nothing
Correctness note:inverseMap expects injective function as its argument,
i.e. the function must map distinct arguments to distinct values.
Like elem but doesn't work on Set and HashSet for performance reasons.
Example2 expressions
>>> elem 'x' ("abc" :: String)False>>> elem False (one True :: Set Bool)...... Do not use 'elem' and 'notElem' methods from 'Foldable' on Set Suggestions: Instead of elem :: (Foldable t, Eq a) => a -> t a -> Bool use member :: Ord a => a -> Set a -> Bool... Instead of notElem :: (Foldable t, Eq a) => a -> t a -> Bool use not . member...
Like notElem but doesn't work on Set and HashSet for performance reasons.
Example2 expressions
>>> notElem 'x' ("abc" :: String)True>>> notElem False (one True :: Set Bool)...... Do not use 'elem' and 'notElem' methods from 'Foldable' on Set Suggestions: Instead of elem :: (Foldable t, Eq a) => a -> t a -> Bool use member :: Ord a => a -> Set a -> Bool... Instead of notElem :: (Foldable t, Eq a) => a -> t a -> Bool use not . member...
Partitions a list based on the result of function which produces an Either
value. List of all elements producing Left are extracted, in order, to the first
element of the output tuple. Similarly, a list of all elements producing Right
are extracted to the second element of output.
Example1 expression
>>> :{ divideEvenOrShow :: Int -> Either Int String divideEvenOrShow n | even n = Left $ n `div` 2 | otherwise = Right $ "Odd: " <> show n :}
but it was given a more complex type to provide friendlier compile time errors.
Example3 expressions
>>> head ('a' :| "bcde")'a'>>> head [0..5 :: Int]...... 'head' works with 'NonEmpty', not ordinary lists. Possible fix: Replace: [Int] With: NonEmpty Int... However, you can use 'head' with the ordinary lists. Apply 'viaNonEmpty' function from relude: viaNonEmpty head (yourList) Note, that this will return 'Maybe Int' therefore it is a safe function unlike 'head' from the standard Prelude...>>> head (Just 'a')...... 'head' works with 'NonEmpty Char' lists But given: Maybe Char...
vvalueinit :: IsNonEmptyfa [a] "init" => fa -> [a]
but it was given a more complex type to provide friendlier compile time errors.
Example3 expressions
>>> init ('a' :| "bcde")"abcd">>> init [0..5 :: Int]...... 'init' works with 'NonEmpty', not ordinary lists. Possible fix: Replace: [Int] With: NonEmpty Int... However, you can use 'init' with the ordinary lists. Apply 'viaNonEmpty' function from relude: viaNonEmpty init (yourList) Note, that this will return 'Maybe [Int]' therefore it is a safe function unlike 'init' from the standard Prelude...>>> init (Just 'a')...... 'init' works with 'NonEmpty Char' lists But given: Maybe Char...
but it was given a more complex type to provide friendlier compile time errors.
Example3 expressions
>>> last ('a' :| "bcde")'e'>>> last [0..5 :: Int]...... 'last' works with 'NonEmpty', not ordinary lists. Possible fix: Replace: [Int] With: NonEmpty Int... However, you can use 'last' with the ordinary lists. Apply 'viaNonEmpty' function from relude: viaNonEmpty last (yourList) Note, that this will return 'Maybe Int' therefore it is a safe function unlike 'last' from the standard Prelude...>>> last (Just 'a')...... 'last' works with 'NonEmpty Char' lists But given: Maybe Char...
vvaluetail :: IsNonEmptyfa [a] "tail" => fa -> [a]
but it was given a more complex type to provide friendlier compile time errors.
Example3 expressions
>>> tail ('a' :| "bcde")"bcde">>> tail [0..5 :: Int]...... 'tail' works with 'NonEmpty', not ordinary lists. Possible fix: Replace: [Int] With: NonEmpty Int... However, you can use 'tail' with the ordinary lists. Apply 'viaNonEmpty' function from relude: viaNonEmpty tail (yourList) Note, that this will return 'Maybe [Int]' therefore it is a safe function unlike 'tail' from the standard Prelude...>>> tail (Just 'a')...... 'tail' works with 'NonEmpty Char' lists But given: Maybe Char...
Creates an infinite list from a finite list by appending the list
to itself infinite times (i.e. by cycling the list). Unlike cycle
from Data.List, this implementation doesn't throw error on empty
lists, but returns an empty list instead.
Example2 expressions
>>> cycle [][]>>> take 10 $ cycle [1,2,3][1,2,3,1,2,3,1,2,3,1]
This is a more type safe version of forever, which has a convenient
but unsafe type.
Consider the following two examples. In the getIntForever functions, it
falsely expects Int as the result of the forever function. But it would need
to wait *forever* to get that, and this mistake won't be caught by the type
system and compiler:
getIntForever :: IO Int
getIntForever = do
i <- forever $ do ...
pure i
In contrast, using infinitely instead of forever in foo is a type error.
Generalized version of show. Unlike show this function
is polymorphic in its result type. This makes it more convenient to work with
data types like Text or ByteString. However, if you
pass the result of show to a function that expects polymorphic argument, this
can break type inference, so use -XTypeApplications to specify the textual
type explicitly.
Example3 expressions
>>> show (42 :: Int)"42">>> show (42 :: Double)"42.0">>> print (show @Text True)"True"
but it was given a more complex type to provide friendlier compile time errors.
Example5 expressions
>>> lines ""[]>>> lines "one line"["one line"]>>> lines "line 1\nline 2"["line 1","line 2"]>>> lines ("string line" :: String)...... 'lines' works with 'Text', not 'String'. Possible fixes: 1. Make sure OverloadedStrings extension is enabled. 2. Apply 'toText' to a single value. 3. Apply 'map toText' to the list value....>>> lines True...... 'lines' works with 'Text' But given: 'Bool'...
but it was given a more complex type to provide friendlier compile time errors.
Example5 expressions
>>> unlines []"">>> unlines ["line 1"]"line 1\n">>> unlines ["first line", "second line"]"first line\nsecond line\n">>> unlines (["line 1", "line 2"] :: [String])...... 'unlines' works with 'Text', not 'String'. Possible fixes: 1. Make sure OverloadedStrings extension is enabled. 2. Apply 'toText' to a single value. 3. Apply 'map toText' to the list value....>>> unlines [True, False]...... 'unlines' works with 'Text' But given: 'Bool'...
but it was given a more complex type to provide friendlier compile time errors.
Example5 expressions
>>> unwords []"">>> unwords ["singleWord"]"singleWord">>> unwords ["word", "another"]"word another">>> unwords (["word", "another"] :: [String])...... 'unwords' works with 'Text', not 'String'. Possible fixes: 1. Make sure OverloadedStrings extension is enabled. 2. Apply 'toText' to a single value. 3. Apply 'map toText' to the list value....>>> unwords [True, False]...... 'unwords' works with 'Text' But given: 'Bool'...
but it was given a more complex type to provide friendlier compile time errors.
Example5 expressions
>>> words ""[]>>> words "one line"["one","line"]>>> words " >_< "[">_<"]>>> words ("string words" :: String)...... 'words' works with 'Text', not 'String'. Possible fixes: 1. Make sure OverloadedStrings extension is enabled. 2. Apply 'toText' to a single value. 3. Apply 'map toText' to the list value....>>> words True...... 'words' works with 'Text' But given: 'Bool'...
A version of putTMVar that does not retry. The tryPutTMVar
function attempts to put the value a into the TMVar, returning
True if it was successful, or False otherwise.
The function coerce allows you to safely convert between values of
types that have the same representation with no run-time overhead. In the
simplest case you can use it instead of a newtype constructor, to go from
the newtype's concrete type to the abstract type. But it also works in
more complicated settings, e.g. converting a list of newtypes to a list of
concrete types.
When used in conversions involving a newtype wrapper,
make sure the newtype constructor is in scope.
This function is representation-polymorphic, but the
RuntimeRep type argument is marked as Inferred, meaning
that it is not available for visible type application. This means
the typechecker will accept coerce @Int @Age 42.
Examples
Example5 expressions
>>> newtype TTL = TTL Int deriving (Eq, Ord, Show)>>> newtype Age = Age Int deriving (Eq, Ord, Show)>>> coerce (Age 42) :: TTLTTL 42>>> coerce (+ (1 :: Int)) (Age 42) :: TTLTTL 43>>> coerce (map (+ (1 :: Int))) [Age 42, Age 24] :: [TTL][TTL 43,TTL 25]
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.
Bifoldable identifies foldable structures with two different varieties
of elements (as opposed to Foldable, which has one variety of element).
Common examples are Either and (,):
instance Bifoldable Either where
bifoldMap f _ (Left a) = f a
bifoldMap _ g (Right b) = g b
instance Bifoldable (,) where
bifoldr f g z (a, b) = f a (g b z)
Some examples below also use the following BiList to showcase empty
Bifoldable behaviors when relevant (Either and (,) containing always exactly
resp. 1 and 2 elements):
data BiList a b = BiList [a] [b]
instance Bifoldable BiList where
bifoldr f g z (BiList as bs) = foldr f (foldr g z bs) as
A minimal Bifoldable definition consists of either bifoldMap or
bifoldr. When defining more than this minimal set, one should ensure
that the following identities hold:
bifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> pab -> 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:
bifoldl :: (c -> a -> c) -> (c -> b -> c) -> c -> pab -> 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:
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.
Class laws for tuples hold only up to laziness. The
Bifoldable methods are lazier than their Foldable counterparts.
For example the law bifoldr (flipconst) ≡ foldr does
not hold for tuples if laziness is exploited:
A bifunctor is a type constructor that takes
two type arguments and is a functor in both arguments. That
is, unlike with Functor, a type constructor such as Either
does not need to be partially applied for a Bifunctor
instance, and the methods in this class permit mapping
functions over the Left value or the Right value,
or both at the same time.
Formally, the class Bifunctor represents a bifunctor
from Hask -> Hask.
Intuitively it is a bifunctor where both the first and second
arguments are covariant.
The class definition of a Bifunctorp uses the
QuantifiedConstraints
language extension to quantify over the first type
argument a in its context. The context requires that p a
must be a Functor for all a. In other words a partially
applied Bifunctor must be a Functor. This makes Functor a
superclass of Bifunctor such that a function with a
Bifunctor constraint may use fmap in its implementation.
Functor has been a quantified superclass of
Bifunctor since base-4.18.0.0.
Bitraversable identifies bifunctorial data structures whose elements can
be traversed in order, performing Applicative or Monad actions at each
element, and collecting a result structure with the same shape.
As opposed to Traversable data structures, which have one variety of
element on which an action can be performed, Bitraversable data structures
have two such varieties of elements.
A definition of bitraverse must satisfy the following laws:
instance Bitraversable Either where
bitraverse f _ (Left x) = Left <$> f x
bitraverse _ g (Right y) = Right <$> g y
instance Bitraversable (,) where
bitraverse f g (x, y) = (,) <$> f x <*> g y
Bitraversable relates to its superclasses in the following ways:
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.
Class laws for tuples hold only up to laziness. The
Bitraversable methods are lazier than their Traversable counterparts.
For example the law bitraversepure ≡ traverse does
not hold for tuples if laziness is exploited:
Example2 expressions
>>> (bitraverse pure pure undefined :: IO (Int, Word)) `seq` ()()>>> (traverse pure (errorWithoutStackTrace "error!") :: IO (Int, Word)) `seq` ()*** Exception: error!
Right-to-left composition of functors.
The composition of applicative functors is always applicative,
but the composition of monads is not always a monad.
Whereas in Haskell, one can think of a Functor as containing or producing
values, a contravariant functor is a functor that can be thought of as
consuming values.
As an example, consider the type of predicate functions a -> Bool. One
such predicate might be negative x = x < 0, which
classifies integers as to whether they are negative. However, given this
predicate, we can re-use it in other situations, providing we have a way to
map values to integers. For instance, we can use the negative predicate
on a person's bank balance to work out if they are currently overdrawn:
newtype Predicate a = Predicate { getPredicate :: a -> Bool }
instance Contravariant Predicate where
contramap :: (a' -> a) -> (Predicate a -> Predicate a')
contramap f (Predicate p) = Predicate (p . f)
| `- First, map the input...
`----- then apply the predicate.
overdrawn :: Predicate Person
overdrawn = contramap personBankBalance negative
Any instance should be subject to the following laws:
Note, that the second law follows from the free theorem of the type of
contramap and the first law, so you need only check that the former
condition holds.
Replace all locations in the output with the same value.
The default definition is contramap . const, but this may be
overridden with a more efficient version.
NOTE: This is not needed anymore since Semigroup became a superclass of
Monoid in base-4.11 and this newtype be deprecated at some point in the future.
EncodingErrorToLText"ByteString""LText" => ToLTextByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toLText ("some string" :: ByteString)...... Type 'ByteString' doesn't have instance of 'ToLText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ByteString -> LText decodeUtf8Strict :: ByteString -> Either UnicodeException LText...
EncodingErrorToString"ByteString""String" => ToStringByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toString ("some string" :: ByteString)...... Type 'ByteString' doesn't have instance of 'ToString'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ByteString -> String decodeUtf8Strict :: ByteString -> Either UnicodeException String...
EncodingErrorToText"ByteString""Text" => ToTextByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toText ("some string" :: ByteString)...... Type 'ByteString' doesn't have instance of 'ToText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ByteString -> Text decodeUtf8Strict :: ByteString -> Either UnicodeException Text...
LiftByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Internal.Type
It has a lower memory overhead than a ByteString and does not
contribute to heap fragmentation. It can be converted to or from a
ByteString (at the cost of copying the string data). It supports very few
other operations.
Instances26IsList, Eq, Data, Ord, Read, Show, …
IsListShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
EqShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
DataShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
OrdShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
Lexicographic order.
ReadShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
ShowShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
EncodingErrorToLText"ShortByteString""LText" => ToLTextShortByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toLText ("some string" :: ShortByteString)...... Type 'ShortByteString' doesn't have instance of 'ToLText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ShortByteString -> LText decodeUtf8Strict :: ShortByteString -> Either UnicodeException LText...
EncodingErrorToString"ShortByteString""String" => ToStringShortByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toString ("some string" :: ShortByteString)...... Type 'ShortByteString' doesn't have instance of 'ToString'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ShortByteString -> String decodeUtf8Strict :: ShortByteString -> Either UnicodeException String...
EncodingErrorToText"ShortByteString""Text" => ToTextShortByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toText ("some string" :: ShortByteString)...... Type 'ShortByteString' doesn't have instance of 'ToText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ShortByteString -> Text decodeUtf8Strict :: ShortByteString -> Either UnicodeException Text...
LiftShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
NFDataa => NFData (Seta)Defined in containers-0.8 · Data.Set.Internal
(Orda, Arbitrarya) => Arbitrary (Seta)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
WARNING: Users working on the internals of the Set type via e.g. Data.Set.Internal
should be aware that this instance aims to give a good representation of Set a
as mathematical sets but *does not* aim to provide a varied distribution over the
underlying representation.
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
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 !_ = ()
Instances434Lifting2, Lifting, NFData, …
NFDataKeyDefined in aeson-2.2.5.1 · Data.Aeson.Key
>>> 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.
>>> 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.
sequence computations and combine their results (<*> and liftA2).
A minimal complete definition must include implementations of pure
and one of either <*> or liftA2. If it defines both, then they must behave
the same as their default definitions:
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.
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.Char>>> import GHC.Internal.Text.ParserCombinators.ReadP>>> let p = string "my name is " *> munch1 isAlpha <* eof>>> readP_to_S p "my name is Simon"[("Simon","")]
A type f is a Functor if it provides a function fmap which, given any types a and b
lets you apply any function from (a -> b) to turn an f a into an f b, preserving the
structure of f. Furthermore f needs to adhere to the following:
Note, that the second law follows from the free theorem of the type fmap and
the first law, so you need only check that the former condition holds.
See these articles by School of Haskell or
David Luposchainsky
for an explanation.
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 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 NothingNothing>>> fmap 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 17>>> fmap show (Right 17)Right "17"
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:
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
FunctorResponseDefined in http-client-0.7.19 · Network.HTTP.Client.Types
FunctorErrorFancyDefined in megaparsec-9.5.0 · Text.Megaparsec.Error
FunctorErrorItemDefined in megaparsec-9.5.0 · Text.Megaparsec.Error
FunctorPackerDefined in memory-0.18.0 · Data.ByteArray.Pack.Internal
FunctorChunkDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Help.Chunk
FunctorComplResultDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
FunctorCompletionDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
FunctorPDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
FunctorCReaderDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorOptReaderDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorOptionDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorParserDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorParserFailureDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorParserInfoDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorParserMDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorParserResultDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorReadMDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
FunctorConsumedDefined in parsec-3.1.18.0 · Text.Parsec.Prim
FunctorAnnotDetailsDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
FunctorDocDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
FunctorSpanDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
FunctorDocDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
Alter the document’s annotations.
This instance makes Doc more flexible (because it can be used in
Functor-polymorphic values), but fmap is much less readable compared to
using reAnnotate in code that only works for Doc anyway. Consider
using the latter when the type does not matter.
FunctorFlattenResultDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
This instance makes SimpleDocStream more flexible (because it can be used in
Functor-polymorphic values), but fmap is much less readable compared to
using reAnnotateST in code that only works for SimpleDocStream anyway.
Consider using the latter when the type does not matter.
FunctorSimpleDocTreeDefined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.SimpleDocTree
Alter the document’s annotations.
This instance makes SimpleDocTree more flexible (because it can be used in
Functor-polymorphic values), but fmap is much less readable compared to
using reAnnotateST in code that only works for SimpleDocTree anyway.
Consider using the latter when the type does not matter.
FunctorArrayDefined in primitive-0.9.1.0 · Data.Primitive.Array
FunctorSmallArrayDefined in primitive-0.9.1.0 · Data.Primitive.SmallArray
FunctorPackerDefined in ram-0.22.1 · Data.ByteArray.Pack.Internal
FunctorCharMapDefined in regex-tdfa-1.3.2.6 · Data.IntMap.CharMap2
FunctorSTMDefined in stm-2.5.3.1 · Control.Sequential.STM
FunctorMaybeDefined in strict-0.5.1 · Data.Strict.Maybe
FunctorLocalTimeDefined in time-hourglass-0.3.0 · Time.LocalTime
FunctorHandshakeMDefined in tls-2.4.9 · Network.TLS.Handshake.State
FunctorRecordMDefined in tls-2.4.9 · Network.TLS.Record.State
FunctorTLSStDefined in tls-2.4.9 · Network.TLS.State
FunctorVectorDefined in vector-0.13.2.0 · Data.Vector
FunctorIdDefined in vector-0.13.2.0 · Data.Vector.Fusion.Util
FunctorVectorDefined in vector-0.13.2.0 · Data.Vector.Strict
FunctorBoxDefined in vector-stream-0.1.0.1 · Data.Stream.Monadic
FunctorBoolPairDefined in witherable-0.5 · Witherable
FunctorStreamDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
Functor []Defined in ghc-internal-10.0.0 · GHC.Internal.Base
The Monad class defines the basic operations over a monad,
a concept from a branch of mathematics known as category theory.
From the perspective of a Haskell programmer, however, it is best to
think of a monad as an abstract datatype of actions.
Haskell's do expressions provide a convenient syntax for writing
monadic expressions.
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', because it
is used to introduce bindings in monadic contexts, but some people may
refer to it as 'flatMap', which results from it being equivalent 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.
Sequentially compose two actions, discarding any value produced
by the first, like sequencing operators (such as the semicolon)
in imperative languages.
Inject a value into the monadic type.
This function should not be different from its default implementation
as pure. The justification for the existence of this function is
merely historic.
The method names refer to the monoid of lists under concatenation,
but there are many other instances.
Some types can be viewed as a monoid in more than one way,
e.g. both addition and multiplication on numbers.
In such cases we often define newtypes and make those instances
of Monoid, e.g. Data.Semigroup.Sum and Data.Semigroup.Product.
NOTE: Semigroup is a superclass of Monoid since base-4.11.0.0.
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.
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.
Lift a semigroup into Maybe forming a Monoid according to
http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be
turned into a monoid simply by adjoining an element e not in S
and defining e*e = e and e*s = s = s*e for all s ∈ S."
Since 4.11.0: constraint on inner a value generalised from
Monoid to Semigroup.
Semigroupa => Monoid (Chunka)Defined in optparse-applicative-0.18.1.0 · Options.Applicative.Help.Chunk
The default definition will raise an exception for a multiplier that is <= 0.
This may be overridden with an implementation that is total. For monoids
it is preferred to use stimesMonoid.
By making this a member of the class, idempotent semigroups
and monoids can upgrade this to execute in \mathcal{O}(1) by
picking stimes = stimesIdempotent or stimes =
stimesIdempotentMonoid respectively.
SemigroupDocDefined in pretty-1.1.3.6 · Text.PrettyPrint.HughesPJ
SemigroupAnsiStyleDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
Keep the first decision for each of foreground color, background color,
boldness, italication, and underlining. If a certain style is not set, the
terminal’s default will be used.
Concatenation of StrictBuilder is right-biased:
the right builder will be run first. This allows a builder to
run tail-recursively when it was accumulated left-to-right.
SemigroupShortTextDefined in text-short-0.1.6.1 · Data.Text.Short.Internal
Note that Semigroup and Monoid instances are right-biased.
That is, if both arguments have the same key, the value from the right
argument will be used.
Since: 1.7.5
Altf => Semigroup (Alt_fa)Defined in semigroupoids-6.0.2 · Data.Semigroup.Foldable
Applyf => Semigroup (Actfa)Defined in semigroupoids-6.0.2 · Data.Semigroup.Bifoldable
Applyf => Semigroup (Actfa)Defined in semigroupoids-6.0.2 · Data.Semigroup.Foldable
The Semigroup instance for ParsecT is used to append the result
of several parsers, for example:
(many $ char a) <> (many $ char b)
The above will parse a string like "aabbb" and return a successful
parse result "aabbb". Compare against the below which will
produce a result of "bbb" for the same input:
(many $ char a) >> (many $ char b)
(many $ char a) *> (many $ char b)
Semigroupc => Semigroup (K1icp)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
The Eq class defines equality (==) and inequality (/=).
All the basic datatypes exported by the Prelude are instances of Eq,
and Eq may be derived for any datatype whose constituents are also
instances of Eq.
The Haskell Report defines no laws for Eq. However, instances are
encouraged to follow these properties:
EqUndefinedDefined in relude-1.2.2.2 · Relude.Debug
EqScientificDefined in scientific-0.3.9.0 · Data.Scientific
Scientific numbers can be safely compared for equality. No magnitude 10^e
is calculated so there's no risk of a blowup in space or time when comparing
scientific numbers coming from untrusted sources.
EqUTF8EncodingDefined in serialise-0.2.6.1 · Codec.Serialise.Internal.GeneralisedUTF8
EqCondensePolicyDefined in split-0.2.5.1 · Data.List.Split.Internals
EqDelimPolicyDefined in split-0.2.5.1 · Data.List.Split.Internals
EqEndPolicyDefined in split-0.2.5.1 · Data.List.Split.Internals
EqTSemDefined in stm-2.5.3.1 · Control.Concurrent.STM.TSem
EqFileTypeDefined in streaming-commons-0.2.3.1 · Data.Streaming.Filesystem
EqHostPreferenceDefined in streaming-commons-0.2.3.1 · Data.Streaming.Network.Internal
EqCodePointDefined in streaming-commons-0.2.3.1 · Data.Streaming.Text
EqDecoderStateDefined in streaming-commons-0.2.3.1 · Data.Streaming.Text
EqStrategyDefined in streaming-commons-0.2.3.1 · Data.Streaming.Zlib.Lowlevel
The Ord class is used for totally ordered datatypes.
Instances of Ord can be derived for any user-defined datatype whose
constituent types are in Ord. The declared order of the constructors in
the data declaration determines the ordering in derived Ord instances. The
Ordering datatype allows a single comparison to determine the precise
ordering of two objects.
Ord, as defined by the Haskell report, implements a total order and has the
following properties:
Note that (7.) and (8.) do not require min and max to return either of
their arguments. The result is merely required to equal one of the
arguments in terms of (==). Users who expect a stronger guarantee are advised
to write their own min and/or max functions.
The nuance of the above distinction is not always fully internalized by
developers, and in the past (tracing back to the Haskell 1.4 Report) the
specification for Ord asserted the stronger property that (min x y, max x
y) = (x, y) or (y, x), or in other words, that min and maxwill
return one of their arguments, using argument order as the tie-breaker if
the arguments are equal by comparison. A few list and
Foldable functions have behavior that is best understood
with this assumption in mind: all variations of minimumBy and maximumBy
(which can't use min and max in their implementations) are written such
that minimumBy compare and maximumBy compare are respectively
equivalent to minimum and maximum (which do use min and max) only if
min and max adhere to this tie-breaking convention. Otherwise, if there
are multiple least or largest elements in a container, minimum and
maximum may not return the same one that minimumBy compare and
maximumBy compare do (though they should return something that is
equal). (This is relevant for types with non-extensional equality, like
Arg, but also in cases where the precise reference held
matters for memory-management reasons.) Unless there is a reason to deviate,
it is less confusing for implementors of Ord to respect this same
convention (as the default definitions of min and max do).
Minimal complete definition: either compare or <=.
Using compare can be more efficient for complex types.
OrdValueDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
The ordering is total, consistent with Eq instance.
However, nothing else about the ordering is specified,
and it may change from environment to environment and version to version
of either this package or its dependencies (hashable and 'unordered-containers').
OrdAdjacencyIntMapDefined in algebraic-graphs-0.8 · Algebra.Graph.AdjacencyIntMap
OrdAlphabetDefined in algebraic-graphs-0.8 · Algebra.Graph.Labelled.Example.Automaton
OrdStateDefined in algebraic-graphs-0.8 · Algebra.Graph.Labelled.Example.Automaton
OrdCityDefined in algebraic-graphs-0.8 · Algebra.Graph.Labelled.Example.Network
OrdBlinkSpeedDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
OrdColorDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
OrdColorIntensityDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
OrdConsoleIntensityDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
OrdConsoleLayerDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
OrdUnderliningDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
OrdPosDefined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
OrdNumberDefined in attoparsec-0.14.4 · Data.Attoparsec.Number
OrdByteArrayDefined in base-4.23.0.0 · Data.Array.Byte
Non-lexicographic ordering. This compares the lengths of
the byte arrays first and uses a lexicographic ordering if
the lengths are equal. Subject to change between major versions.
OrdEncodingDefined in basement-0.0.16 · Basement.String
OrdUTF32_InvalidDefined in basement-0.0.16 · Basement.String.Encoding.UTF32
OrdAsciiStringDefined in basement-0.0.16 · Basement.Types.AsciiString
OrdChar7Defined in basement-0.0.16 · Basement.Types.Char7
OrdFileSizeDefined in basement-0.0.16 · Basement.Types.OffsetSize
OrdAddrDefined in basement-0.0.16 · Basement.Types.Ptr
OrdWord128Defined in basement-0.0.16 · Basement.Types.Word128
OrdWord256Defined in basement-0.0.16 · Basement.Types.Word256
OrdStringDefined in basement-0.0.16 · Basement.UTF8.Base
OrdOptionsDefined in bifunctors-5.6.3 · Data.Bifunctor.TH
OrdByteOrderDefined in byteorder-1.0.4 · System.ByteOrder
OrdByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Internal.Type
OrdByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Lazy.Internal
OrdShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal
Lexicographic order.
OrdByteArrayDefined in cborg-0.2.10.0 · Codec.CBOR.ByteArray
OrdSlicedByteArrayDefined in cborg-0.2.10.0 · Codec.CBOR.ByteArray.Sliced
OrdTokenTypeDefined in cborg-0.2.10.0 · Codec.CBOR.Decoding
OrdTermTokenDefined in cborg-0.2.10.0 · Codec.CBOR.FlatTerm
OrdTermDefined in cborg-0.2.10.0 · Codec.CBOR.Term
OrdSpecificityDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
OrdStmtDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
OrdTyLitDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
OrdTySynEqnDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
OrdTypeDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
OrdTypeFamilyHeadDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
OrdSomeCharDefined in ghc-internal-10.0.0 · GHC.Internal.TypeLits
OrdSomeSymbolDefined in ghc-internal-10.0.0 · GHC.Internal.TypeLits
OrdSomeNatDefined in ghc-internal-10.0.0 · GHC.Internal.TypeNats
OrdBoolDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
OrdCharDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
OrdDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
IEEE 754 Double-precision type includes not only numbers, but also
positive and negative infinities and a special element called NaN
(which can be quiet or signal).
IEEE 754-2008, section 5.11 requires that if at least one of arguments of
<=, <, >, >= is NaN then the result of the comparison is False,
and instanceOrdDouble complies with this requirement. This violates
the reflexivity: both NaN<=NaN and NaN>=NaN are False.
IEEE 754-2008, section 5.10 defines totalOrder predicate. Unfortunately,
compare on Doubles violates the IEEE standard and does not define a total order.
More specifically, both compareNaNx and comparexNaN always return GT.
Thus, users must be extremely cautious when using instanceOrdDouble.
For instance, one should avoid ordered containers with keys represented by Double,
because data loss and corruption may happen. An IEEE-compliant compare is available
in fp-ieee package as TotallyOrdered newtype.
Moving further, the behaviour of min and max with regards to NaN is
also non-compliant. IEEE 754-2008, section 5.3.1 defines that quiet NaN
should be treated as a missing data by minNum and maxNum functions,
for example, minNum(NaN, 1) = minNum(1, NaN) = 1. Some languages such as Java
deviate from the standard implementing minNum(NaN, 1) = minNum(1, NaN) = NaN.
However, min / max in base are even worse: minNaN 1 is 1, but min 1 NaN
is NaN.
IEEE 754-2008 compliant min / max can be found in ieee754 package under
minNum / maxNum names. Implementations compliant with
minimumNumber / maximumNumber from a newer
IEEE 754-2019,
section 9.6 are available from fp-ieee package.
OrdFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
See instanceOrdDouble for discussion of deviations from IEEE 754 standard.
OrdIntDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
OrdOrderingDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
OrdTyConDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
OrdWordDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
OrdUndefinedDefined in relude-1.2.2.2 · Relude.Debug
OrdScientificDefined in scientific-0.3.9.0 · Data.Scientific
Scientific numbers can be safely compared for ordering. No magnitude 10^e
is calculated so there's no risk of a blowup in space or time when comparing
scientific numbers coming from untrusted sources.
OrdFileTypeDefined in streaming-commons-0.2.3.1 · Data.Streaming.Filesystem
OrdHostPreferenceDefined in streaming-commons-0.2.3.1 · Data.Streaming.Network.Internal
OrdStrategyDefined in streaming-commons-0.2.3.1 · Data.Streaming.Zlib.Lowlevel
Ord (Proxys)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Proxy
Ord (TypeRepa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Typeable.Internal
Ord (U1p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
Ord (V1p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
Ord (a:-b)Defined in constraints-0.14.4 · Data.Constraint
Assumes IncoherentInstances doesn't exist.
Ord (fa) => Ord (Zippyfa)Defined in semialign-1.3.1.1 · Data.Zip
Orda => Ord (Argab)Defined in base-4.23.0.0 · Data.Semigroup
Note that Arg's Ord instance has min and max implementations that
differ from the tie-breaking conventions of the default implementation of
min and max in class Ord; Arg breaks ties by favoring the first
argument in both functions.
Orda => Ord (ListNna)Defined in basement-0.0.16 · Basement.Sized.List
Orda => Ord (EnumMapka)Defined in regex-tdfa-1.3.2.6 · Data.IntMap.EnumMap2
GComparetag => Ord (Sometag)Defined in some-1.0.6 · Data.GADT.Internal
GComparetag => Ord (Sometag)Defined in some-1.0.6 · Data.Some.GADT
GComparetag => Ord (Sometag)Defined in some-1.0.6 · Data.Some.Newtype
(Ord1f, Orda) => Ord (Apfa)Defined in free-5.2 · Control.Applicative.Free
(Ord1f, Orda) => Ord (Cofreefa)Defined in free-5.2 · Control.Comonad.Cofree
(Ord1f, Orda) => Ord (Freefa)Defined in free-5.2 · Control.Monad.Free
(Ord1f, Orda) => Ord (Freefa)Defined in free-5.2 · Control.Monad.Free.Ap
(Ord1f, Orda) => Ord (Liftfa)Defined in transformers-0.6.3.0 · Control.Applicative.Lift
(Ord1m, Orda) => Ord (IterTma)Defined in free-5.2 · Control.Monad.Trans.Iter
(Ord1m, Orda) => Ord (MaybeTma)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Maybe
(Ord1w, Orda) => Ord (CoiterTwa)Defined in free-5.2 · Control.Comonad.Trans.Coiter
(PrimTypea, Orda) => Ord (BlockNna)Defined in basement-0.0.16 · Basement.Sized.Block
(Monoide, Orda, Orde) => Ord (Graphea)Defined in algebraic-graphs-0.8 · Algebra.Graph.Labelled
(Orda, Ordb) => Ord (AdjacencyMapab)Defined in algebraic-graphs-0.8 · Algebra.Graph.Bipartite.AdjacencyMap
(Orda, Ordb) => Ord (Listab)Defined in algebraic-graphs-0.8 · Algebra.Graph.Bipartite.AdjacencyMap
(Orda, Ordb) => Ord (Matchingab)Defined in algebraic-graphs-0.8 · Algebra.Graph.Bipartite.AdjacencyMap.Algorithm
(Orda, Ordb) => Ord (Theseab)Defined in basement-0.0.16 · Basement.These
(Orda, Ordb) => Ord (Eitherab)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Either
(Orda, Ordb) => Ord (Eitherab)Defined in strict-0.5.1 · Data.Strict.Either
(Orda, Ordb) => Ord (Theseab)Defined in strict-0.5.1 · Data.Strict.These
(Orda, Ordb) => Ord (Pairab)Defined in strict-0.5.1 · Data.Strict.Tuple
(Orda, Ordb) => Ord (Theseab)Defined in these-1.2.1 · Data.These
(Orda, Ordb) => Ord (a, b)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
(Ordann, Ordexpr) => Ord (AnnUnitannexpr)Defined in hnix-0.17.0 · Nix.Expr.Types.Annotated
(Orde, Monoide, Orda) => Ord (AdjacencyMapea)Defined in algebraic-graphs-0.8 · Algebra.Graph.Labelled.AdjacencyMap
(Ordfp, Ordtxt) => Ord (DerivationOutputfptxt)Defined in nix-derivation-1.1.3 · Nix.Derivation.Types
(Ordk, Ordv) => Ord (Mapkv)Defined in containers-0.8 · Data.Map.Internal
(Ordk, Ordv) => Ord (HashMapkv)Defined in unordered-containers-0.2.21 · Data.HashMap.Internal
The ordering is total and consistent with the Eq instance. However,
nothing else about the ordering is specified, and it may change from
version to version of either this package or of hashable.
(Ordo, Orda) => Ord (Optimumoa)Defined in algebraic-graphs-0.8 · Algebra.Graph.Label
(Ordtxt, Ordfp) => Ord (Derivationfptxt)Defined in nix-derivation-1.1.3 · Nix.Derivation.Types
When a value is bound in do-notation, the pattern on the left
hand side of <- might not match. In this case, this class
provides a function to recover.
A Monad without a MonadFail instance may only be used in conjunction
with pattern that always match, such as newtypes, tuples, data types with
only a single data constructor, and irrefutable patterns (~pat).
Instances of MonadFail should satisfy the following law: fail s should
be a left zero for >>=,
fail s >>= f = fail s
If your Monad is also MonadPlus, a popular definition is
fail _ = mzero
fail s should be an action that runs in the monad itself, not an
exception (except in instances of MonadIO). In particular,
fail should not be implemented in terms of error.
Monads in which IO computations may be embedded.
Any monad built by applying a sequence of monad transformers to the
IO monad will be an instance of this class.
Instances should satisfy the following laws, which state that liftIO
is a transformer of monads:
Lift a computation from the IO monad.
This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations
(i.e. IO is the base monad for the stack).
Example
import Control.Monad.Trans.State -- from the "transformers" library
printState :: Show s => StateT s IO ()
printState = do
state <- get
liftIO $ print state
Had we omitted liftIO, we would have ended up with this error:
• Couldn't match type ‘IO’ with ‘StateT s IO’
Expected type: StateT s IO ()
Actual type: IO ()
The important part here is the mismatch between StateT s IO () and IO ().
Luckily, we know of a function that takes an IO a and returns an (m a): liftIO,
enabling us to run the program and see the expected results:
The Either type represents values with two possibilities: a value of
type Either a b is either Left a or Right b.
The Either type is sometimes used to represent a value which is
either correct or an error; by convention, the Left constructor is
used to hold an error value and the Right constructor is used to
hold a correct value (mnemonic: "right" also means "correct").
Examples
The type EitherStringInt is the type of values which can be either
a String or an Int. The Left constructor can be used only on
Strings, and the Right constructor can be used only on Ints:
Example6 expressions
>>> let s = Left "foo" :: Either String Int>>> sLeft "foo">>> let n = Right 3 :: Either String Int>>> nRight 3>>> :type ss :: Either String Int>>> :type nn :: Either String Int
The fmap from our Functor instance will ignore Left values, but
will apply the supplied function to values contained in a Right:
Example4 expressions
>>> let s = Left "foo" :: Either String Int>>> let n = Right 3 :: Either String Int>>> fmap (*2) sLeft "foo">>> fmap (*2) nRight 6
The Monad instance for Either allows us to chain together multiple
actions which may fail, and fail overall if any of the individual
steps failed. First we'll write a function that can either parse an
Int from a Char, or fail.
Example3 expressions
>>> import Data.Char ( digitToInt, isDigit )>>> :{ let parseEither :: Char -> Either String Int parseEither c | isDigit c = Right (digitToInt c) | otherwise = Left "parse error">>> :}
The following should work, since both '1' and '2' can be
parsed as Ints.
Example2 expressions
>>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither '1' y <- parseEither '2' return (x + y)>>> :}
Example1 expression
>>> parseMultipleRight 3
But the following should fail overall, since the first operation where
we attempt to parse 'm' as an Int will fail:
Example2 expressions
>>> :{ let parseMultiple :: Either String Int parseMultiple = do x <- parseEither 'm' y <- parseEither '2' return (x + y)>>> :}
The Foldable class represents data structures that can be reduced to a
summary value one element at a time. Strict left-associative folds are a
good fit for space-efficient reduction, while lazy right-associative folds
are a good fit for corecursive iteration, or for folds that short-circuit
after processing an initial subsequence of the structure's elements.
Instances can be derived automatically by enabling the DeriveFoldable
extension. For example, a derived instance for a binary tree might be:
{-# LANGUAGE DeriveFoldable #-}
data Tree a = Empty
| Leaf a
| Node (Tree a) a (Tree a)
deriving Foldable
A more detailed description can be found in the Overview section of
Data.Foldable#overview.
For the class laws see the Laws section of Data.Foldable#laws.
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.
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.
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 L>>> import qualified Data.ByteString.Builder as B>>> let bld :: Int -> B.Builder; bld i = B.intDec i <> B.word8 0x20>>> let 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"
A left-associative variant of foldMap that is strict in the
accumulator. Use this method for strict reduction when partial
results are merged via (<>).
Examples
Define a Monoid over finite bit strings under xor. Use it to
strictly compute the xor of a list of Int values.
Example11 expressions
>>> :set -XGeneralizedNewtypeDeriving>>> import Data.Bits (Bits, FiniteBits, xor, zeroBits)>>> import Data.Foldable (foldMap')>>> import Numeric (showHex)>>> >>> newtype X a = X a deriving (Eq, Bounded, Enum, Bits, FiniteBits)>>> instance Bits a => Semigroup (X a) where X a <> X b = X (a `xor` b)>>> instance Bits a => Monoid (X a) where mempty = X zeroBits>>> >>> let bits :: [Int]; bits = [0xcafe, 0xfeed, 0xdeaf, 0xbeef, 0x5411]>>> (\ (X a) -> showString "0x" . showHex a $ "") $ foldMap' X bits"0x42"
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,
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]
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,
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.
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).
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.
Because we ignore the second type parameter to Const,
the Applicative instance, which has
(<*>) :: Monoid m => Const m (a -> b) -> Const m a -> Const m b
essentially turns into Monoid m => m -> m -> m, which is (<>)
Enum (fa) => Enum (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
Eq (fa) => Eq (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
(Data (fa), Dataa, Typeablef) => Data (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Data
(Applicativef, Numa) => Num (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
Note that even if the underlying Num and Applicative instances are
lawful, for most Applicatives, this instance will not be lawful. If you use
this instance with the list Applicative, the following customary laws will
not hold:
Commutativity:
Example2 expressions
>>> Ap [10,20] + Ap [1,2]Ap {getAp = [11,12,21,22]}>>> Ap [1,2] + Ap [10,20]Ap {getAp = [11,21,12,22]}
Additive inverse:
Example2 expressions
>>> Ap [] + negate (Ap [])Ap {getAp = []}>>> fromInteger 0 :: Ap [] IntAp {getAp = [0]}
Distributivity:
Example2 expressions
>>> Ap [1,2] * (3 + 4)Ap {getAp = [7,14]}>>> (Ap [1,2] * 3) + (Ap [1,2] * 4)Ap {getAp = [7,11,10,14]}
Ord (fa) => Ord (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
Read (fa) => Read (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
Show (fa) => Show (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
Generic (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
Maybe monoid returning the leftmost non-Nothing value.
First a is isomorphic to AltMaybe a, but precedes it
historically.
Beware that Data.Monoid.First is different from
Data.Semigroup.First. The former returns the first non-Nothing,
so Data.Monoid.First Nothing <> x = x. The latter simply returns the first value,
thus Data.Semigroup.First Nothing <> x = Data.Semigroup.First Nothing.
Examples
Example1 expression
>>> First (Just "hello") <> First Nothing <> First (Just "world")First {getFirst = Just "hello"}
Example1 expression
>>> First Nothing <> memptyFirst {getFirst = Nothing}
Data.Semigroup.Last. The former returns the last non-Nothing,
so x <> Data.Monoid.Last Nothing = x. The latter simply returns the last value,
thus x <> Data.Semigroup.Last Nothing = Data.Semigroup.Last Nothing.
Examples
Example1 expression
>>> Last (Just "hello") <> Last Nothing <> Last (Just "world")Last {getLast = Just "world"}
Example1 expression
>>> Last Nothing <> memptyLast {getLast = Nothing}
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.
Proxy is a type that holds no data, but has a phantom parameter of
arbitrary type (or even kind). Its use is to provide type information, even
though there is no value available of that type (or it may be too costly to
create one).
Historically, Proxy :: Proxy a is a safer alternative to the
undefined :: a idiom.
Functors representing data structures that can be transformed to
structures of the same shape by performing an Applicative (or,
therefore, Monad) action on each element from left to right.
A more detailed description of what same shape means, the various methods,
how traversals are constructed, and example advanced use-cases can be found
in the Overview section of Data.Traversable#overview.
For the class laws see the Laws section of Data.Traversable#laws.
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
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
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.
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]
The Bounded class is used to name the upper and lower limits of a
type. Ord is not a superclass of Bounded since types that are not
totally ordered may also have upper and lower bounds.
The Bounded class may be derived for any enumeration type;
minBound is the first constructor listed in the data declaration
and maxBound is the last.
Bounded may also be derived for single-constructor datatypes whose
constituent types are in Bounded.
Class Enum defines operations on sequentially ordered types.
The enumFrom... methods are used in Haskell's translation of
arithmetic sequences.
Instances of Enum may be derived for any enumeration type (types
whose constructors have no fields). The nullary constructors are
assumed to be numbered left-to-right by fromEnum from 0 through n-1.
See Chapter 10 of the Haskell Report for more details.
For any type that is an instance of class Bounded as well as Enum,
the following should hold:
fromEnum and toEnum should give a runtime error if the
result value is not representable in the result type.
For example, toEnum 7 :: Bool is an error.
enumFrom x = enumFromTo x maxBound
enumFromThen x y = enumFromThenTo x y bound
where
bound | fromEnum y >= fromEnum x = maxBound
| otherwise = minBound
Used in Haskell's translation of [n,n'..]
with [n,n'..] = enumFromThen n n', a possible implementation being
enumFromThen n n' = n : n' : worker (f x) (f x n'),
worker s v = v : worker s (s v), x = fromEnum n' - fromEnum n and
f n y
| n > 0 = f (n - 1) (succ y)
| n < 0 = f (n + 1) (pred y)
| otherwise = y
Used in Haskell's translation of [n,n'..m] with
[n,n'..m] = enumFromThenTo n n' m, a possible implementation
being enumFromThenTo n n' m = worker (f x) (c x) n m,
x = fromEnum n' - fromEnum n, c x = bool (>=) ((x 0)
f n y
| n > 0 = f (n - 1) (succ y)
| n < 0 = f (n + 1) (pred y)
| otherwise = y
and
worker s c v m
| c v m = v : worker s c (s v) m
| otherwise = []
EnumFPFormatDefined in text-2.1.4 · Data.Text.Lazy.Builder.RealFloat
EnumDayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
EnumMonthDefined in time-1.16.0.1 · Data.Time.Calendar.Month
EnumQuarterDefined in time-1.16.0.1 · Data.Time.Calendar.Quarter
EnumQuarterOfYearDefined in time-1.16.0.1 · Data.Time.Calendar.Quarter
maps Q1..Q4 to 1..4
EnumDayOfWeekDefined in time-1.16.0.1 · Data.Time.Calendar.Week
"Circular", so for example [Tuesday ..] gives an endless sequence.
Also: fromEnum gives [1 .. 7] for [Monday .. Sunday], and toEnum performs mod 7 to give a cycle of days.
EnumDiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
EnumNominalDiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.NominalDiffTime
EnumHoursDefined in time-hourglass-0.3.0 · Time.Types
EnumMinutesDefined in time-hourglass-0.3.0 · Time.Types
EnumMonthDefined in time-hourglass-0.3.0 · Time.Types
EnumSecondsDefined in time-hourglass-0.3.0 · Time.Types
EnumWeekDayDefined in time-hourglass-0.3.0 · Time.Types
EnumMessageTypeDefined in tls-2.4.9 · Network.TLS.Extension
EnumCipherIdDefined in tls-2.4.9 · Network.TLS.Types.Cipher
EnumSessionFlagDefined in tls-2.4.9 · Network.TLS.Types.Session
EnumStatxFlagsDefined in unix-2.8.8.0 · System.Posix.Files.Common
EnumStatxMaskDefined in unix-2.8.8.0 · System.Posix.Files.Common
EnumBaudRateDefined in unix-2.8.8.0 · System.Posix.Terminal.Common
Enum (Fixeda)Defined in base-4.23.0.0 · Data.Fixed
Recall that, for numeric types, succ and pred typically add and subtract
1, respectively. This is not true in the case of Fixed, whose successor
and predecessor functions intuitively return the "next" and "previous" values
in the enumeration. The results of these functions thus depend on the
resolution of the Fixed value. For example, when enumerating values of
resolution 10^-3 of type Milli = Fixed E3,
Example1 expression
>>> succ (0.000 :: Milli)0.001
and likewise
Example1 expression
>>> pred (0.000 :: Milli)-0.001
In other words, succ and pred increment and decrement a fixed-precision
value by the least amount such that the value's resolution is unchanged.
For example, 10^-12 is the smallest (positive) amount that can be added to
a value of type Pico = Fixed E12 without changing its resolution, and so
Example1 expression
>>> succ (0.000000000000 :: Pico)0.000000000001
and similarly
Example1 expression
>>> pred (0.000000000000 :: Pico)-0.000000000001
This is worth bearing in mind when defining Fixed arithmetic sequences. In
particular, you may be forgiven for thinking the sequence
However, this is not true. On the contrary, similarly to the above
implementations of succ and pred, enumFromTo :: Pico -> Pico -> [Pico]
has a "step size" of 10^-12. Hence, the list [1..10] :: [Pico] has
the form
Any type that you wish to throw or catch as an exception must be an
instance of the Exception class. The simplest case is a new exception
type directly below the root:
data MyException = ThisException | ThatException
deriving Show
instance Exception MyException
The default method definitions in the Exception class do what we need
in this case. You can now throw and catch ThisException and
ThatException as exceptions:
*Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
Caught ThisException
In more complicated examples, you may wish to define a whole hierarchy
of exceptions:
---------------------------------------------------------------------
-- Make the root exception type for all the exceptions in a compiler
data SomeCompilerException = forall e . Exception e => SomeCompilerException e
instance Show SomeCompilerException where
show (SomeCompilerException e) = show e
instance Exception SomeCompilerException
compilerExceptionToException :: Exception e => e -> SomeException
compilerExceptionToException = toException . SomeCompilerException
compilerExceptionFromException :: Exception e => SomeException -> Maybe e
compilerExceptionFromException x = do
SomeCompilerException a <- fromException x
cast a
---------------------------------------------------------------------
-- Make a subhierarchy for exceptions in the frontend of the compiler
data SomeFrontendException = forall e . Exception e => SomeFrontendException e
instance Show SomeFrontendException where
show (SomeFrontendException e) = show e
instance Exception SomeFrontendException where
toException = compilerExceptionToException
fromException = compilerExceptionFromException
frontendExceptionToException :: Exception e => e -> SomeException
frontendExceptionToException = toException . SomeFrontendException
frontendExceptionFromException :: Exception e => SomeException -> Maybe e
frontendExceptionFromException x = do
SomeFrontendException a <- fromException x
cast a
---------------------------------------------------------------------
-- Make an exception type for a particular frontend compiler exception
data MismatchedParentheses = MismatchedParentheses
deriving Show
instance Exception MismatchedParentheses where
toException = frontendExceptionToException
fromException = frontendExceptionFromException
We can now catch a MismatchedParentheses exception as
MismatchedParentheses, SomeFrontendException or
SomeCompilerException, but not other types, e.g. IOException:
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
*** Exception: MismatchedParentheses
In most cases, the exception does not store its own ExceptionContext.
The default implementation of toException (which does not store any
ExceptionContext) is suitable for these cases.
In the rare case that the exception itself stores an ExceptionContext,
this context should be preserved by toException.
The SomeException type is the root of the exception type hierarchy.
When an exception of type e is thrown, behind the scenes it is
encapsulated in a SomeException.
Trigonometric and hyperbolic functions and related functions.
The Haskell Report defines no laws for Floating. However, (+), (*)
and exp are customarily expected to define an exponential field and have
the following properties:
A constant function, returning the lowest and highest values
that exponent x may assume for a normal x.
The relation to IEEE emin and emax is
floatRange x = (emin + 1, emax + 1).
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 ofdecodeFloat xis unspecified if either ofisNaN xorisInfinite xisTrue.
encodeFloat performs the inverse of decodeFloat in the
sense that for finite x with the exception of -0.0,
Prelude.uncurryencodeFloat (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.
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.
Instances18:=>, Class, RealFloat, …
RealFloatCDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
RealFloatCFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
RealFloatDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Float
RealFloatFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Float
RealFloatHalfDefined in half-0.3.3 · Numeric.Half.Internal
File and directory names are values of type String, whose precise
meaning is operating system dependent. Files can be opened, yielding a
handle which can then be used to operate on the contents of that file.
Three kinds of buffering are supported: line-buffering,
block-buffering or no-buffering. These modes have the following
effects. For output, items are written out, or flushed,
from the internal buffer according to the buffer mode:
line-buffering: the entire output buffer is flushed
whenever a newline is output, the buffer overflows,
a GHC.Internal.System.IO.hFlush is issued, or the handle is closed.
block-buffering: the entire buffer is written out whenever it
overflows, a GHC.Internal.System.IO.hFlush is issued, or the handle is closed.
no-buffering: output is written immediately, and never stored
in the buffer.
An implementation is free to flush the buffer more frequently,
but not less frequently, than specified above.
The output buffer is emptied as soon as it has been written out.
Similarly, input occurs according to the buffer mode for the handle:
line-buffering: when the buffer for the handle is not empty,
the next item is obtained from the buffer; otherwise, when the
buffer is empty, characters up to and including the next newline
character are read into the buffer. No characters are available
until the newline character is available or the buffer is full.
block-buffering: when the buffer for the handle becomes empty,
the next block of data is read into the buffer.
no-buffering: the next input item is read and returned.
The GHC.Internal.System.IO.hLookAhead operation implies that even a no-buffered
handle may require a one-character buffer.
The default buffering mode when a handle is opened is
implementation-dependent and may depend on the file system object
which is attached to that handle.
For most implementations, physical files will normally be block-buffered
and terminals will normally be line-buffered.
Haskell defines operations to read and write characters from and to files,
represented by values of type Handle. Each value of this type is a
handle: a record used by the Haskell run-time system to manage I/O
with file system objects. A handle has at least the following properties:
whether it manages input or output or both;
whether it is open, closed or semi-closed;
whether the object is seekable;
whether buffering is disabled, or enabled on a line or block basis;
a buffer (whose length may be zero).
Most handles will also have a current I/O position indicating where the next
input or output operation will occur. A handle is readable if it
manages only input or both input and output; likewise, it is writable if
it manages only output or both input and output. A handle is open when
first allocated.
Once it is closed it can no longer be used for either input or output,
though an implementation cannot re-use its storage while references
remain to it. Handles are in the Show and Eq classes. The string
produced by showing a handle is system dependent; it should include
enough information to identify the handle for debugging. A handle is
equal according to == only to itself; no attempt
is made to compare the internal state of different handles for equality.
The fromListN function takes the input list's length and potentially
uses it to construct the structure l more efficiently compared to
fromList. If the given number does not equal to the input list's length
the behaviour of fromListN is not specified.
An MVar (pronounced "em-var") is a synchronising variable, used
for communication between concurrent threads. It can be thought of
as a box, which may be empty or full.
Instances4NFData1, Eq, Data, NFData
NFData1MVarDefined in deepseq-1.5.2.0 · Control.DeepSeq
Eq (MVara)Defined in ghc-internal-10.0.0 · GHC.Internal.MVar
Compares the underlying pointers.
Typeablea => Data (MVara)Defined in syb-0.7.4 · Data.Generics.Instances · orphan
NFData (MVara)Defined in deepseq-1.5.2.0 · Control.DeepSeq
NOTE: Only strict in the reference and not the referenced value.
Note that it isn't customarily expected that a type instance of both Num
and Ord implement an ordered ring. Indeed, in base only Integer and
Data.Ratio.Rational do.
Conversion from an Integer.
An integer literal represents the application of the function
fromInteger to the appropriate value of type Integer,
so such literals have type (Num a) => a.
Instances179:=>, Class, Num, …
NumOrdADefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Poly
NumOrdBDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Poly
NumOrdCDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Poly
NumAdjacencyIntMapDefined in algebraic-graphs-0.8 · Algebra.Graph.AdjacencyIntMap
Note: this does not satisfy the usual ring laws; see AdjacencyIntMap
for more details.
NumPosDefined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
NumNumberDefined in attoparsec-0.14.4 · Data.Attoparsec.Number
NumWord128Defined in basement-0.0.16 · Basement.Types.Word128
NumWord256Defined in basement-0.0.16 · Basement.Types.Word256
NumPublicNumberDefined in cryptonite-0.30 · Crypto.PubKey.DH
NumIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Num
NumNaturalDefined in ghc-internal-10.0.0 · GHC.Internal.Num
Note that Natural's Num instance isn't a ring: no element but 0 has an
additive inverse. It is a semiring though.
NumEventTypeDefined in ghc-internal-10.0.0 · GHC.Internal.Event.EPoll
NumEventDefined in ghc-internal-10.0.0 · GHC.Internal.Event.Poll
NumUniqueDefined in ghc-internal-10.0.0 · GHC.Internal.Event.Unique
NumCBoolDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCCharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCClockDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCIntDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCIntMaxDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCIntPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCLLongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCLongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCPtrdiffDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCSCharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCSUSecondsDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCShortDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCSigAtomicDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCSizeDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCTimeDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCUCharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCUIntDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCUIntMaxDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCUIntPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCULLongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCULongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCUSecondsDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCUShortDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumCWcharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
NumIntPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.Ptr
NumWordPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.Ptr
NumHalfWordDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.InfoTable.Types
NumInt16Defined in ghc-internal-10.0.0 · GHC.Internal.Int
NumInt32Defined in ghc-internal-10.0.0 · GHC.Internal.Int
NumInt64Defined in ghc-internal-10.0.0 · GHC.Internal.Int
NumInt8Defined in ghc-internal-10.0.0 · GHC.Internal.Int
NumByteOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.Constants
NumWordOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.Constants
NumByteOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.ConstantsProf
NumWordOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.ConstantsProf
NumCBlkCntDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCBlkSizeDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCCcDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCClockIdDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCDevDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCFsBlkCntDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCFsFilCntDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCGidDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCIdDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCInoDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCKeyDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCModeDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCNfdsDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCNlinkDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCOffDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCPidDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCRLimDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCSocklenDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCSpeedDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCSsizeDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCTcflagDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumCUidDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumFdDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
NumDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
NumFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
NumInferStateDefined in hnix-0.17.0 · Nix.Type.Infer
NumSecondsDefined in hspec-core-2.11.18 · Test.Hspec.Core.Clock
NumMaxHeaderLengthDefined in http-client-0.7.19 · Network.HTTP.Client.Types
NumMaxNumberHeadersDefined in http-client-0.7.19 · Network.HTTP.Client.Types
NumMsgFlagDefined in network-3.2.9.0 · Network.Socket.Flag
NumPortNumberDefined in network-3.2.9.0 · Network.Socket.Types
NumCardinalityDefined in random-1.3.1 · System.Random.GFinite
NumScientificDefined in scientific-0.3.9.0 · Data.Scientific
WARNING:+ and - compute the Integer magnitude: 10^e where e is
the difference between the base10Exponents of the arguments. If these
methods are applied to arguments which have huge exponents this could fill up
all space and crash your program! So don't apply these methods to scientific
numbers coming from untrusted sources. The other methods can be used safely.
NumCodePointDefined in streaming-commons-0.2.3.1 · Data.Streaming.Text
NumDecoderStateDefined in streaming-commons-0.2.3.1 · Data.Streaming.Text
(Applicativef, Numa) => Num (Apfa)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
Note that even if the underlying Num and Applicative instances are
lawful, for most Applicatives, this instance will not be lawful. If you use
this instance with the list Applicative, the following customary laws will
not hold:
Commutativity:
Example2 expressions
>>> Ap [10,20] + Ap [1,2]Ap {getAp = [11,12,21,22]}>>> Ap [1,2] + Ap [10,20]Ap {getAp = [11,21,12,22]}
Additive inverse:
Example2 expressions
>>> Ap [] + negate (Ap [])Ap {getAp = []}>>> fromInteger 0 :: Ap [] IntAp {getAp = [0]}
Distributivity:
Example2 expressions
>>> Ap [1,2] * (3 + 4)Ap {getAp = [7,14]}>>> (Ap [1,2] * 3) + (Ap [1,2] * 4)Ap {getAp = [7,11,10,14]}
Num (f (ga)) => Num (Composefga)Defined in base-4.23.0.0 · Data.Functor.Compose
Derived instances of Read make the following assumptions, which
derived instances of Text.Show.Show obey:
If the constructor is defined to be an infix operator, then the
derived Read instance will parse only infix applications of
the constructor (not the prefix form).
Associativity is not used to reduce the occurrence of parentheses,
although precedence may be.
If the constructor is defined using record syntax, the derived Read
will parse only the record-syntax form, and furthermore, the fields
must be given in the same order as the original declaration.
The derived Read instance allows arbitrary Haskell whitespace
between tokens of the input string. Extra parentheses are also
allowed.
For example, given the declarations
infixr 5 :^:
data Tree a = Leaf a | Tree a :^: Tree a
the derived instance of Read in Haskell 2010 is equivalent to
instance (Read a) => Read (Tree a) where
readsPrec d r = readParen (d > app_prec)
(\r -> [(Leaf m,t) |
("Leaf",s) <- lex r,
(m,t) <- readsPrec (app_prec+1) s]) r
++ readParen (d > up_prec)
(\r -> [(u:^:v,w) |
(u,s) <- readsPrec (up_prec+1) r,
(":^:",t) <- lex s,
(v,w) <- readsPrec (up_prec+1) t]) r
where app_prec = 10
up_prec = 5
Note that right-associativity of :^: is unused.
The derived instance in GHC is equivalent to
instance (Read a) => Read (Tree a) where
readPrec = parens $ (prec app_prec $ do
Ident "Leaf" <- lexP
m <- step readPrec
return (Leaf m))
+++ (prec up_prec $ do
u <- step readPrec
Symbol ":^:" <- lexP
v <- step readPrec
return (u :^: v))
where app_prec = 10
up_prec = 5
readListPrec = readListPrecDefault
Why do both readsPrec and readPrec exist, and why does GHC opt to
implement readPrec in derived Read instances instead of readsPrec?
The reason is that readsPrec is based on the ReadS type, and although
ReadS is mentioned in the Haskell 2010 Report, it is not a very efficient
parser data structure.
readPrec, on the other hand, is based on a much more efficient ReadPrec
datatype (a.k.a "new-style parsers"), but its definition relies on the use
of the RankNTypes language extension. Therefore, readPrec (and its
cousin, readListPrec) are marked as GHC-only. Nevertheless, it is
recommended to use readPrec instead of readsPrec whenever possible
for the efficiency improvements it brings.
As mentioned above, derived Read instances in GHC will implement
readPrec instead of readsPrec. The default implementations of
readsPrec (and its cousin, readList) will simply use readPrec under
the hood. If you are writing a Read instance by hand, it is recommended
to write it like so:
ReadTextDefined in text-2.1.4 · Data.Text · orphan
ReadTextDefined in text-2.1.4 · Data.Text.Lazy · orphan
ReadFPFormatDefined in text-2.1.4 · Data.Text.Lazy.Builder.RealFloat
ReadShortTextDefined in text-short-0.1.6.1 · Data.Text.Short.Internal
ReadDatatypeVariantDefined in th-abstraction-0.7.2.0 · Language.Haskell.TH.Datatype
ReadCalendarDiffDaysDefined in time-1.16.0.1 · Data.Time.Format.ISO8601 · orphan
ReadDayDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
ReadMonthDefined in time-1.16.0.1 · Data.Time.Calendar.Month
Read as yyyy-mm.
ReadQuarterDefined in time-1.16.0.1 · Data.Time.Calendar.Quarter
Read as yyyy-Qn.
ReadQuarterOfYearDefined in time-1.16.0.1 · Data.Time.Calendar.Quarter
ReadDayOfWeekDefined in time-1.16.0.1 · Data.Time.Calendar.Week
ReadDiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
ReadNominalDiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.NominalDiffTime
ReadUTCTimeDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
ReadUniversalTimeDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
ReadCalendarDiffTimeDefined in time-1.16.0.1 · Data.Time.Format.ISO8601 · orphan
ReadLocalTimeDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
ReadTimeOfDayDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
ReadTimeZoneDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
This only works for ±HHMM format,
single-letter military time-zones,
and these time-zones: "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
per RFC 822 section 5.
ReadZonedTimeDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
This only works for a zonedTimeZone in ±HHMM format,
single-letter military time-zones,
and these time-zones: "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT",
per RFC 822 section 5.
ReadDurationDefined in time-hourglass-0.3.0 · Time.Diff
ReadPeriodDefined in time-hourglass-0.3.0 · Time.Diff
ReadDateDefined in time-hourglass-0.3.0 · Time.Types
ReadDateTimeDefined in time-hourglass-0.3.0 · Time.Types
ReadElapsedDefined in time-hourglass-0.3.0 · Time.Types
ReadElapsedPDefined in time-hourglass-0.3.0 · Time.Types
ReadHoursDefined in time-hourglass-0.3.0 · Time.Types
ReadMinutesDefined in time-hourglass-0.3.0 · Time.Types
ReadMonthDefined in time-hourglass-0.3.0 · Time.Types
The Haskell Report defines no laws for Fractional. However, (+) and
(*) are customarily expected to define a division ring and have the
following properties:
These methods also compute Integer magnitudes (10^e). If these methods
are applied to arguments which have huge exponents this could fill up all
space and crash your program! So don't apply these methods to scientific
numbers coming from untrusted sources.
fromRational will throw an error when the input Rational is a repeating
decimal. Consider using fromRationalRepetend for these rationals which
will detect the repetition and indicate where it starts.
FractionalDiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
The Haskell Report defines no laws for Integral. However, Integral
instances are customarily expected to define a Euclidean domain and have the
following properties for the div/mod and quot/rem pairs, given
suitable Euclidean functions f and g:
x = y * quot x y + rem x y with rem x y = fromInteger 0 or
g (rem x y) < g y
x = y * div x y + mod x y with mod x y = fromInteger 0 or
f (mod x y) < f y
An example of a suitable Euclidean function, for Integer's instance, is
abs.
In addition, toInteger should be total, and fromInteger should be a left
inverse for it, i.e. fromInteger (toInteger i) = i.
Rational numbers, with numerator and denominator of some Integral type.
Note that Ratio's instances inherit the deficiencies from the type
parameter's. For example, Ratio Natural's Num instance has similar
problems to Numeric.Natural.Natural's.
The law does not hold for Float, Double, CFloat,
CDouble, etc., because these types contain non-finite values,
which cannot be roundtripped through Rational.
RealScientificDefined in scientific-0.3.9.0 · Data.Scientific
WARNING:toRational needs to compute the Integer magnitude:
10^e. If applied to a huge exponent this could fill up all space
and crash your program!
Avoid applying toRational (or realToFrac) to scientific numbers
coming from an untrusted source and use toRealFloat instead. The
latter guards against excessive space usage.
WARNING: the methods of the RealFrac instance need to compute the
magnitude 10^e. If applied to a huge exponent this could take a long
time. Even worse, when the destination type is unbounded (i.e. Integer) it
could fill up all space and crash your program!
RealFracDiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
Derived instances of Show have the following properties, which
are compatible with derived instances of Text.Read.Read:
The result of show is a syntactically correct Haskell
expression containing only constants, given the fixity
declarations in force at the point where the type is declared.
It contains only the constructor names defined in the data type,
parentheses, and spaces. When labelled constructor fields are
used, braces, commas, field names, and equal signs are also used.
If the constructor is defined to be an infix operator, then
showsPrec will produce infix applications of the constructor.
the representation will be enclosed in parentheses if the
precedence of the top-level constructor in x is less than d
(associativity is ignored). Thus, if d is 0 then the result
is never surrounded in parentheses; if d is 11 it is always
surrounded in parentheses, unless it is an atomic expression.
If the constructor is defined using record syntax, then show
will produce the record-syntax form, with the fields given in the
same order as the original declaration.
For example, given the declarations
infixr 5 :^:
data Tree a = Leaf a | Tree a :^: Tree a
instance (Show a) => Show (Tree a) where
showsPrec d (Leaf m) = showParen (d > app_prec) $
showString "Leaf " . showsPrec (app_prec+1) m
where app_prec = 10
showsPrec d (u :^: v) = showParen (d > up_prec) $
showsPrec (up_prec+1) u .
showString " :^: " .
showsPrec (up_prec+1) v
where up_prec = 5
Note that right-associativity of :^: is ignored. For example,
show (Leaf 1 :^: Leaf 2 :^: Leaf 3) produces the string
"Leaf 1 :^: (Leaf 2 :^: Leaf 3)".
as a variant of putStrLn that will get its call-site and print it,
along with the string given as argument. We can access the
call-stack inside putStrLnWithCallStack with callStack.
Thus, if we call putStrLnWithCallStack we will get a formatted call-stack
alongside our string.
Example1 expression
>>> putStrLnWithCallStack "hello"helloCallStack (from HasCallStack): putStrLnWithCallStack, called at <interactive>:... in interactive:Ghci...
GHC solves HasCallStack constraints in three steps:
If there is a CallStack in scope -- i.e. the enclosing function
has a HasCallStack constraint -- GHC will append the new
call-site to the existing CallStack.
If there is no CallStack in scope -- e.g. in the GHCi session
above -- and the enclosing definition does not have an explicit
type signature, GHC will infer a HasCallStack constraint for the
enclosing definition (subject to the monomorphism restriction).
If there is no CallStack in scope and the enclosing definition
has an explicit type signature, GHC will solve the HasCallStack
constraint for the singleton CallStack containing just the
current call-site.
CallStacks do not interact with the RTS and do not require compilation
with -prof. On the other hand, as they are built up explicitly via the
HasCallStack constraints, they will generally not contain as much
information as the simulated call-stacks maintained by the RTS.
A CallStack is a [(String, SrcLoc)]. The String is the name of
function that was called, the SrcLoc is the call-site. The list is
ordered with the most recently called function at the head.
NOTE: The intrepid user may notice that HasCallStack is just an
alias for an implicit parameter ?callStack :: CallStack. This is an
implementation detail and should not be considered part of the
CallStack API, we may decide to change the implementation in the
future.
Instances4IsList, Show, NFData, Item
IsListCallStackDefined in ghc-internal-10.0.0 · GHC.Internal.IsList
Be aware that 'fromList . toList = id' only for unfrozen CallStacks,
since toList removes frozenness information.
ShowCallStackDefined in ghc-internal-10.0.0 · GHC.Internal.Show
NOTE: The implicit parameter ?callStack :: CallStack is an
implementation detail and should not be considered part of the
CallStack API, we may decide to change the implementation in the
future.
A value of type IO a is a computation which, when performed,
does some I/O before returning a value of type a.
There is really only one way to "perform" an I/O action: bind it to
Main.main in your program. When your program is run, the I/O will
be performed. It isn't possible to perform I/O from an arbitrary
function, unless that function is itself in the IO monad and called
at some point, directly or indirectly, from Main.main.
IO is a monad, so IO actions can be combined using either the do-notation
or the Prelude.>> and Prelude.>>= operations from the Prelude.Monad
class.
Hashable is intended exclusively for use in in-memory data structures.
.
Hashable does not have a fixed standard.
This allows it to improve over time.
.
Because it does not have a fixed standard, different computers or computers on different versions of the code will observe different hash values.
As such, Hashable is not recommended for use other than in-memory datastructures.
Specifically, Hashable is not intended for network use or in applications which persist hashed values.
For stable hashing use named hashes: sha256, crc32, xxhash etc.
If two values are equal according to the == method, then
applying the hashWithSalt method on each of the two values
must produce the same integer result if the same salt is
used in each case.
It is not required that if two values are unequal
according to the == method, then applying the
hashWithSalt method on each of the two values must produce
distinct integer results. However, the programmer should be
aware that producing distinct integer results for unequal
values may improve the performance of hashing-based data
structures.
This method can be used to compute different hash values for
the same input by providing a different salt in each
application of the method. This implies that any instance
that defines hashWithSaltmust make use of the salt in
its implementation.
A hash can be safely calculated from a Scientific. No magnitude 10^e is
calculated so there's no risk of a blowup in space or time when hashing
scientific numbers coming from untrusted sources.
Example4 expressions
>>> import Data.Hashable (hash)>>> let x = scientific 1 2>>> let y = scientific 100 0>>> (x == y, hash x == hash y)(True,True)
HashableTextDefined in hashable-1.5.1.0 · Data.Hashable.Class
HashableTextDefined in hashable-1.5.1.0 · Data.Hashable.Class
HashableShortTextDefined in text-short-0.1.6.1 · Data.Text.Short.Internal
HashableDayDefined in time-compat-1.9.9 · Data.Time.Orphans · orphan
HashableMonthDefined in time-compat-1.9.9 · Data.Time.Orphans · orphan
HashableQuarterDefined in time-compat-1.9.9 · Data.Time.Orphans · orphan
EncodingErrorToLText"ByteString""LText" => ToLTextByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toLText ("some string" :: ByteString)...... Type 'ByteString' doesn't have instance of 'ToLText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ByteString -> LText decodeUtf8Strict :: ByteString -> Either UnicodeException LText...
EncodingErrorToLText"LByteString""LText" => ToLTextLByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toLText ("some string" :: LByteString)...... Type 'LByteString' doesn't have instance of 'ToLText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: LByteString -> LText decodeUtf8Strict :: LByteString -> Either UnicodeException LText...
EncodingErrorToLText"ShortByteString""LText" => ToLTextShortByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toLText ("some string" :: ShortByteString)...... Type 'ShortByteString' doesn't have instance of 'ToLText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ShortByteString -> LText decodeUtf8Strict :: ShortByteString -> Either UnicodeException LText...
ToLTextStringDefined in relude-1.2.2.2 · Relude.String.Conversion
ToLTextTextDefined in relude-1.2.2.2 · Relude.String.Conversion
ToLTextTextDefined in relude-1.2.2.2 · Relude.String.Conversion
EncodingErrorToString"ByteString""String" => ToStringByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toString ("some string" :: ByteString)...... Type 'ByteString' doesn't have instance of 'ToString'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ByteString -> String decodeUtf8Strict :: ByteString -> Either UnicodeException String...
EncodingErrorToString"LByteString""String" => ToStringLByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toString ("some string" :: LByteString)...... Type 'LByteString' doesn't have instance of 'ToString'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: LByteString -> String decodeUtf8Strict :: LByteString -> Either UnicodeException String...
EncodingErrorToString"ShortByteString""String" => ToStringShortByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toString ("some string" :: ShortByteString)...... Type 'ShortByteString' doesn't have instance of 'ToString'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ShortByteString -> String decodeUtf8Strict :: ShortByteString -> Either UnicodeException String...
ToStringStringDefined in relude-1.2.2.2 · Relude.String.Conversion
EncodingErrorToText"ByteString""Text" => ToTextByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toText ("some string" :: ByteString)...... Type 'ByteString' doesn't have instance of 'ToText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ByteString -> Text decodeUtf8Strict :: ByteString -> Either UnicodeException Text...
EncodingErrorToText"LByteString""Text" => ToTextLByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toText ("some string" :: LByteString)...... Type 'LByteString' doesn't have instance of 'ToText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: LByteString -> Text decodeUtf8Strict :: LByteString -> Either UnicodeException Text...
EncodingErrorToText"ShortByteString""Text" => ToTextShortByteStringDefined in relude-1.2.2.2 · Relude.String.Conversion
⚠️CAUTION⚠️ This instance is for custom error display only.
You should always specify encoding of bytes explicitly.
In case it is used by mistake, the user will see the following:
Example1 expression
>>> toText ("some string" :: ShortByteString)...... Type 'ShortByteString' doesn't have instance of 'ToText'. Use 'decodeUtf8' or 'decodeUtf8Strict' to convert from UTF-8: decodeUtf8 :: ShortByteString -> Text decodeUtf8Strict :: ShortByteString -> Either UnicodeException Text...
ToTextStringDefined in relude-1.2.2.2 · Relude.String.Conversion
The input value that caused the error. If the error arose
because the end of input was reached or could not be identified
precisely, this value will be Nothing.
If the handler returns a value wrapped with Just, that value will
be used in the output as the replacement for the invalid input. If
it returns Nothing, no value will be used in the output.
Should the handler need to abort processing, it should use error
or throw an exception (preferably a UnicodeException). It may
use the description provided to construct a more helpful error
report.
DataTextDefined in text-2.1.4 · Data.Text · orphan
This instance preserves data abstraction at the cost of inefficiency.
We omit reflection services for the sake of data abstraction.
This instance was created by copying the updated behavior of
Data.Set.Set and Data.Map.Data.Map.Map. If you
feel a mistake has been made, please feel free to submit
improvements.
The class of monad transformers.
For any monad m, the result t m should also be a monad,
and lift should be a monad transformation from m to t m,
i.e. it should satisfy the following laws:
Since 0.6.0.0 and for GHC 8.6 and later, the requirement that t m
be a Monad is enforced by the implication constraint
forall m. Monad m => Monad (t m) enabled by the
QuantifiedConstraints extension.
'Extends' the possibilities considered by m to include every value of
e; this means that the potential result could be either a Left (making it
a choice of type e) or a Right (making it a choice of type a).
'Extends' the possibilities considered by m to include Nothing; this
means that Nothing gains a 'rank' (namely, a value of r), and the
potential result could also be Nothing.
Provides a read-only environment of type r to the 'strategy' function.
However, the 'ranking' function (or more accurately, representation) has no
access to r. Put another way, you can influence what values get chosen by
changing r, but not how solutions are ranked.
'Readerizes' the state: the 'ranking' function can see a value of
type s, but not modify it. Effectively, can be thought of as 'extending'
the 'ranking' by all values in s, but whichs gets given to any rank
calls is predetermined by the 'outer state' (and cannot change).
(Ordk, Ordv) => Ord (HashMapkv)Defined in unordered-containers-0.2.21 · Data.HashMap.Internal
The ordering is total and consistent with the Eq instance. However,
nothing else about the ordering is specified, and it may change from
version to version of either this package or of hashable.
String constants in Haskell are values of type String.
That means if you write a string literal like "hello world",
it will have the type [Char], which is the same as String.
Note: You can ask the compiler to automatically infer different types
with the -XOverloadedStrings language extension, for example
"hello world" :: Text. See IsString for more information.
Because String is just a list of characters, you can use normal list functions
to do basic string manipulation. See Data.List for operations on lists.
Performance considerations
[Char] is a relatively memory-inefficient type.
It is a linked list of boxed word-size characters, internally it looks something like:
╭─────┬───┬──╮ ╭─────┬───┬──╮ ╭─────┬───┬──╮ ╭────╮
│ (:) │ │ ─┼─>│ (:) │ │ ─┼─>│ (:) │ │ ─┼─>│ [] │
╰─────┴─┼─┴──╯ ╰─────┴─┼─┴──╯ ╰─────┴─┼─┴──╯ ╰────╯
v v v
'a' 'b' 'c'
The String "abc" will use 5*3+1 = 16 (in general 5n+1)
words of space in memory.
Furthermore, operations like (++) (string concatenation) are O(n)
(in the left argument).
For historical reasons, the base library uses String in a lot of places
for the conceptual simplicity, but library code dealing with user-data
should use the text
package for Unicode text, or the the
bytestring package
for binary data.
Arbitrary precision integers. In contrast with fixed-size integral types
such as Int, the Integer type represents the entire infinite range of
integers.
Integers are stored in a kind of sign-magnitude form, hence do not expect
two's complement form when using bit operations.
If the value is small (i.e., fits into an Int), the IS constructor is
used. Otherwise IP and IN constructors are used to store a BigNat
representing the positive or the negative value magnitude, respectively.
Invariant: IP and IN are used iff the value does not fit in IS.
Instances66Enum, Eq, Data, Num, Ord, Read, …
EnumIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Enum
EqIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Bignum.Integer
IntegralIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Real
DataIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Data
NumIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Num
OrdIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Bignum.Integer
ReadIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Read
RealIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Real
ShowIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Show
IxIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Ix
BitsIntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Bits
ArbitraryIntegerDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
CoArbitraryIntegerDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
FunctionIntegerDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Function
BinaryIntegerDefined in binary-0.8.9.3 · Data.Binary.Class
HashableIntegerDefined in hashable-1.5.1.0 · Data.Hashable.Class
DayPeriodYearDefined in time-1.16.0.1 · Data.Time.Calendar.Gregorian · orphan
ShowPaddedIntegerDefined in time-1.16.0.1 · Data.Time.Calendar.Private
ShowPaddedIntegerDefined in time-compat-1.9.9 · Data.Time.Calendar.Private
FromJSONIntegerDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON
This instance includes a bounds check to prevent maliciously
large inputs to fill up the memory of the target system. You can
newtype Scientific and provide your own instance using
withScientific if you want to allow larger inputs.
The Maybe type encapsulates an optional value. A value of type
Maybe a either contains a value of type a (represented as Just a),
or it is empty (represented as Nothing). Using Maybe is a good way to
deal with errors or exceptional cases without resorting to drastic
measures such as error.
The Maybe type is also a monad. It is a simple kind of error
monad, where all errors are represented by Nothing. A richer
error monad can be built using the Either type.
Lift a semigroup into Maybe forming a Monoid according to
http://en.wikipedia.org/wiki/Monoid: "Any semigroup S may be
turned into a monoid simply by adjoining an element e not in S
and defining e*e = e and e*s = s = s*e for all s ∈ S."
Since 4.11.0: constraint on inner a value generalised from
Monoid to Semigroup.
SingKinda => SingKind (Maybea)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
NFDataa => NFData (Maybea)Defined in deepseq-1.5.2.0 · Control.DeepSeq
Prettya => Pretty (Maybea)Defined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJClass
Prettya => Pretty (Maybea)Defined in pretty-1.1.3.6 · Text.PrettyPrint.HughesPJClass
Finitea => Finite (Maybea)Defined in random-1.3.1 · System.Random.GFinite
Character literals in Haskell are single-quoted: 'Q', 'Я' or 'Ω'.
To represent a single quote itself use '\'', and to represent a backslash
use '\\'. The full grammar can be found in the section 2.6 of the
Haskell 2010 Language Report.
To specify a character by its code point one can use decimal, hexadecimal
or octal notation: '\65', '\x41' and '\o101' are all alternative forms
of 'A'. The largest code point is '\x10ffff'.
There is a special escape syntax for ASCII control characters:
Coercible is a two-parameter class that has instances for types a and b if
the compiler can infer that they have the same representation. This class
does not have regular instances; instead they are created on-the-fly during
type-checking. Trying to manually declare an instance of Coercible
is an error.
Nevertheless one can pretend that the following three kinds of instances
exist. First, as a trivial base-case:
instance Coercible a a
Furthermore, for every type constructor there is
an instance that allows to coerce under the type constructor. For
example, let D be a prototypical type constructor (data or
newtype) with three type arguments, which have roles nominal,
representational resp. phantom. Then there is an instance of
the form
instance Coercible b b' => Coercible (D a b c) (D a b' c')
Note that the nominal type arguments are equal, the
representational type arguments can differ, but need to have a
Coercible instance themself, and the phantom type arguments can be
changed arbitrarily.
The third kind of instance exists for every newtype NT = MkNT T and
comes in two variants, namely
instance Coercible a T => Coercible a NT
instance Coercible T b => Coercible NT b
This instance is only usable if the constructor MkNT is in scope.
If, as a library author of a type constructor like Set a, you
want to prevent a user of your module to write
coerce :: Set T -> Set NT,
you need to set the role of Set's type parameter to nominal,
by writing
type role Set nominal
For more details about this feature, please refer to
Safe Coercions
by Joachim Breitner, Richard A. Eisenberg, Simon Peyton Jones and Stephanie Weirich.
DataDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Data
NumDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
OrdDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
IEEE 754 Double-precision type includes not only numbers, but also
positive and negative infinities and a special element called NaN
(which can be quiet or signal).
IEEE 754-2008, section 5.11 requires that if at least one of arguments of
<=, <, >, >= is NaN then the result of the comparison is False,
and instanceOrdDouble complies with this requirement. This violates
the reflexivity: both NaN<=NaN and NaN>=NaN are False.
IEEE 754-2008, section 5.10 defines totalOrder predicate. Unfortunately,
compare on Doubles violates the IEEE standard and does not define a total order.
More specifically, both compareNaNx and comparexNaN always return GT.
Thus, users must be extremely cautious when using instanceOrdDouble.
For instance, one should avoid ordered containers with keys represented by Double,
because data loss and corruption may happen. An IEEE-compliant compare is available
in fp-ieee package as TotallyOrdered newtype.
Moving further, the behaviour of min and max with regards to NaN is
also non-compliant. IEEE 754-2008, section 5.3.1 defines that quiet NaN
should be treated as a missing data by minNum and maxNum functions,
for example, minNum(NaN, 1) = minNum(1, NaN) = 1. Some languages such as Java
deviate from the standard implementing minNum(NaN, 1) = minNum(1, NaN) = NaN.
However, min / max in base are even worse: minNaN 1 is 1, but min 1 NaN
is NaN.
IEEE 754-2008 compliant min / max can be found in ieee754 package under
minNum / maxNum names. Implementations compliant with
minimumNumber / maximumNumber from a newer
IEEE 754-2019,
section 9.6 are available from fp-ieee package.
ReadDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Read
RealDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Float · orphan
RealFloatDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Float
RealFracDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Float · orphan
Beware that results for non-finite arguments are garbage:
Example2 expressions
>>> [ f x | f <- [round, floor, ceiling], x <- [-1/0, 0/0, 1/0] ] :: [Int][0,0,0,0,0,0,0,0,0]>>> map properFraction [-1/0, 0/0, 1/0] :: [(Int, Double)][(0,0.0),(0,0.0),(0,0.0)]
and get even more non-sensical if you ask for Integer instead of Int.
ShowDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Float · orphan
StorableDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.Storable
DataFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Data
NumFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Float · orphan
This instance implements IEEE 754 standard with all its usual pitfalls
about NaN, infinities and negative zero.
Neither addition nor multiplication are associative or distributive:
A fixed-precision integer type with at least the range [-2^29 .. 2^29-1].
The exact range for a given implementation can be determined by using
Prelude.minBound and Prelude.maxBound from the Prelude.Bounded class.
Lifted, homogeneous equality. By lifted, we mean that it
can be bogus (deferred type error). By homogeneous, the two
types a and b must have the same kinds.