Safe Haskell | None |
---|---|
Language | Haskell2010 |
Synopsis
- (&) :: a -> (a -> b) -> b
- (&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')
- (<&>) :: Functor f => f a -> (a -> b) -> f b
- toList :: Foldable t => t a -> [a]
- bool :: a -> a -> Bool -> a
- first :: Bifunctor p => (a -> b) -> p a c -> p b c
- second :: Bifunctor p => (b -> c) -> p a b -> p a c
- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
- isNothing :: Maybe a -> Bool
- isJust :: Maybe a -> Bool
- fromMaybe :: a -> Maybe a -> a
- guard :: Alternative f => Bool -> f ()
- foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b
- fold :: ( Foldable t, Monoid m) => t m -> m
- for :: ( Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
- throw :: forall (r :: RuntimeRep ) (a :: TYPE r) e. Exception e => e -> a
- join :: Monad m => m (m a) -> m a
- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
- ($>) :: Functor f => f a -> b -> f b
- fromRight :: b -> Either a b -> b
- isRight :: Either a b -> Bool
- void :: Functor f => f a -> f ()
- through :: Functor f => (a -> f b) -> a -> f a
- coerce :: forall (k :: RuntimeRep ) (a :: TYPE k) (b :: TYPE k). Coercible a b => a -> b
- class Generic a
- class NFData a
- data Natural
- data NonEmpty a = a :| [a]
- data Word8
- class Applicative f => Alternative (f :: Type -> Type ) where
- class ( Typeable e, Show e) => Exception e
-
newtype
PairT
b f a =
PairT
{
- unPairT :: f (b, a)
- class a ~R# b => Coercible (a :: k) (b :: k)
- class Typeable (a :: k)
- type Lens' s a = Lens s s a a
- lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b
- (^.) :: s -> Getting a s a -> a
- view :: MonadReader s m => Getting a s a -> m a
- (.~) :: ASetter s t a b -> b -> s -> t
- set :: ASetter s t a b -> b -> s -> t
- (%~) :: ASetter s t a b -> (a -> b) -> s -> t
- over :: ASetter s t a b -> (a -> b) -> s -> t
- traceShowId :: Show a => a -> a
- trace :: String -> a -> a
- (.*) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
- (<<$>>) :: ( Functor f1, Functor f2) => (a -> b) -> f1 (f2 a) -> f1 (f2 b)
- (<<*>>) :: ( Applicative f1, Applicative f2) => f1 (f2 (a -> b)) -> f1 (f2 a) -> f1 (f2 b)
- mtraverse :: ( Monad m, Traversable m, Applicative f) => (a -> f (m b)) -> m a -> f (m b)
- foldMapM :: ( Foldable f, Monad m, Monoid b) => (a -> m b) -> f a -> m b
- reoption :: ( Foldable f, Alternative g) => f a -> g a
- enumeration :: ( Bounded a, Enum a) => [a]
- tabulateArray :: ( Bounded i, Enum i, Ix i) => (i -> a) -> Array i a
- (?) :: Alternative f => Bool -> a -> f a
- ensure :: Alternative f => (a -> Bool ) -> a -> f a
- asksM :: MonadReader r m => (r -> m a) -> m a
- data Doc ann
-
newtype
ShowPretty
a =
ShowPretty
{
- unShowPretty :: a
-
class
Pretty
a
where
- pretty :: a -> Doc ann
- prettyList :: [a] -> Doc ann
-
class
PrettyBy
config a
where
- prettyBy :: config -> a -> Doc ann
- prettyListBy :: config -> [a] -> Doc ann
- type family HasPrettyDefaults config :: Bool
- type PrettyDefaultBy config = DispatchPrettyDefaultBy ( NonStuckHasPrettyDefaults config) config
-
newtype
PrettyAny
a =
PrettyAny
{
- unPrettyAny :: a
- class Render str where
- display :: forall str a. ( Pretty a, Render str) => a -> str
- printPretty :: Pretty a => a -> IO ()
- showText :: Show a => a -> Text
Reexports from base
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c') infixr 3 Source #
Fanout: send the input to both argument arrows and combine their output.
The default definition may be overridden with a more efficient version if desired.
toList :: Foldable t => t a -> [a] Source #
List of elements of a structure, from left to right.
Since: base-4.8.0.0
bool :: a -> a -> Bool -> a Source #
Case analysis for the
Bool
type.
evaluates to
bool
x y p
x
when
p
is
False
, and evaluates to
y
when
p
is
True
.
This is equivalent to
if p then y else x
; that is, one can
think of it as an if-then-else construct with its arguments
reordered.
Examples
Basic usage:
>>>
bool "foo" "bar" True
"bar">>>
bool "foo" "bar" False
"foo"
Confirm that
and
bool
x y p
if p then y else x
are
equivalent:
>>>
let p = True; x = "bar"; y = "foo"
>>>
bool x y p == if p then y else x
True>>>
let p = False
>>>
bool x y p == if p then y else x
True
Since: base-4.7.0.0
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c infixl 0 Source #
fromMaybe :: a -> Maybe a -> a Source #
The
fromMaybe
function takes a default value and and
Maybe
value. If the
Maybe
is
Nothing
, it returns the default values;
otherwise, it returns the value contained in the
Maybe
.
Examples
Basic usage:
>>>
fromMaybe "" (Just "Hello, World!")
"Hello, World!"
>>>
fromMaybe "" Nothing
""
Read an integer from a string using
readMaybe
. If we fail to
parse an integer, we want to return
0
by default:
>>>
import Text.Read ( readMaybe )
>>>
fromMaybe 0 (readMaybe "5")
5>>>
fromMaybe 0 (readMaybe "")
0
guard :: Alternative f => Bool -> f () Source #
Conditional failure of
Alternative
computations. Defined by
guard True =pure
() guard False =empty
Examples
Common uses of
guard
include conditionally signaling an error in
an error monad and conditionally rejecting the current choice in an
Alternative
-based parser.
As an example of signaling 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
otherwise. For example:
Just
(x `div`
y)
>>> safeDiv 4 0 Nothing >>> safeDiv 4 2 Just 2
A definition of
safeDiv
using guards, but not
guard
:
safeDiv :: Int -> Int -> Maybe Int safeDiv x y | y /= 0 = Just (x `div` y) | otherwise = Nothing
A definition of
safeDiv
using
guard
and
Monad
do
-notation:
safeDiv :: Int -> Int -> Maybe Int safeDiv x y = do guard (y /= 0) return (x `div` y)
foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b Source #
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
list to a single, monolithic result (e.g.
length
).
For a general
Foldable
structure this should be semantically identical
to,
foldl' f z =foldl'
f z .toList
Since: base-4.6.0.0
fold :: ( Foldable t, Monoid m) => t m -> m Source #
Combine the elements of a structure using a monoid.
for :: ( Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) Source #
throw :: forall (r :: RuntimeRep ) (a :: TYPE r) e. Exception e => e -> a Source #
Throw an exception. Exceptions may be thrown from purely
functional code, but may only be caught within the
IO
monad.
join :: Monad m => m (m a) -> m a Source #
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.
'
' can be understood as the
join
bss
do
expression
do bs <- bss bs
Examples
A common use of
join
is to run an
IO
computation returned from
an
STM
transaction, since
STM
transactions
can't perform
IO
directly. Recall that
atomically
:: STM a -> IO a
is used to run
STM
transactions atomically. So, by
specializing the types of
atomically
and
join
to
atomically
:: STM (IO b) -> IO (IO b)join
:: IO (IO b) -> IO b
we can compose them as
join
.atomically
:: STM (IO b) -> IO b
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 Source #
Left-to-right composition of Kleisli arrows.
'
(bs
' can be understood as the
>=>
cs) a
do
expression
do b <- bs a cs b
($>) :: Functor f => f a -> b -> f b infixl 4 Source #
Flipped version of
<$
.
Using
ApplicativeDo
: '
as
' can be understood as the
$>
b
do
expression
do as pure b
with an inferred
Functor
constraint.
Examples
Replace the contents of a
with a constant
Maybe
Int
String
:
>>>
Nothing $> "foo"
Nothing>>>
Just 90210 $> "foo"
Just "foo"
Replace the contents of an
with a constant
Either
Int
Int
String
, resulting in an
:
Either
Int
String
>>>
Left 8675309 $> "foo"
Left 8675309>>>
Right 8675309 $> "foo"
Right "foo"
Replace each element of a list with a constant
String
:
>>>
[1,2,3] $> "foo"
["foo","foo","foo"]
Replace the second element of a pair with a constant
String
:
>>>
(1,2) $> "foo"
(1,"foo")
Since: base-4.7.0.0
fromRight :: b -> Either a b -> b Source #
Return the contents of a
Right
-value or a default value otherwise.
Examples
Basic usage:
>>>
fromRight 1 (Right 3)
3>>>
fromRight 1 (Left "foo")
1
Since: base-4.10.0.0
isRight :: Either a b -> Bool Source #
Return
True
if the given value is a
Right
-value,
False
otherwise.
Examples
Basic usage:
>>>
isRight (Left "foo")
False>>>
isRight (Right 3)
True
Assuming a
Left
value signifies some sort of error, we can use
isRight
to write a very simple reporting function that only
outputs "SUCCESS" when a computation has succeeded.
This example shows how
isRight
might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>
import Control.Monad ( when )
>>>
let report e = when (isRight e) $ putStrLn "SUCCESS"
>>>
report (Left "parse error")
>>>
report (Right 1)
SUCCESS
Since: base-4.7.0.0
void :: Functor f => f a -> f () Source #
discards or ignores the result of evaluation, such
as the return value of an
void
value
IO
action.
Using
ApplicativeDo
: '
' can be understood as the
void
as
do
expression
do as pure ()
with an inferred
Functor
constraint.
Examples
Replace the contents of a
with unit:
Maybe
Int
>>>
void Nothing
Nothing>>>
void (Just 3)
Just ()
Replace the contents of an
with unit, resulting in an
Either
Int
Int
:
Either
Int
()
>>>
void (Left 8675309)
Left 8675309>>>
void (Right 8675309)
Right ()
Replace every element of a list with unit:
>>>
void [1,2,3]
[(),(),()]
Replace the second element of a pair with unit:
>>>
void (1,2)
(1,())
Discard the result of an
IO
action:
>>>
mapM print [1,2]
1 2 [(),()]>>>
void $ mapM print [1,2]
1 2
through :: Functor f => (a -> f b) -> a -> f a Source #
Makes an effectful function ignore its result value and return its input value.
coerce :: forall (k :: RuntimeRep ) (a :: TYPE k) (b :: TYPE k). Coercible a b => a -> b Source #
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.
This function is runtime-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
.
Representable types of kind
*
.
This class is derivable in GHC with the
DeriveGeneric
flag on.
A
Generic
instance must satisfy the following laws:
from
.to
≡id
to
.from
≡id
Instances
A class of types that can be fully evaluated.
Since: deepseq-1.1.0.0
Instances
Type representing arbitrary-precision non-negative integers.
>>>
2^100 :: Natural
1267650600228229401496703205376
Operations whose result would be negative
,
throw
(
Underflow
::
ArithException
)
>>>
-1 :: Natural
*** Exception: arithmetic underflow
Since: base-4.8.0.0
Instances
Non-empty (and non-strict) list type.
Since: base-4.9.0.0
a :| [a] infixr 5 |
Instances
8-bit unsigned integer type
Instances
class Applicative f => Alternative (f :: Type -> Type ) where Source #
A monoid on applicative functors.
If defined,
some
and
many
should be the least solutions
of the equations:
The identity of
<|>
(<|>) :: f a -> f a -> f a infixl 3 Source #
An associative binary operation
One or more.
Zero or more.
Instances
class ( Typeable e, Show e) => Exception e Source #
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
Instances
class a ~R# b => Coercible (a :: k) (b :: k) Source #
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.
Since: ghc-prim-4.7.0.0
class Typeable (a :: k) Source #
The class
Typeable
allows a concrete representation of a type to
be calculated.
typeRep#
Lens
(^.) :: s -> Getting a s a -> a infixl 8 Source #
View the value pointed to by a
Getter
or
Lens
or the
result of folding over all the results of a
Fold
or
Traversal
that points at a monoidal values.
This is the same operation as
view
with the arguments flipped.
The fixity and semantics are such that subsequent field accesses can be
performed with (
.
).
>>>
(a,b)^._2
b
>>>
("hello","world")^._2
"world"
>>>
import Data.Complex
>>>
((0, 1 :+ 2), 3)^._1._2.to magnitude
2.23606797749979
(^.
) :: s ->Getter
s a -> a (^.
) ::Monoid
m => s ->Fold
s m -> m (^.
) :: s ->Iso'
s a -> a (^.
) :: s ->Lens'
s a -> a (^.
) ::Monoid
m => s ->Traversal'
s m -> m
view :: MonadReader s m => Getting a s a -> m a Source #
View the value pointed to by a
Getter
,
Iso
or
Lens
or the result of folding over all the results of a
Fold
or
Traversal
that points
at a monoidal value.
view
.
to
≡id
>>>
view (to f) a
f a
>>>
view _2 (1,"hello")
"hello"
>>>
view (to succ) 5
6
>>>
view (_2._1) ("hello",("world","!!!"))
"world"
As
view
is commonly used to access the target of a
Getter
or obtain a monoidal summary of the targets of a
Fold
,
It may be useful to think of it as having one of these more restricted signatures:
view
::Getter
s a -> s -> aview
::Monoid
m =>Fold
s m -> s -> mview
::Iso'
s a -> s -> aview
::Lens'
s a -> s -> aview
::Monoid
m =>Traversal'
s m -> s -> m
In a more general setting, such as when working with a
Monad
transformer stack you can use:
view
::MonadReader
s m =>Getter
s a -> m aview
:: (MonadReader
s m,Monoid
a) =>Fold
s a -> m aview
::MonadReader
s m =>Iso'
s a -> m aview
::MonadReader
s m =>Lens'
s a -> m aview
:: (MonadReader
s m,Monoid
a) =>Traversal'
s a -> m a
(.~) :: ASetter s t a b -> b -> s -> t infixr 4 Source #
Replace the target of a
Lens
or all of the targets of a
Setter
or
Traversal
with a constant value.
This is an infix version of
set
, provided for consistency with (
.=
).
f<$
a ≡mapped
.~
f$
a
>>>
(a,b,c,d) & _4 .~ e
(a,b,c,e)
>>>
(42,"world") & _1 .~ "hello"
("hello","world")
>>>
(a,b) & both .~ c
(c,c)
(.~
) ::Setter
s t a b -> b -> s -> t (.~
) ::Iso
s t a b -> b -> s -> t (.~
) ::Lens
s t a b -> b -> s -> t (.~
) ::Traversal
s t a b -> b -> s -> t
set :: ASetter s t a b -> b -> s -> t Source #
Replace the target of a
Lens
or all of the targets of a
Setter
or
Traversal
with a constant value.
(<$
) ≡set
mapped
>>>
set _2 "hello" (1,())
(1,"hello")
>>>
set mapped () [1,2,3,4]
[(),(),(),()]
Note: Attempting to
set
a
Fold
or
Getter
will fail at compile time with an
relatively nice error message.
set
::Setter
s t a b -> b -> s -> tset
::Iso
s t a b -> b -> s -> tset
::Lens
s t a b -> b -> s -> tset
::Traversal
s t a b -> b -> s -> t
(%~) :: ASetter s t a b -> (a -> b) -> s -> t infixr 4 Source #
Modifies the target of a
Lens
or all of the targets of a
Setter
or
Traversal
with a user supplied function.
This is an infix version of
over
.
fmap
f ≡mapped
%~
ffmapDefault
f ≡traverse
%~
f
>>>
(a,b,c) & _3 %~ f
(a,b,f c)
>>>
(a,b) & both %~ f
(f a,f b)
>>>
_2 %~ length $ (1,"hello")
(1,5)
>>>
traverse %~ f $ [a,b,c]
[f a,f b,f c]
>>>
traverse %~ even $ [1,2,3]
[False,True,False]
>>>
traverse.traverse %~ length $ [["hello","world"],["!!!"]]
[[5,5],[3]]
(%~
) ::Setter
s t a b -> (a -> b) -> s -> t (%~
) ::Iso
s t a b -> (a -> b) -> s -> t (%~
) ::Lens
s t a b -> (a -> b) -> s -> t (%~
) ::Traversal
s t a b -> (a -> b) -> s -> t
over :: ASetter s t a b -> (a -> b) -> s -> t Source #
Modify the target of a
Lens
or all the targets of a
Setter
or
Traversal
with a function.
fmap
≡over
mapped
fmapDefault
≡over
traverse
sets
.
over
≡id
over
.
sets
≡id
Given any valid
Setter
l
, you can also rely on the law:
over
l f.
over
l g =over
l (f.
g)
e.g.
>>>
over mapped f (over mapped g [a,b,c]) == over mapped (f . g) [a,b,c]
True
Another way to view
over
is to say that it transforms a
Setter
into a
"semantic editor combinator".
>>>
over mapped f (Just a)
Just (f a)
>>>
over mapped (*10) [1,2,3]
[10,20,30]
>>>
over _1 f (a,b)
(f a,b)
>>>
over _1 show (10,20)
("10",20)
over
::Setter
s t a b -> (a -> b) -> s -> tover
::ASetter
s t a b -> (a -> b) -> s -> t
Debugging
traceShowId :: Show a => a -> a Source #
Like
traceShow
but returns the shown value instead of a third value.
>>>
traceShowId (1+2+3, "hello" ++ "world")
(6,"helloworld") (6,"helloworld")
Since: base-4.7.0.0
trace :: String -> a -> a Source #
The
trace
function outputs the trace message given as its first argument,
before returning the second argument as its result.
For example, this returns the value of
f x
but first outputs the message.
>>>
let x = 123; f = show
>>>
trace ("calling f with x = " ++ show x) (f x)
"calling f with x = 123 123"
The
trace
function should
only
be used for debugging, or for monitoring
execution. The function is not referentially transparent: its type indicates
that it is a pure function but it has the side effect of outputting the
trace message.
Reexports from Control.Composition
Custom functions
(<<*>>) :: ( Applicative f1, Applicative f2) => f1 (f2 (a -> b)) -> f1 (f2 a) -> f1 (f2 b) infixl 4 Source #
mtraverse :: ( Monad m, Traversable m, Applicative f) => (a -> f (m b)) -> m a -> f (m b) Source #
reoption :: ( Foldable f, Alternative g) => f a -> g a Source #
This function generalizes
eitherToMaybe
,
eitherToList
,
listToMaybe
and other such functions.
enumeration :: ( Bounded a, Enum a) => [a] Source #
tabulateArray :: ( Bounded i, Enum i, Ix i) => (i -> a) -> Array i a Source #
Basically a
Data.Functor.Representable
instance for
Array
.
We can't provide an actual instance because of the
Distributive
superclass:
Array i
is not
Distributive
unless we assume that indices in an array range over the entirety of
i
.
(?) :: Alternative f => Bool -> a -> f a infixr 2 Source #
b ? x
is equal to
pure x
whenever
b
holds and is
empty
otherwise.
ensure :: Alternative f => (a -> Bool ) -> a -> f a Source #
ensure p x
is equal to
pure x
whenever
p x
holds and is
empty
otherwise.
asksM :: MonadReader r m => (r -> m a) -> m a Source #
A monadic version of
asks
.
Pretty-printing
The abstract data type
represents pretty documents that have
been annotated with data of type
Doc
ann
ann
.
More specifically, a value of type
represents a non-empty set of
possible layouts of a document. The layout functions select one of these
possibilities, taking into account things like the width of the output
document.
Doc
The annotation is an arbitrary piece of data associated with (part of) a document. Annotations may be used by the rendering backends in order to display output differently, such as
- color information (e.g. when rendering to the terminal)
- mouseover text (e.g. when rendering to rich HTML)
- whether to show something or not (to allow simple or detailed versions)
The simplest way to display a
Doc
is via the
Show
class.
>>>
putStrLn (show (vsep ["hello", "world"]))
hello world
Instances
newtype ShowPretty a Source #
A newtype wrapper around
a
whose point is to provide a
Show
instance
for anything that has a
Pretty
instance.
ShowPretty | |
|
Instances
Eq a => Eq ( ShowPretty a) Source # | |
Defined in PlutusPrelude (==) :: ShowPretty a -> ShowPretty a -> Bool Source # (/=) :: ShowPretty a -> ShowPretty a -> Bool Source # |
|
Pretty a => Show ( ShowPretty a) Source # | |
Defined in PlutusPrelude |
pretty :: a -> Doc ann Source #
>>>
pretty 1 <+> pretty "hello" <+> pretty 1.234
1 hello 1.234
prettyList :: [a] -> Doc ann Source #
is only used to define the
prettyList
instance
. In normal circumstances only the
Pretty
a =>
Pretty
[a]
function is used.
pretty
>>>
prettyList [1, 23, 456]
[1, 23, 456]
Instances
class PrettyBy config a where Source #
A class for pretty-printing values in a configurable manner.
A basic example:
>>>
data Case = UpperCase | LowerCase
>>>
data D = D
>>>
instance PrettyBy Case D where prettyBy UpperCase D = "D"; prettyBy LowerCase D = "d"
>>>
prettyBy UpperCase D
D>>>
prettyBy LowerCase D
d
The library provides instances for common types like
Integer
or
Bool
, so you can't define
your own
PrettyBy SomeConfig Integer
instance. And for the same reason you should not define
instances like
PrettyBy SomeAnotherConfig a
for universally quantified
a
, because such an
instance would overlap with the existing ones. Take for example
>>>
data ViaShow = ViaShow
>>>
instance Show a => PrettyBy ViaShow a where prettyBy ViaShow = pretty . show
with such an instance
prettyBy ViaShow (1 :: Int)
throws an error about overlapping instances:
• Overlapping instances for PrettyBy ViaShow Int arising from a use of ‘prettyBy’ Matching instances: instance PrettyDefaultBy config Int => PrettyBy config Int instance [safe] Show a => PrettyBy ViaShow a
There's a
newtype
provided specifically for the purpose of defining a
PrettyBy
instance for
any
a
:
PrettyAny
. Read its docs for details on when you might want to use it.
The
PrettyBy
instance for common types is defined in a way that allows to override default
pretty-printing behaviour, read the docs of
HasPrettyDefaults
for details.
Nothing
prettyBy :: config -> a -> Doc ann Source #
Pretty-print a value of type
a
the way a
config
specifies it.
The default implementation of
prettyBy
is in terms of
pretty
,
defaultPrettyFunctorBy
or
defaultPrettyBifunctorBy
depending on the kind of the data type that you're providing
an instance for. For example, the default implementation of
prettyBy
for a monomorphic type
is going to be "ignore the config and call
pretty
over the value":
>>>
newtype N = N Int deriving newtype (Pretty)
>>>
instance PrettyBy () N
>>>
prettyBy () (N 42)
42
The default implementation of
prettyBy
for a
Functor
is going to be in terms of
defaultPrettyFunctorBy
:
>>>
newtype N a = N a deriving stock (Functor) deriving newtype (Pretty)
>>>
instance PrettyBy () a => PrettyBy () (N a)
>>>
prettyBy () (N (42 :: Int))
42
It's fine for the data type to have a phantom parameter as long as the data type is still a
Functor
(i.e. the parameter has to be of kind
Type
). Then
defaultPrettyFunctorBy
is used
again:
>>>
newtype N a = N Int deriving stock (Functor) deriving newtype (Pretty)
>>>
instance PrettyBy () (N b)
>>>
prettyBy () (N 42)
42
If the data type has a single parameter of any other kind, then it's not a functor and so
like in the monomorphic case
pretty
is used:
>>>
newtype N (b :: Bool) = N Int deriving newtype (Pretty)
>>>
instance PrettyBy () (N b)
>>>
prettyBy () (N 42)
42
Same applies to a data type with two parameters: if both the parameters are of kind
Type
,
then the data type is assumed to be a
Bifunctor
and hence
defaultPrettyBifunctorBy
is
used. If the right parameter is of kind
Type
and the left parameter is of any other kind,
then we fallback to assuming the data type is a
Functor
and defining
prettyBy
as
defaultPrettyFunctorBy
. If both the parameters are not of kind
Type
, we fallback to
implementing
prettyBy
in terms of
pretty
like in the monomorphic case.
Note that in all those cases a
Pretty
instance for the data type has to already exist,
so that we can derive a
PrettyBy
one in terms of it. If it doesn't exist or if your data
type is not supported (for example, if it has three or more parameters of kind
Type
), then
you'll need to provide the implementation manually.
prettyListBy :: config -> [a] -> Doc ann Source #
prettyListBy
is used to define the default
PrettyBy
instance for
[a]
and
NonEmpty a
.
In normal circumstances only the
prettyBy
function is used.
The default implementation of
prettyListBy
is in terms of
defaultPrettyFunctorBy
.
Instances
type family HasPrettyDefaults config :: Bool Source #
Determines whether a pretty-printing config allows default pretty-printing for types that support it. I.e. it's possible to create a new config and get access to pretty-printing for all types supporting default pretty-printing just by providing the right type instance. Example:
>>>
data DefCfg = DefCfg
>>>
type instance HasPrettyDefaults DefCfg = 'True
>>>
prettyBy DefCfg (['a', 'b', 'c'], (1 :: Int), Just True)
(abc, 1, True)
The set of types supporting default pretty-printing is determined by the
prettyprinter
library: whatever
there
has a
Pretty
instance also supports default pretty-printing
in this library and the behavior of
pretty x
and
prettyBy config_with_defaults x
must
be identical when
x
is one of such types.
It is possible to override default pretty-printing. For this you need to specify that
HasPrettyDefaults
is
'False
for your config and then define a
NonDefaultPrettyBy config
instance for each of the types supporting default pretty-printing that you want to pretty-print
values of. Note that once
HasPrettyDefaults
is specified to be
'False
,
all defaults are lost
for your config, so you can't override default pretty-printing for one
type and keep the defaults for all the others. I.e. if you have
>>>
data NonDefCfg = NonDefCfg
>>>
type instance HasPrettyDefaults NonDefCfg = 'False
then you have no defaults available and an attempt to pretty-print a value of a type supporting default pretty-printing
prettyBy NonDefCfg True
results in a type error:
• No instance for (NonDefaultPrettyBy NonDef Bool) arising from a use of ‘prettyBy’
As the error suggests you need to provide a
NonDefaultPrettyBy
instance explicitly:
>>>
instance NonDefaultPrettyBy NonDefCfg Bool where nonDefaultPrettyBy _ b = if b then "t" else "f"
>>>
prettyBy NonDefCfg True
t
It is also possible not to provide any implementation for
nonDefaultPrettyBy
, in which case
it defaults to being the default pretty-printing for the given type. This can be useful to
recover default pretty-printing for types pretty-printing of which you don't want to override:
>>>
instance NonDefaultPrettyBy NonDefCfg Int
>>>
prettyBy NonDefCfg (42 :: Int)
42
Look into
test/NonDefault.hs
for an extended example.
We could give the user more fine-grained control over what defaults to override instead of requiring to explicitly provide all the instances whenever there's a need to override any default behavior, but that would complicate the library even more, so we opted for not doing that at the moment.
Note that you can always override default behavior by wrapping a type in
newtype
and
providing a
PrettyBy config_name
instance for that
newtype
.
Also note that if you want to extend the set of types supporting default pretty-printing
it's not enough to provide a
Pretty
instance for your type (such logic is hardly expressible
in present day Haskell). Read the docs of
DefaultPrettyBy
for how to extend the set of types
supporting default pretty-printing.
Instances
type HasPrettyDefaults () |
|
Defined in Text.PrettyBy.Internal |
|
type HasPrettyDefaults PrettyConfigPlc Source # | |
Defined in PlutusCore.Pretty.Plc |
|
type HasPrettyDefaults ConstConfig Source # | |
Defined in PlutusCore.Pretty.PrettyConst |
|
type HasPrettyDefaults ( PrettyConfigReadable _1) Source # | |
Defined in PlutusCore.Pretty.Readable |
|
type HasPrettyDefaults ( PrettyConfigClassic _1) Source # | |
Defined in PlutusCore.Pretty.Classic |
type PrettyDefaultBy config = DispatchPrettyDefaultBy ( NonStuckHasPrettyDefaults config) config Source #
PrettyDefaultBy config a
is the same thing as
PrettyBy config a
, when
a
supports
default pretty-printing. Thus
PrettyDefaultBy config a
and
PrettyBy config a
are
interchangeable constraints for such types, but the latter throws an annoying
"this makes type inference for inner bindings fragile" warning, unlike the former.
PrettyDefaultBy config a
reads as "
a
supports default pretty-printing and can be
pretty-printed via
config
in either default or non-default manner depending on whether
config
supports default pretty-printing".
A
newtype
wrapper around
a
provided for the purporse of defining
PrettyBy
instances
handling any
a
. For example you can wrap values with the
PrettyAny
constructor directly
like in this last line of
>>>
data ViaShow = ViaShow
>>>
instance Show a => PrettyBy ViaShow (PrettyAny a) where prettyBy ViaShow = pretty . show . unPrettyAny
>>>
prettyBy ViaShow $ PrettyAny True
True
or you can use the type to via-derive instances:
>>>
data D = D deriving stock (Show)
>>>
deriving via PrettyAny D instance PrettyBy ViaShow D
>>>
prettyBy ViaShow D
D
One important use case is handling sum-type configs. For example having two configs you can
define their sum and derive
PrettyBy
for the unified config in terms of its components:
>>>
data UpperCase = UpperCase
>>>
data LowerCase = LowerCase
>>>
data Case = CaseUpperCase UpperCase | CaseLowerCase LowerCase
>>>
instance (PrettyBy UpperCase a, PrettyBy LowerCase a) => PrettyBy Case (PrettyAny a) where prettyBy (CaseUpperCase upper) = prettyBy upper . unPrettyAny; prettyBy (CaseLowerCase lower) = prettyBy lower . unPrettyAny
Then having a data type implementing both
PrettyBy UpperCase
and
PrettyBy LowerCase
you can
derive
PrettyBy Case
for that data type:
>>>
data D = D
>>>
instance PrettyBy UpperCase D where prettyBy UpperCase D = "D"
>>>
instance PrettyBy LowerCase D where prettyBy LowerCase D = "d"
>>>
deriving via PrettyAny D instance PrettyBy Case D
>>>
prettyBy UpperCase D
D>>>
prettyBy LowerCase D
d
Look into
test/Universal.hs
for an extended example.
PrettyAny | |
|
Instances
display :: forall str a. ( Pretty a, Render str) => a -> str Source #
Pretty-print and render a value as a string type.
GHCi
printPretty :: Pretty a => a -> IO () Source #
A command suitable for use in GHCi as an interactive printer.
Text
Orphan instances
PrettyDefaultBy config ( Either a b) => PrettyBy config ( Either a b) Source # |
An instance extending the set of types supporting default pretty-printing with
|
( PrettyBy config a, PrettyBy config b) => DefaultPrettyBy config ( Either a b) Source # |
Default pretty-printing for the
spine
of
|
defaultPrettyBy :: config -> Either a b -> Doc ann Source # defaultPrettyListBy :: config -> [ Either a b] -> Doc ann Source # |
|
( Pretty a, Pretty b) => Pretty ( Either a b) Source # | |