HORIZON HASKELLDocslts/ghc-9.14.xd82dee82026-10-12Search names, modules, packages, or :: a typeCtrl K

GHC 9.14.1 · lts/ghc-9.14.x · d82dee8 · 2026-10-12

Moduleplutus-core-1.70.0.0

PlutusPrelude

  • 10 types
  • 11 classes
  • 58 values
value(.*) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
#
valuejoin :: Monad m => m (m a) -> m a
#

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

'join bss' can be understood as the do expression

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

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

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

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

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

we can compose them as

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

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

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

Left-to-right composition. This is useful if you want to write a morphism as a pipeline going from left to right.

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

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

Note how this operator resembles function composition (.):

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

Left-to-right composition of Kleisli arrows.

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

do b <- bs a
   cs b

or in terms of (>>=) as

bs a >>= cs
valueguard :: Alternative f => Bool -> f ()
#

Conditional failure of Alternative computations. Defined by

guard True  = pure ()
guard False = empty
Examples

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

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

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

A definition of safeDiv using guards, but not guard:

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

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

safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
  guard (y /= 0)
  return (x `div` y)
valuefromRight :: b -> Either a b -> b
#

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

Examples

Basic usage:

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

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

Examples

Basic usage:

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

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

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

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

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

Examples

Basic usage:

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

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

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

Example4 expressions
import Control.Monad ( when )let report e = when (isRight e) $ putStrLn "SUCCESS"report (Left "parse error")report (Right 1)SUCCESS
valuetraverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
#

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

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

Examples

Basic usage:

Example1 expression
traverse_ print ["Hello", "world", "!"]"Hello""world""!"
value(&) :: a -> (a -> b) -> b
#

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

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

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

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

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

Flipped version of <$.

Examples

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

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

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

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

Replace each element of a list with a constant String:

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

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

Example1 expression
(1,2) $> "foo"(1,"foo")
value(<&>) :: Functor f => f a -> (a -> b) -> f b
#

Flipped version of <$>.

(<&>) = flip fmap
Examples

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

Example1 expression
Just 2 <&> (+1)Just 3
Example1 expression
[1,2,3] <&> (+1)[2,3,4]
Example1 expression
Right 3 <&> (+1)Right 4
valuevoid :: Functor f => f a -> f ()
#

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

Examples

Replace the contents of a Maybe Int with unit:

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

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

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

Replace every element of a list with unit:

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

Replace the second element of a pair with unit:

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

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

Example1 expression
mapM print [1,2]12[(),()]
Example1 expression
void $ mapM print [1,2]12
valuefromMaybe :: a -> Maybe a -> a
#

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

Examples

Basic usage:

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

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

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

isJust x returns True when x is of the form Just _ and False otherwise.

Examples

Basic usage:

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

Only the outer constructor is taken into consideration:

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

isNothing x returns True when x is Nothing and False otherwise.

Examples

Basic usage:

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

Only the outer constructor is taken into consideration:

Example1 expression
isNothing (Just Nothing)False
valuetrace :: String -> a -> a
#

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 and outputs the message to stderr. Depending on your terminal (settings), they may or may not be mixed.

Example2 expressions
let x = 123; f = showtrace ("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.

valuetraceShowId :: Show a => a -> a
#

Like traceShow but returns the shown value instead of a third value.

Example1 expression
traceShowId (1+2+3, "hello" ++ "world")(6,"helloworld")(6,"helloworld")
valuethrow :: (HasCallStack, Exception e) => e -> a
#

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

WARNING: You may want to use throwIO instead so that your pure code stays exception-free.

value(^.) :: s -> Getting a s a -> a
#

View the value pointed to by a Getter or Lens or the result of folding over all the results of a Control.Lens.Fold.Fold or Control.Lens.Traversal.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 (Prelude..).

Example1 expression
(a,b)^._2b
Example1 expression
("hello","world")^._2"world"
Example2 expressions
import Data.Complex((0, 1 :+ 2), 3)^._1._2.to magnitude2.23606797749979
(^.) ::             s -> Getter s a     -> a
(^.) :: Monoid m => s -> Control.Lens.Fold.Fold s m       -> m
(^.) ::             s -> Control.Lens.Iso.Iso' s a       -> a
(^.) ::             s -> Lens' s a      -> a
(^.) :: Monoid m => s -> Control.Lens.Traversal.Traversal' s m -> m
valueview :: MonadReader s m => Getting a s a -> m a
#

View the value pointed to by a Getter, Control.Lens.Iso.Iso or Lens or the result of folding over all the results of a Fold or Control.Lens.Traversal.Traversal that points at a monoidal value.

view . to ≡ id
Example1 expression
view (to f) af a
Example1 expression
view _2 (1,"hello")"hello"
Example1 expression
view (to succ) 56
Example1 expression
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 -> a
view :: Monoid m => Fold s m       -> s -> m
view ::             Control.Lens.Iso.Iso' s a       -> s -> a
view ::             Lens' s a      -> s -> a
view :: Monoid m => Control.Lens.Traversal.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 a
view :: (MonadReader s m, Monoid a) => Fold s a       -> m a
view :: MonadReader s m             => Control.Lens.Iso.Iso' s a       -> m a
view :: MonadReader s m             => Lens' s a      -> m a
view :: (MonadReader s m, Monoid a) => Control.Lens.Traversal.Traversal' s a -> m a
valuelens :: (s -> a) -> (s -> b -> t) -> Lens s t a b
#

Build a Lens from a getter and a setter.

lens :: Functor f => (s -> a) -> (s -> b -> t) -> (a -> f b) -> s -> f t
Example1 expression
s ^. lens getter settergetter s
Example1 expression
s & lens getter setter .~ bsetter s b
Example1 expression
s & lens getter setter %~ fsetter s (f (getter s))
lens :: (s -> a) -> (s -> a -> s) -> Lens' s a
value(%~) :: ASetter s t a b -> (a -> b) -> s -> t
#

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 %~ f
fmapDefault f ≡ traverse %~ f
Example1 expression
(a,b,c) & _3 %~ f(a,b,f c)
Example1 expression
(a,b) & both %~ f(f a,f b)
Example1 expression
_2 %~ length $ (1,"hello")(1,5)
Example1 expression
traverse %~ f $ [a,b,c][f a,f b,f c]
Example1 expression
traverse %~ even $ [1,2,3][False,True,False]
Example1 expression
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
value(.~) :: ASetter s t a b -> b -> s -> t
#

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
Example1 expression
(a,b,c,d) & _4 .~ e(a,b,c,e)
Example1 expression
(42,"world") & _1 .~ "hello"("hello","world")
Example1 expression
(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
valueover :: ASetter s t a b -> (a -> b) -> s -> t
#

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.

Example1 expression
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".

Example1 expression
over mapped f (Just a)Just (f a)
Example1 expression
over mapped (*10) [1,2,3][10,20,30]
Example1 expression
over _1 f (a,b)(f a,b)
Example1 expression
over _1 show (10,20)("10",20)
over :: Setter s t a b -> (a -> b) -> s -> t
over :: ASetter s t a b -> (a -> b) -> s -> t
valueset :: ASetter s t a b -> b -> s -> t
#

Replace the target of a Lens or all of the targets of a Setter or Traversal with a constant value.

(<$) ≡ set mapped
Example1 expression
set _2 "hello" (1,())(1,"hello")
Example1 expression
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 -> t
set :: Iso s t a b       -> b -> s -> t
set :: Lens s t a b      -> b -> s -> t
set :: Traversal s t a b -> b -> s -> t
value(#.) :: Coercible b c => (b -> c) -> (a -> b) -> a -> c
#
valuedisplay :: (Pretty a, Render str) => a -> str
#

Pretty-print and render a value as a string type.

valuecoerce :: Coercible a b => a -> b
#

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 42coerce (+ (1 :: Int)) (Age 42) :: TTLTTL 43coerce (map (+ (1 :: Int))) [Age 42, Age 24] :: [TTL][TTL 43,TTL 25]
methodfirst :: (a -> b) -> p a c -> p b c
#

Map covariantly over the first argument.

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

Map covariantly over the second argument.

second ≡ bimap id
Examples
Example1 expression
second (+1) ('j', 3)('j',4)
Example1 expression
second (+1) (Right 3)Right 4
classclass Default a where
#

A class for types with a default value.

Methods

  • def :: a

    The default value for this type.

Instances113Default, …
classclass NFData a where
#

A class of types that can be fully evaluated.

Instances504Lifting2, Lifting, NFData, …
classclass Applicative f => Alternative (f :: Type -> Type) where
#

A monoid on applicative functors.

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

Examples
Example1 expression
Nothing <|> Just 42Just 42
Example1 expression
[1, 2] <|> [3, 4][1,2,3,4]
Example1 expression
empty <|> print (2^15)32768

Methods

  • empty :: f a

    The identity of <|>

    empty <|> a     == a
    a     <|> empty == a
  • (<|>) :: f a -> f a -> f ainfixl 3

    An associative binary operation

  • some :: f a -> f [a]

    One or more.

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

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

  • many :: f a -> f [a]

    Zero or more.

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

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

Instances115:=>, Lifting2, Lifting, Class, Alternative, …
datadata NonEmpty a
#

Non-empty (and non-strict) list type.

Constructors

  • a :| [a]infixr 5
Instances95Monad, Functor, MonadFix, Applicative, Foldable, Traversable, …
method(&&&) :: a b c -> a b c' -> a b (c, c')
#

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

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

    ╭───────╮ c
  b │ ┌─ f ─┼───>
>───┼─┤     │
    │ └─ g ─┼───>
    ╰───────╯ c'
methodfold :: Monoid m => t m -> m
#

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

Examples

Basic usage:

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

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

Example1 expression
fold (repeat Nothing)* Hangs forever *

Lazy corecursive folds of unbounded structures are fine:

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

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

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

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

foldl' f z = foldl' f z . toList
methodtoList :: t a -> [a]
#

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

Examples

Basic usage:

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

For lists, toList is the identity:

Example1 expression
toList [1, 2, 3][1,2,3]
classclass (Typeable e, Show e) => Exception e where
#

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

data MyException = ThisException | ThatException
    deriving Show

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
Instances83Exception, …
classclass Generic a where
#

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 ≡ Prelude.id
to . from ≡ Prelude.id
Instances494Generic, …
datadata Word64
#

64-bit unsigned integer type

Instances113Bounded, Enum, Eq, Data, Num, Ord, …
datadata Word8
#

8-bit unsigned integer type

Instances125Bounded, Enum, Eq, Data, Num, Ord, …
classclass HasAnn (f :: Type -> Type) where
#

Methods

Instances3HasAnn
  • HasAnn (Type tyname uni)Defined in plutus-core-1.70.0.0 · PlutusCore.Core.Type
  • HasAnn (Term name uni fun)Defined in plutus-core-1.70.0.0 · UntypedPlutusCore.Core.Type
  • HasAnn (Term tyname name uni fun)Defined in plutus-core-1.70.0.0 · PlutusCore.Core.Type
datadata Doc ann
#

The abstract data type Doc ann represents pretty documents that have been annotated with data of type ann.

More specifically, a value of type Doc 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.

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.

Example1 expression
putStrLn (show (vsep ["hello", "world"]))helloworld
Instances9Functor, PrettyAnn, Show, IsString, Generic, Semigroup, …
classclass Pretty a where
#

Overloaded conversion to Doc.

Laws:

  1. output should be pretty. :-)

Methods

  • pretty :: a -> Doc ann
    Example1 expression
    pretty 1 <+> pretty "hello" <+> pretty 1.2341 hello 1.234
  • prettyList :: [a] -> Doc ann

    prettyList is only used to define the instance Pretty a => Pretty [a]. In normal circumstances only the pretty function is used.

    Example1 expression
    prettyList [1, 23, 456][1, 23, 456]
Instances101Pretty, …
  • Pretty VoidDefined in prettyprinter-1.7.2 · Prettyprinter.Internal

    Finding a good example for printing something that does not exist is hard, so here is an example of printing a list full of nothing.

    Example1 expression
    pretty ([] :: [Void])[]
  • Pretty IntegerDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (2^123 :: Integer)10633823966279326983230456482242756608
  • Pretty NaturalDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Int16Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Int32Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Int64Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Int8Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty BoolDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty TrueTrue
  • Pretty CharDefined in prettyprinter-1.7.2 · Prettyprinter.Internal

    Instead of (pretty '\n'), consider using line as a more readable alternative.

    Example2 expressions
    pretty 'f' <> pretty 'o' <> pretty 'o'foopretty ("string" :: String)string
  • Pretty DoubleDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (exp 1 :: Double)2.71828182845904...
  • Pretty FloatDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (pi :: Float)3.1415927
  • Pretty IntDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (123 :: Int)123
  • Pretty WordDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Word16Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Word32Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Word64Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty Word8Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty SourcePosDefined in plutus-core-1.70.0.0 · PlutusCore.Error · orphan
  • Pretty DeserialiseFailureInfoDefined in plutus-core-1.70.0.0 · Codec.Extras.SerialiseViaFlat
  • Pretty DeserialiseFailureReasonDefined in plutus-core-1.70.0.0 · Codec.Extras.SerialiseViaFlat
  • Pretty AnnDefined in plutus-core-1.70.0.0 · PlutusCore.Annotation
  • Pretty SrcSpanDefined in plutus-core-1.70.0.0 · PlutusCore.Annotation
  • Pretty SrcSpansDefined in plutus-core-1.70.0.0 · PlutusCore.Annotation
  • Pretty ParamDefined in plutus-core-1.70.0.0 · PlutusCore.Arity
  • Pretty AstSizeDefined in plutus-core-1.70.0.0 · PlutusCore.AstSize
  • Pretty BuiltinErrorDefined in plutus-core-1.70.0.0 · PlutusCore.Builtin.Result
  • Pretty UnliftingErrorDefined in plutus-core-1.70.0.0 · PlutusCore.Builtin.Result
  • Pretty UnliftingEvaluationErrorDefined in plutus-core-1.70.0.0 · PlutusCore.Builtin.Result
  • Pretty NameAnnDefined in plutus-core-1.70.0.0 · PlutusCore.Check.Scoping
  • Pretty ScopeErrorDefined in plutus-core-1.70.0.0 · PlutusCore.Check.Scoping
  • Pretty ElementDefined in plutus-core-1.70.0.0 · PlutusCore.Crypto.BLS12_381.G1
  • Pretty ElementDefined in plutus-core-1.70.0.0 · PlutusCore.Crypto.BLS12_381.G2
  • Pretty MlResultDefined in plutus-core-1.70.0.0 · PlutusCore.Crypto.BLS12_381.Pairing
  • Pretty DataDefined in plutus-core-1.70.0.0 · PlutusCore.Data
  • Pretty FreeVariableErrorDefined in plutus-core-1.70.0.0 · PlutusCore.DeBruijn.Internal
  • Pretty IndexDefined in plutus-core-1.70.0.0 · PlutusCore.DeBruijn.Internal
  • Pretty DefaultFunDefined in plutus-core-1.70.0.0 · PlutusCore.Default.Builtins
  • Pretty ParserErrorDefined in plutus-core-1.70.0.0 · PlutusCore.Error
  • Pretty ParserErrorBundleDefined in plutus-core-1.70.0.0 · PlutusCore.Error
  • Pretty CkUserErrorDefined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Machine.Ck
  • Pretty CostModelApplyErrorDefined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Machine.CostModelInterface
  • Pretty CostModelApplyWarnDefined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Machine.CostModelInterface
  • Pretty ExBudgetDefined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Machine.ExBudget
  • Pretty ExRestrictingBudgetDefined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Machine.ExBudget
  • Pretty ExCPUDefined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Machine.ExMemory
  • Pretty ExMemoryDefined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Machine.ExMemory
  • Pretty ExtensionFunDefined in plutus-core-1.70.0.0 · PlutusCore.Examples.Builtins
  • Pretty NameDefined in plutus-core-1.70.0.0 · PlutusCore.Core.Instance.Pretty.Default · orphan
  • Pretty TyNameDefined in plutus-core-1.70.0.0 · PlutusCore.Core.Instance.Pretty.Default · orphan
  • Pretty UniqueDefined in plutus-core-1.70.0.0 · PlutusCore.Name.Unique
  • Pretty QuantityDefined in plutus-core-1.70.0.0 · PlutusCore.Value
  • Pretty ValueDefined in plutus-core-1.70.0.0 · PlutusCore.Value
  • Pretty VersionDefined in plutus-core-1.70.0.0 · PlutusCore.Version
  • Pretty CountingStDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Evaluation.Machine.Cek.ExBudgetMode
  • Pretty RestrictingStDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Evaluation.Machine.Cek.ExBudgetMode
  • Pretty CekUserErrorDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Evaluation.Machine.Cek.Internal
  • Pretty CseWhichSubtermsDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Optimize.Opts
  • Pretty PurityDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Purity
  • Pretty WorkFreedomDefined in plutus-core-1.70.0.0 · UntypedPlutusCore.Purity
  • Pretty TextDefined in prettyprinter-1.7.2 · Prettyprinter.Internal

    Automatically converts all newlines to line.

    Example1 expression
    pretty ("hello\nworld" :: Text)helloworld

    Note that line can be undone by group:

    Example1 expression
    group (pretty ("hello\nworld" :: Text))hello world

    Manually use hardline if you definitely want newlines.

  • Pretty TextDefined in prettyprinter-1.7.2 · Prettyprinter.Internal

    (lazy Text instance, identical to the strict version)

  • Pretty ()Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty ()()

    The argument is not used:

    Example1 expression
    pretty (error "Strict?" :: ())()
  • Show fun => Pretty (ExBudgetCategory fun)Defined in plutus-core-1.70.0.0 · UntypedPlutusCore.Evaluation.Machine.Cek.Internal
  • PrettyClassic a => Pretty (EvaluationResult a)Defined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Result
  • PrettyReadable a => Pretty (AsReadable a)Defined in plutus-core-1.70.0.0 · PlutusCore.Pretty.Readable
  • Pretty (BuiltinSemanticsVariant DefaultFun)Defined in plutus-core-1.70.0.0 · PlutusCore.Default.Builtins
  • Pretty (DefaultUni a)Defined in plutus-core-1.70.0.0 · PlutusCore.Default.Universe
  • Pretty (SomeTypeIn DefaultUni)Defined in plutus-core-1.70.0.0 · PlutusCore.Default.Universe
  • Pretty (SomeTypeIn uni) => Pretty (SomeTypeIn (Kinded uni))Defined in plutus-core-1.70.0.0 · PlutusCore.Pretty.PrettyConst · orphan
  • Pretty a => Pretty (NonEmpty a)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Pretty a => Pretty (Identity a)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (Identity 1)1
  • Pretty a => Pretty (Maybe a)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal

    Ignore Nothings, print Just contents.

    Example2 expressions
    pretty (Just True)Truebraces (pretty (Nothing :: Maybe Bool)){}
    Example1 expression
    pretty [Just 1, Nothing, Just 3, Nothing][1, 3]
  • Pretty a => Pretty (Spine a)Defined in plutus-core-1.70.0.0 · PlutusCore.Builtin.KnownType
  • Pretty a => Pretty (Normalized a)Defined in plutus-core-1.70.0.0 · PlutusCore.Core.Type
  • Pretty a => Pretty [a]Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty [1,2,3][1, 2, 3]
  • Pretty ann => Pretty (Kind ann)Defined in plutus-core-1.70.0.0 · PlutusCore.Core.Instance.Pretty.Default · orphan
  • Pretty ann => Pretty (UniqueError ann)Defined in plutus-core-1.70.0.0 · PlutusCore.Error
  • (Show fun, Ord fun) => Pretty (CekExTally fun)Defined in plutus-core-1.70.0.0 · UntypedPlutusCore.Evaluation.Machine.Cek.ExBudgetMode
  • (Show fun, Ord fun) => Pretty (TallyingSt fun)Defined in plutus-core-1.70.0.0 · UntypedPlutusCore.Evaluation.Machine.Cek.ExBudgetMode
  • ann ~ Void => Pretty (Doc ann)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • DefaultPrettyBy config a => Pretty (AttachDefaultPrettyConfig config a)Defined in prettyprinter-configurable-1.36.0.0 · Text.PrettyBy.Internal
  • PrettyBy config a => Pretty (AttachPrettyConfig config a)Defined in prettyprinter-configurable-1.36.0.0 · Text.PrettyBy.Internal
    Example4 expressions
    data Cfg = Cfgdata D = Dinstance PrettyBy Cfg D where prettyBy Cfg D = "D"pretty $ AttachPrettyConfig Cfg DD
  • (Closed uni, Everywhere uni PrettyConst) => Pretty (ValueOf uni a)Defined in plutus-core-1.70.0.0 · PlutusCore.Pretty.PrettyConst · orphan
  • (Closed uni, Everywhere uni PrettyConst) => Pretty (Some (ValueOf uni))Defined in plutus-core-1.70.0.0 · PlutusCore.Pretty.PrettyConst · orphan
  • (Pretty a, Pretty b) => Pretty (Either a b)Defined in plutus-core-1.70.0.0 · PlutusPrelude · orphan
  • (Pretty a1, Pretty a2) => Pretty (a1, a2)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (123, "hello")(123, hello)
  • (Pretty err, Pretty cause) => Pretty (ErrorWithCause err cause)Defined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.ErrorWithCause
  • (Pretty structural, Pretty operational) => Pretty (EvaluationError structural operational)Defined in plutus-core-1.70.0.0 · PlutusCore.Evaluation.Error
  • Pretty (CekState uni fun ann)Defined in plutus-core-1.70.0.0 · UntypedPlutusCore.Evaluation.Machine.SteppableCek.Internal
  • Pretty a => Pretty (Const a b)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • (PrettyClassic tyname, PrettyParens (SomeTypeIn uni), Pretty ann) => Pretty (Type tyname uni ann)Defined in plutus-core-1.70.0.0 · PlutusCore.Core.Instance.Pretty.Default · orphan
  • (Pretty a1, Pretty a2, Pretty a3) => Pretty (a1, a2, a3)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (123, "hello", False)(123, hello, False)
  • (Pretty err, Pretty a, Pretty b) => Pretty (HeadSpine err a b)Defined in plutus-core-1.70.0.0 · PlutusCore.Builtin.KnownType
  • (PrettyClassic name, PrettyUni uni, Pretty fun, Pretty ann) => Pretty (Program name uni fun ann)Defined in plutus-core-1.70.0.0 · UntypedPlutusCore.Core.Instance.Pretty.Default · orphan
  • (PrettyClassic name, PrettyUni uni, Pretty fun, Pretty ann) => Pretty (Term name uni fun ann)Defined in plutus-core-1.70.0.0 · UntypedPlutusCore.Core.Instance.Pretty.Default · orphan
  • (Pretty a1, Pretty a2, Pretty a3, Pretty a4) => Pretty (a1, a2, a3, a4)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (123, "hello", False, ())(123, hello, False, ())
  • (PrettyClassic tyname, PrettyClassic name, PrettyUni uni, Pretty fun, Pretty ann) => Pretty (Program tyname name uni fun ann)Defined in plutus-core-1.70.0.0 · PlutusCore.Core.Instance.Pretty.Default · orphan
  • (PrettyClassic tyname, PrettyClassic name, PrettyUni uni, Pretty fun, Pretty ann) => Pretty (Term tyname name uni fun ann)Defined in plutus-core-1.70.0.0 · PlutusCore.Core.Instance.Pretty.Default · orphan
  • (Pretty a1, Pretty a2, Pretty a3, Pretty a4, Pretty a5) => Pretty (a1, a2, a3, a4, a5)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (123, "hello", False, (), 3.14)(123, hello, False, (), 3.14)
  • (Pretty a1, Pretty a2, Pretty a3, Pretty a4, Pretty a5, Pretty a6) => Pretty (a1, a2, a3, a4, a5, a6)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (123, "hello", False, (), 3.14, Just 2.71)(123, hello, False, (), 3.14, 2.71)
  • (Pretty a1, Pretty a2, Pretty a3, Pretty a4, Pretty a5, Pretty a6, Pretty a7) => Pretty (a1, a2, a3, a4, a5, a6, a7)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
    Example1 expression
    pretty (123, "hello", False, (), 3.14, Just 2.71, [1,2,3])(123, hello, False, (), 3.14, 2.71, [1, 2, 3])
classclass Render str where
#

A class for rendering Docs as string types.

Methods

Instances3Render
  • Render TextDefined in prettyprinter-configurable-1.36.0.0 · Text.PrettyBy.Default
  • Render TextDefined in prettyprinter-configurable-1.36.0.0 · Text.PrettyBy.Default
  • a ~ Char => Render [a]Defined in prettyprinter-configurable-1.36.0.0 · Text.PrettyBy.Default
familytype family HasPrettyDefaults config :: Bool
#

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:

Example3 expressions
data DefCfg = DefCfgtype instance HasPrettyDefaults DefCfg = 'TrueprettyBy 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

Example2 expressions
data NonDefCfg = NonDefCfgtype 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:

Example2 expressions
instance NonDefaultPrettyBy NonDefCfg Bool where nonDefaultPrettyBy _ b = if b then "t" else "f"prettyBy NonDefCfg Truet

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:

Example2 expressions
instance NonDefaultPrettyBy NonDefCfg IntprettyBy 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.

Instances7HasPrettyDefaults, …
newtypenewtype PrettyAny a
#

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

Example3 expressions
data ViaShow = ViaShowinstance Show a => PrettyBy ViaShow (PrettyAny a) where prettyBy ViaShow = pretty . show . unPrettyAnyprettyBy ViaShow $ PrettyAny TrueTrue

or you can use the type to via-derive instances:

Example3 expressions
data D = D deriving stock (Show)deriving via PrettyAny D instance PrettyBy ViaShow DprettyBy ViaShow DD

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:

Example4 expressions
data UpperCase = UpperCasedata LowerCase = LowerCasedata Case = CaseUpperCase UpperCase | CaseLowerCase LowerCaseinstance (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:

Example6 expressions
data D = Dinstance PrettyBy UpperCase D where prettyBy UpperCase D = "D"instance PrettyBy LowerCase D where prettyBy LowerCase D = "d"deriving via PrettyAny D instance PrettyBy Case DprettyBy UpperCase DDprettyBy LowerCase Dd

Look into test/Universal.hs for an extended example.

Constructors

Instances5NonDefaultPrettyBy, PrettyBy, DefaultPrettyBy
classclass PrettyBy config a where
#

A class for pretty-printing values in a configurable manner.

A basic example:

Example5 expressions
data Case = UpperCase | LowerCasedata D = Dinstance PrettyBy Case D where prettyBy UpperCase D = "D"; prettyBy LowerCase D = "d"prettyBy UpperCase DDprettyBy LowerCase Dd

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

Example2 expressions
data ViaShow = ViaShowinstance 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.

Methods

  • prettyBy :: config -> a -> Doc ann

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

    Example3 expressions
    newtype N = N Int deriving newtype (Pretty)instance PrettyBy () NprettyBy () (N 42)42

    The default implementation of prettyBy for a Functor is going to be in terms of defaultPrettyFunctorBy:

    Example3 expressions
    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:

    Example3 expressions
    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:

    Example3 expressions
    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

    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.

Instances110PrettyBy, …

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".

datadata Natural
#

Natural number

Invariant: numbers <= 0xffffffffffffffff use the NS constructor

Instances90Enum, Eq, Data, Num, Ord, Read, …
classclass a ~ b => Coercible (a :: k) (b :: k)
#

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.

Instances1HasDict

Orphan instances

3 instances