Copyright | (c) Red Hat 2022 |
---|---|
License | Apache-2.0 |
Maintainer | tdecacqu@redhat.com, fboucher@redhat.com |
Stability | provisional |
Portability | portable |
Safe Haskell | Safe-Inferred |
Language | GHC2021 |
This module exports common functions and helpers.
Synopsis
- getSec :: IO Int64
- intervalMilliSec :: IO (IO Int64)
- gitVersion :: Text
- data Logger
- info :: Logger -> ByteString -> IO ()
- withLogger :: (Logger -> IO a) -> IO a
- pPrint :: (MonadIO m, Show a) => a -> m ()
- pShowNoColor :: Show a => a -> Text
- data SomeException
- try :: Exception e => IO a -> IO (Either e a)
- catchAll :: MonadCatch m => m a -> (SomeException -> m a) -> m a
- newtype FilePathT = FilePathT Text
- (</>) :: FilePathT -> FilePathT -> FilePathT
- getPath :: FilePathT -> FilePath
- listDirectory :: FilePathT -> IO [FilePathT]
- doesDirectoryExist :: FilePathT -> IO Bool
- readFileBS :: FilePathT -> IO ByteString
- readFileText :: FilePathT -> IO Text
- writeFileText :: FilePathT -> Text -> IO ()
- data Text
- data ByteString
- data Map k a
- data Set a
- type Forest a = [Tree a]
- data Tree a = Node {}
- class From source target
- from :: From source target => source -> target
- via :: forall through source target. (From source through, From through target) => source -> target
- into :: forall target source. From source target => source -> target
- unsafeFrom :: (HasCallStack, TryFrom source target, Show source, Typeable source, Typeable target) => source -> target
- unsafeInto :: forall target source. (HasCallStack, TryFrom source target, Show source, Typeable source, Typeable target) => source -> target
- lift :: (MonadTrans t, Monad m) => m a -> t m a
- type Reader r = ReaderT r Identity
- data ReaderT r (m :: Type -> Type) a
- runReaderT :: ReaderT r m a -> r -> m a
- type State s = StateT s Identity
- data StateT s (m :: Type -> Type) a
- execStateT :: Monad m => StateT s m a -> s -> m s
- data ExceptT e (m :: Type -> Type) a
- runExceptT :: ExceptT e m a -> m (Either e a)
- throwError :: MonadError e m => e -> m a
- except :: forall (m :: Type -> Type) e a. Monad m => Either e a -> ExceptT e m a
- runIdentity :: Identity a -> a
- set :: ASetter s t a b -> b -> s -> t
- over :: ASetter s t a b -> (a -> b) -> s -> t
- use :: MonadState s m => Getting a s a -> m a
- (%=) :: MonadState s m => ASetter s s a b -> (a -> b) -> m ()
- class FromJSON a where
- class FromJSONKey a where
- class ToJSON a where
- toJSON :: a -> Value
- toEncoding :: a -> Encoding
- toJSONList :: [a] -> Value
- toEncodingList :: [a] -> Encoding
- class ToJSONKey a where
- toJSONKey :: ToJSONKeyFunction a
- toJSONKeyList :: ToJSONKeyFunction [a]
- data Value = Object !Object
- genericParseJSON :: (Generic a, GFromJSON Zero (Rep a)) => Options -> Value -> Parser a
- genericToJSON :: (Generic a, GToJSON' Value Zero (Rep a)) => Options -> a -> Value
- defaultOptions :: Options
- omitNothingFields :: Options -> Bool
- encodeJSON :: ToJSON a => a -> ByteString
- decodeJSON :: FromJSON a => ByteString -> Either String a
- newtype Decoder a = Decoder (Either (Text, Value) a)
- decodeFail :: Text -> Value -> Decoder a
- decodeObject :: Value -> Decoder Object
- decodeObjectAttribute :: Key -> Object -> Decoder Value
- decodeAsList :: Key -> (Text -> a) -> Object -> Decoder [a]
- decodeString :: Value -> Decoder Text
- decodeList :: Value -> Decoder [Value]
- s :: QuasiQuoter
- withUtf8 :: (MonadIO m, MonadMask m) => m r -> m r
- whenM :: Monad m => m Bool -> m () -> m ()
- orDie :: Maybe a -> b -> Either b a
- fromEither :: Show a => Either a b -> b
- forkIO :: IO () -> IO ThreadId
- threadDelay :: Int -> IO ()
- data IORef a
- newIORef :: a -> IO (IORef a)
- readIORef :: IORef a -> IO a
- writeIORef :: IORef a -> a -> IO ()
- data MVar a
- newMVar :: a -> IO (MVar a)
- modifyMVar :: MVar a -> (a -> IO (a, b)) -> IO b
- sort :: Ord a => [a] -> [a]
- nub :: Eq a => [a] -> [a]
- data NonEmpty a
- nonEmpty :: [a] -> Maybe (NonEmpty a)
- data Int64
- (&) :: a -> (a -> b) -> b
- data Proxy (t :: k) = Proxy
- first :: Bifunctor p => (a -> b) -> p a c -> p b c
- bool :: a -> a -> Bool -> a
- traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()
- foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b
- catMaybes :: [Maybe a] -> [a]
- mapMaybe :: (a -> Maybe b) -> [a] -> [b]
- isJust :: Maybe a -> Bool
- isNothing :: Maybe a -> Bool
- fromMaybe :: a -> Maybe a -> a
- fromRight :: b -> Either a b -> b
- forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
- foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
- unless :: Applicative f => Bool -> f () -> f ()
- when :: Applicative f => Bool -> f () -> f ()
- void :: Functor f => f a -> f ()
- liftIO :: MonadIO m => IO 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
- (<|>) :: Alternative f => f a -> f a -> f a
- trace :: String -> a -> a
- hPutStrLn :: Handle -> String -> IO ()
- stderr :: Handle
- printf :: PrintfType r => String -> r
- type HasCallStack = ?callStack :: CallStack
- showVersion :: Version -> String
- lookupEnv :: String -> IO (Maybe String)
- getArgs :: IO [String]
- timeout :: Int -> IO a -> IO (Maybe a)
- hash :: Hashable a => a -> Int
- class Eq a => Hashable a
- module Prelude
- class Generic a
clock
intervalMilliSec :: IO (IO Int64) Source #
Compute the time interval in milli-seconds ellapsed between now and the provided action.
th-env
gitVersion :: Text Source #
The content of the GIT_COMMIT environment variable, default to HEAD.
fast-logger
pretty-simple
pPrint :: (MonadIO m, Show a) => a -> m () #
Pretty-print any data type that has a Show
instance.
If you've never seen MonadIO
before, you can think of this function as
having the following type signature:
pPrint :: Show a => a -> IO ()
This function will only use colors if it detects it's printing to a TTY.
This function is for printing to a dark background. Use pPrintLightBg
for
printing to a terminal with a light background. Different colors are used.
Prints to stdout
. Use pHPrint
to print to a different Handle
.
>>>
pPrint [Just (1, "hello")]
[ Just ( 1 , "hello" ) ]
pShowNoColor :: Show a => a -> Text #
Like pShow
, but without color.
>>>
pShowNoColor [ Nothing, Just (1, "hello") ]
"[ Nothing\n, Just\n ( 1\n , \"hello\"\n )\n]"
exceptions
data SomeException #
The SomeException
type is the root of the exception type hierarchy.
When an exception of type e
is thrown, behind the scenes it is
encapsulated in a SomeException
.
Instances
Exception SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type | |
Show SomeException | Since: base-3.0 |
Defined in GHC.Exception.Type showsPrec :: Int -> SomeException -> ShowS # show :: SomeException -> String # showList :: [SomeException] -> ShowS # |
try :: Exception e => IO a -> IO (Either e a) #
Similar to catch
, but returns an Either
result which is
(
if no exception of type Right
a)e
was raised, or (
if an exception of type Left
ex)e
was raised and its value is ex
.
If any other type of exception is raised then it will be propagated
up to the next enclosing exception handler.
try a = catch (Right `liftM` a) (return . Left)
catchAll :: MonadCatch m => m a -> (SomeException -> m a) -> m a #
Catches all exceptions, and somewhat defeats the purpose of the extensible exception system. Use sparingly.
NOTE This catches all exceptions, but if the monad supports other ways of aborting the computation, those other kinds of errors will not be caught.
filepath text
A FilePath encoded with UTF-8.
Instances
FromJSON FilePathT Source # | |
ToJSON FilePathT Source # | |
Defined in ZuulWeeder.Prelude | |
IsString FilePathT Source # | |
Defined in ZuulWeeder.Prelude fromString :: String -> FilePathT # | |
Monoid FilePathT Source # | |
Semigroup FilePathT Source # | |
Generic FilePathT Source # | |
Show FilePathT Source # | |
Eq FilePathT Source # | |
Ord FilePathT Source # | |
Defined in ZuulWeeder.Prelude | |
Hashable FilePathT Source # | |
Defined in ZuulWeeder.Prelude | |
From FilePathT Text Source # | |
Defined in ZuulWeeder.Prelude | |
type Rep FilePathT Source # | |
Defined in ZuulWeeder.Prelude |
listDirectory :: FilePathT -> IO [FilePathT] Source #
Wrapper for listDirectory
.
doesDirectoryExist :: FilePathT -> IO Bool Source #
Wrapper for doesDirectoryExist
readFileBS :: FilePathT -> IO ByteString Source #
Wrapper for readFile
text, bytestring
A space efficient, packed, unboxed Unicode text type.
Instances
data ByteString #
A space-efficient representation of a Word8
vector, supporting many
efficient operations.
A ByteString
contains 8-bit bytes, or by using the operations from
Data.ByteString.Char8 it can be interpreted as containing 8-bit
characters.
Instances
containers
A Map from keys k
to values a
.
The Semigroup
operation for Map
is union
, which prefers
values from the left operand. If m1
maps a key k
to a value
a1
, and m2
maps the same key to a different value a2
, then
their union m1 <> m2
maps k
to a1
.
Instances
Bifoldable Map | Since: containers-0.6.3.1 |
Eq2 Map | Since: containers-0.5.9 |
Ord2 Map | Since: containers-0.5.9 |
Defined in Data.Map.Internal | |
Show2 Map | Since: containers-0.5.9 |
Hashable2 Map | Since: hashable-1.3.4.0 |
Defined in Data.Hashable.Class | |
(FromJSONKey k, Ord k) => FromJSON1 (Map k) | |
ToJSONKey k => ToJSON1 (Map k) | |
Defined in Data.Aeson.Types.ToJSON liftToJSON :: (a -> Value) -> ([a] -> Value) -> Map k a -> Value # liftToJSONList :: (a -> Value) -> ([a] -> Value) -> [Map k a] -> Value # liftToEncoding :: (a -> Encoding) -> ([a] -> Encoding) -> Map k a -> Encoding # liftToEncodingList :: (a -> Encoding) -> ([a] -> Encoding) -> [Map k a] -> Encoding # | |
Foldable (Map k) | Folds in order of increasing key. |
Defined in Data.Map.Internal fold :: Monoid m => Map k m -> m # foldMap :: Monoid m => (a -> m) -> Map k a -> m # foldMap' :: Monoid m => (a -> m) -> Map k a -> m # foldr :: (a -> b -> b) -> b -> Map k a -> b # foldr' :: (a -> b -> b) -> b -> Map k a -> b # foldl :: (b -> a -> b) -> b -> Map k a -> b # foldl' :: (b -> a -> b) -> b -> Map k a -> b # foldr1 :: (a -> a -> a) -> Map k a -> a # foldl1 :: (a -> a -> a) -> Map k a -> a # elem :: Eq a => a -> Map k a -> Bool # maximum :: Ord a => Map k a -> a # minimum :: Ord a => Map k a -> a # | |
Eq k => Eq1 (Map k) | Since: containers-0.5.9 |
Ord k => Ord1 (Map k) | Since: containers-0.5.9 |
Defined in Data.Map.Internal | |
(Ord k, Read k) => Read1 (Map k) | Since: containers-0.5.9 |
Defined in Data.Map.Internal | |
Show k => Show1 (Map k) | Since: containers-0.5.9 |
Traversable (Map k) | Traverses in order of increasing key. |
Functor (Map k) | |
Hashable k => Hashable1 (Map k) | Since: hashable-1.3.4.0 |
Defined in Data.Hashable.Class | |
(FromJSONKey k, Ord k, FromJSON v) => FromJSON (Map k v) | |
(ToJSON v, ToJSONKey k) => ToJSON (Map k v) | |
Defined in Data.Aeson.Types.ToJSON | |
(Data k, Data a, Ord k) => Data (Map k a) | |
Defined in Data.Map.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Map k a -> c (Map k a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Map k a) # toConstr :: Map k a -> Constr # dataTypeOf :: Map k a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Map k a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Map k a)) # gmapT :: (forall b. Data b => b -> b) -> Map k a -> Map k a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Map k a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Map k a -> r # gmapQ :: (forall d. Data d => d -> u) -> Map k a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Map k a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Map k a -> m (Map k a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Map k a -> m (Map k a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Map k a -> m (Map k a) # | |
Ord k => Monoid (Map k v) | |
Ord k => Semigroup (Map k v) | |
Ord k => IsList (Map k v) | Since: containers-0.5.6.2 |
(Ord k, Read k, Read e) => Read (Map k e) | |
(Show k, Show a) => Show (Map k a) | |
(NFData k, NFData a) => NFData (Map k a) | |
Defined in Data.Map.Internal | |
(Eq k, Eq a) => Eq (Map k a) | |
(Ord k, Ord v) => Ord (Map k v) | |
(Hashable k, Hashable v) => Hashable (Map k v) | Since: hashable-1.3.4.0 |
Defined in Data.Hashable.Class | |
(Ord k, FromFormKey k, FromHttpApiData v) => FromForm (Map k [v]) | |
(ToFormKey k, ToHttpApiData v) => ToForm (Map k [v]) | |
Defined in Web.Internal.FormUrlEncoded | |
Ord k => At (Map k a) | |
Ord k => Ixed (Map k a) | |
Defined in Control.Lens.At | |
Ord k => Wrapped (Map k a) | |
(t ~ Map k' a', Ord k) => Rewrapped (Map k a) t | Use |
Defined in Control.Lens.Wrapped | |
type Item (Map k v) | |
Defined in Data.Map.Internal | |
type Index (Map k a) | |
Defined in Control.Lens.At | |
type IxValue (Map k a) | |
Defined in Control.Lens.At | |
type Unwrapped (Map k a) | |
Defined in Control.Lens.Wrapped |
A set of values a
.
Instances
ToJSON1 Set | |
Defined in Data.Aeson.Types.ToJSON | |
Foldable Set | Folds in order of increasing key. |
Defined in Data.Set.Internal fold :: Monoid m => Set m -> m # foldMap :: Monoid m => (a -> m) -> Set a -> m # foldMap' :: Monoid m => (a -> m) -> Set a -> m # foldr :: (a -> b -> b) -> b -> Set a -> b # foldr' :: (a -> b -> b) -> b -> Set a -> b # foldl :: (b -> a -> b) -> b -> Set a -> b # foldl' :: (b -> a -> b) -> b -> Set a -> b # foldr1 :: (a -> a -> a) -> Set a -> a # foldl1 :: (a -> a -> a) -> Set a -> a # elem :: Eq a => a -> Set a -> Bool # maximum :: Ord a => Set a -> a # | |
Eq1 Set | Since: containers-0.5.9 |
Ord1 Set | Since: containers-0.5.9 |
Defined in Data.Set.Internal | |
Show1 Set | Since: containers-0.5.9 |
Hashable1 Set | Since: hashable-1.3.4.0 |
Defined in Data.Hashable.Class | |
(Ord a, FromJSON a) => FromJSON (Set a) | |
ToJSON a => ToJSON (Set a) | |
Defined in Data.Aeson.Types.ToJSON | |
(Data a, Ord a) => Data (Set a) | |
Defined in Data.Set.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Set a -> c (Set a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Set a) # dataTypeOf :: Set a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Set a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Set a)) # gmapT :: (forall b. Data b => b -> b) -> Set a -> Set a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Set a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Set a -> r # gmapQ :: (forall d. Data d => d -> u) -> Set a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Set a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Set a -> m (Set a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Set a -> m (Set a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Set a -> m (Set a) # | |
Ord a => Monoid (Set a) | |
Ord a => Semigroup (Set a) | Since: containers-0.5.7 |
Ord a => IsList (Set a) | Since: containers-0.5.6.2 |
(Read a, Ord a) => Read (Set a) | |
Show a => Show (Set a) | |
NFData a => NFData (Set a) | |
Defined in Data.Set.Internal | |
Eq a => Eq (Set a) | |
Ord a => Ord (Set a) | |
Hashable v => Hashable (Set v) | Since: hashable-1.3.4.0 |
Defined in Data.Hashable.Class | |
Ord k => At (Set k) | |
Ord a => Contains (Set a) | |
Ord k => Ixed (Set k) | |
Defined in Control.Lens.At | |
Ord a => Wrapped (Set a) | |
(t ~ Set a', Ord a) => Rewrapped (Set a) t | Use |
Defined in Control.Lens.Wrapped | |
type Item (Set a) | |
Defined in Data.Set.Internal | |
type Index (Set a) | |
Defined in Control.Lens.At | |
type IxValue (Set k) | |
Defined in Control.Lens.At | |
type Unwrapped (Set a) | |
Defined in Control.Lens.Wrapped |
Non-empty, possibly infinite, multi-way trees; also known as rose trees.
Instances
FromJSON1 Tree | |
ToJSON1 Tree | |
Defined in Data.Aeson.Types.ToJSON | |
MonadFix Tree | Since: containers-0.5.11 |
MonadZip Tree | |
Foldable Tree | |
Defined in Data.Tree fold :: Monoid m => Tree m -> m # foldMap :: Monoid m => (a -> m) -> Tree a -> m # foldMap' :: Monoid m => (a -> m) -> Tree a -> m # foldr :: (a -> b -> b) -> b -> Tree a -> b # foldr' :: (a -> b -> b) -> b -> Tree a -> b # foldl :: (b -> a -> b) -> b -> Tree a -> b # foldl' :: (b -> a -> b) -> b -> Tree a -> b # foldr1 :: (a -> a -> a) -> Tree a -> a # foldl1 :: (a -> a -> a) -> Tree a -> a # elem :: Eq a => a -> Tree a -> Bool # maximum :: Ord a => Tree a -> a # | |
Eq1 Tree | Since: containers-0.5.9 |
Ord1 Tree | Since: containers-0.5.9 |
Read1 Tree | Since: containers-0.5.9 |
Show1 Tree | Since: containers-0.5.9 |
Traversable Tree | |
Applicative Tree | |
Functor Tree | |
Monad Tree | |
Hashable1 Tree | Since: hashable-1.3.4.0 |
Defined in Data.Hashable.Class | |
Generic1 Tree | |
FromJSON v => FromJSON (Tree v) | |
ToJSON v => ToJSON (Tree v) | |
Defined in Data.Aeson.Types.ToJSON | |
Data a => Data (Tree a) | |
Defined in Data.Tree gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Tree a -> c (Tree a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Tree a) # toConstr :: Tree a -> Constr # dataTypeOf :: Tree a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Tree a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Tree a)) # gmapT :: (forall b. Data b => b -> b) -> Tree a -> Tree a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Tree a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Tree a -> r # gmapQ :: (forall d. Data d => d -> u) -> Tree a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Tree a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Tree a -> m (Tree a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Tree a -> m (Tree a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Tree a -> m (Tree a) # | |
Generic (Tree a) | |
Read a => Read (Tree a) | |
Show a => Show (Tree a) | |
NFData a => NFData (Tree a) | |
Eq a => Eq (Tree a) | |
Ord a => Ord (Tree a) | Since: containers-0.6.5 |
Hashable v => Hashable (Tree v) | Since: hashable-1.3.4.0 |
Defined in Data.Hashable.Class | |
Ixed (Tree a) | |
Defined in Control.Lens.At | |
type Rep1 Tree | Since: containers-0.5.8 |
Defined in Data.Tree type Rep1 Tree = D1 ('MetaData "Tree" "Data.Tree" "containers-0.6.5.1" 'False) (C1 ('MetaCons "Node" 'PrefixI 'True) (S1 ('MetaSel ('Just "rootLabel") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) Par1 :*: S1 ('MetaSel ('Just "subForest") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) ([] :.: Rec1 Tree))) | |
type Rep (Tree a) | Since: containers-0.5.8 |
Defined in Data.Tree type Rep (Tree a) = D1 ('MetaData "Tree" "Data.Tree" "containers-0.6.5.1" 'False) (C1 ('MetaCons "Node" 'PrefixI 'True) (S1 ('MetaSel ('Just "rootLabel") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 a) :*: S1 ('MetaSel ('Just "subForest") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 [Tree a]))) | |
type Index (Tree a) | |
Defined in Control.Lens.At | |
type IxValue (Tree a) | |
Defined in Control.Lens.At |
witch
This type class is for converting values from some source
type into
some other target
type. The constraint
means that
you can convert from a value of type From
source targetsource
into a value of type
target
.
This type class is for conversions that always succeed. If your conversion
sometimes fails, consider implementing TryFrom
instead.
Instances
from :: From source target => source -> target #
This method implements the conversion of a value between types. At call
sites you may prefer to use into
instead.
-- Avoid this: from (x :: s) -- Prefer this: from @s x
The default implementation of this method simply calls coerce
,
which works for types that have the same runtime representation. This
means that for newtype
s you do not need to implement this method at
all. For example:
>>>
newtype Name = Name String
>>>
instance From Name String
>>>
instance From String Name
via :: forall through source target. (From source through, From through target) => source -> target #
This function first converts from some source
type into some through
type, and then converts that into some target
type. Usually this is used
when writing From
instances. Sometimes this can be used to work
around the lack of an instance that should probably exist.
-- Avoid this: from @u . into @u -- Prefer this: via @u
into :: forall target source. From source target => source -> target #
This is the same as from
except that the type variables are in the
opposite order.
-- Avoid this: from x :: t -- Prefer this: into @t x
unsafeFrom :: (HasCallStack, TryFrom source target, Show source, Typeable source, Typeable target) => source -> target #
This function is like tryFrom
except that it will throw an
impure exception if the conversion fails.
-- Avoid this: either throw id . tryFrom @s -- Prefer this: unsafeFrom @s
unsafeInto :: forall target source. (HasCallStack, TryFrom source target, Show source, Typeable source, Typeable target) => source -> target #
This function is like tryInto
except that it will throw an impure
exception if the conversion fails.
-- Avoid this: either throw id . tryInto @t -- Prefer this: unsafeInto @t
mtl
lift :: (MonadTrans t, Monad m) => m a -> t m a #
Lift a computation from the argument monad to the constructed monad.
type Reader r = ReaderT r Identity #
The parameterizable reader monad.
Computations are functions of a shared environment.
The return
function ignores the environment, while >>=
passes
the inherited environment to both subcomputations.
data ReaderT r (m :: Type -> Type) a #
The reader monad transformer, which adds a read-only environment to the given monad.
The return
function ignores the environment, while >>=
passes
the inherited environment to both subcomputations.
Instances
runReaderT :: ReaderT r m a -> r -> m a #
type State s = StateT s Identity #
A state monad parameterized by the type s
of the state to carry.
The return
function leaves the state unchanged, while >>=
uses
the final state of the first computation as the initial state of
the second.
data StateT s (m :: Type -> Type) a #
A state transformer monad parameterized by:
s
- The state.m
- The inner monad.
The return
function leaves the state unchanged, while >>=
uses
the final state of the first computation as the initial state of
the second.
Instances
execStateT :: Monad m => StateT s m a -> s -> m s #
Evaluate a state computation with the given initial state and return the final state, discarding the final value.
execStateT
m s =liftM
snd
(runStateT
m s)
data ExceptT e (m :: Type -> Type) a #
A monad transformer that adds exceptions to other monads.
ExceptT
constructs a monad parameterized over two things:
- e - The exception type.
- m - The inner monad.
The return
function yields a computation that produces the given
value, while >>=
sequences two subcomputations, exiting on the
first exception.
Instances
runExceptT :: ExceptT e m a -> m (Either e a) #
The inverse of ExceptT
.
throwError :: MonadError e m => e -> m a #
Is used within a monadic computation to begin exception processing.
except :: forall (m :: Type -> Type) e a. Monad m => Either e a -> ExceptT e m a #
Constructor for computations in the exception monad.
(The inverse of runExcept
).
runIdentity :: Identity a -> a #
lens
set :: 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
>>>
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
over :: 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.
>>>
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
use :: MonadState s m => Getting a s a -> m a #
Use the target of a Lens
, Iso
, or
Getter
in the current state, or use a summary of a
Fold
or Traversal
that points
to a monoidal value.
>>>
evalState (use _1) (a,b)
a
>>>
evalState (use _1) ("hello","world")
"hello"
use
::MonadState
s m =>Getter
s a -> m ause
:: (MonadState
s m,Monoid
r) =>Fold
s r -> m ruse
::MonadState
s m =>Iso'
s a -> m ause
::MonadState
s m =>Lens'
s a -> m ause
:: (MonadState
s m,Monoid
r) =>Traversal'
s r -> m r
(%=) :: MonadState s m => ASetter s s a b -> (a -> b) -> m () infix 4 #
Map over the target of a Lens
or all of the targets of a Setter
or Traversal
in our monadic state.
>>>
execState (do _1 %= f;_2 %= g) (a,b)
(f a,g b)
>>>
execState (do both %= f) (a,b)
(f a,f b)
(%=
) ::MonadState
s m =>Iso'
s a -> (a -> a) -> m () (%=
) ::MonadState
s m =>Lens'
s a -> (a -> a) -> m () (%=
) ::MonadState
s m =>Traversal'
s a -> (a -> a) -> m () (%=
) ::MonadState
s m =>Setter'
s a -> (a -> a) -> m ()
(%=
) ::MonadState
s m =>ASetter
s s a b -> (a -> b) -> m ()
aeson
A type that can be converted from JSON, with the possibility of failure.
In many cases, you can get the compiler to generate parsing code for you (see below). To begin, let's cover writing an instance by hand.
There are various reasons a conversion could fail. For example, an
Object
could be missing a required key, an Array
could be of
the wrong size, or a value could be of an incompatible type.
The basic ways to signal a failed conversion are as follows:
fail
yields a custom error message: it is the recommended way of reporting a failure;empty
(ormzero
) is uninformative: use it when the error is meant to be caught by some(
;<|>
)typeMismatch
can be used to report a failure when the encountered value is not of the expected JSON type;unexpected
is an appropriate alternative when more than one type may be expected, or to keep the expected type implicit.
prependFailure
(or modifyFailure
) add more information to a parser's
error messages.
An example type and instance using typeMismatch
and prependFailure
:
-- Allow ourselves to writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceFromJSON
Coord whereparseJSON
(Object
v) = Coord<$>
v.:
"x"<*>
v.:
"y" -- We do not expect a non-Object
value here. -- We could useempty
to fail, buttypeMismatch
-- gives a much more informative error message.parseJSON
invalid =prependFailure
"parsing Coord failed, " (typeMismatch
"Object" invalid)
For this common case of only being concerned with a single
type of JSON value, the functions withObject
, withScientific
, etc.
are provided. Their use is to be preferred when possible, since
they are more terse. Using withObject
, we can rewrite the above instance
(assuming the same language extension and data type) as:
instanceFromJSON
Coord whereparseJSON
=withObject
"Coord" $ \v -> Coord<$>
v.:
"x"<*>
v.:
"y"
Instead of manually writing your FromJSON
instance, there are two options
to do it automatically:
- Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
- The compiler can provide a default generic implementation for
parseJSON
.
To use the second, simply add a deriving
clause to your
datatype and declare a Generic
FromJSON
instance for your datatype without giving
a definition for parseJSON
.
For example, the previous example can be simplified to just:
{-# LANGUAGE DeriveGeneric #-} import GHC.Generics data Coord = Coord { x :: Double, y :: Double } derivingGeneric
instanceFromJSON
Coord
The default implementation will be equivalent to
parseJSON =
; if you need different
options, you can customize the generic decoding by defining:genericParseJSON
defaultOptions
customOptions =defaultOptions
{fieldLabelModifier
=map
toUpper
} instanceFromJSON
Coord whereparseJSON
=genericParseJSON
customOptions
Nothing
Instances
class FromJSONKey a where #
Read the docs for ToJSONKey
first. This class is a conversion
in the opposite direction. If you have a newtype wrapper around Text
,
the recommended way to define instances is with generalized newtype deriving:
newtype SomeId = SomeId { getSomeId :: Text } deriving (Eq,Ord,Hashable,FromJSONKey)
If you have a sum of nullary constructors, you may use the generic implementation:
data Color = Red | Green | Blue deriving Generic instanceFromJSONKey
Color wherefromJSONKey
=genericFromJSONKey
defaultJSONKeyOptions
Nothing
fromJSONKey :: FromJSONKeyFunction a #
Strategy for parsing the key of a map-like container.
fromJSONKeyList :: FromJSONKeyFunction [a] #
Instances
A type that can be converted to JSON.
Instances in general must specify toJSON
and should (but don't need
to) specify toEncoding
.
An example type and instance:
-- Allow ourselves to writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceToJSON
Coord wheretoJSON
(Coord x y) =object
["x".=
x, "y".=
y]toEncoding
(Coord x y) =pairs
("x".=
x<>
"y".=
y)
Instead of manually writing your ToJSON
instance, there are two options
to do it automatically:
- Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
- The compiler can provide a default generic implementation for
toJSON
.
To use the second, simply add a deriving
clause to your
datatype and declare a Generic
ToJSON
instance. If you require nothing other than
defaultOptions
, it is sufficient to write (and this is the only
alternative where the default toJSON
implementation is sufficient):
{-# LANGUAGE DeriveGeneric #-} import GHC.Generics data Coord = Coord { x :: Double, y :: Double } derivingGeneric
instanceToJSON
Coord wheretoEncoding
=genericToEncoding
defaultOptions
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions =defaultOptions
{fieldLabelModifier
=map
toUpper
} instanceToJSON
Coord wheretoJSON
=genericToJSON
customOptionstoEncoding
=genericToEncoding
customOptions
Previous versions of this library only had the toJSON
method. Adding
toEncoding
had two reasons:
- toEncoding is more efficient for the common case that the output of
toJSON
is directly serialized to aByteString
. Further, expressing either method in terms of the other would be non-optimal. - The choice of defaults allows a smooth transition for existing users:
Existing instances that do not define
toEncoding
still compile and have the correct semantics. This is ensured by making the default implementation oftoEncoding
usetoJSON
. This produces correct results, but since it performs an intermediate conversion to aValue
, it will be less efficient than directly emitting anEncoding
. (this also means that specifying nothing more thaninstance ToJSON Coord
would be sufficient as a generically decoding instance, but there probably exists no good reason to not specifytoEncoding
in new instances.)
Nothing
Convert a Haskell value to a JSON-friendly intermediate type.
toEncoding :: a -> Encoding #
Encode a Haskell value as JSON.
The default implementation of this method creates an
intermediate Value
using toJSON
. This provides
source-level compatibility for people upgrading from older
versions of this library, but obviously offers no performance
advantage.
To benefit from direct encoding, you must provide an
implementation for this method. The easiest way to do so is by
having your types implement Generic
using the DeriveGeneric
extension, and then have GHC generate a method body as follows.
instanceToJSON
Coord wheretoEncoding
=genericToEncoding
defaultOptions
toJSONList :: [a] -> Value #
toEncodingList :: [a] -> Encoding #
Instances
Typeclass for types that can be used as the key of a map-like container
(like Map
or HashMap
). For example, since Text
has a ToJSONKey
instance and Char
has a ToJSON
instance, we can encode a value of
type Map
Text
Char
:
>>>
LBC8.putStrLn $ encode $ Map.fromList [("foo" :: Text, 'a')]
{"foo":"a"}
Since Int
also has a ToJSONKey
instance, we can similarly write:
>>>
LBC8.putStrLn $ encode $ Map.fromList [(5 :: Int, 'a')]
{"5":"a"}
JSON documents only accept strings as object keys. For any type
from base
that has a natural textual representation, it can be
expected that its ToJSONKey
instance will choose that representation.
For data types that lack a natural textual representation, an alternative is provided. The map-like container is represented as a JSON array instead of a JSON object. Each value in the array is an array with exactly two values. The first is the key and the second is the value.
For example, values of type '[Text]' cannot be encoded to a
string, so a Map
with keys of type '[Text]' is encoded as follows:
>>>
LBC8.putStrLn $ encode $ Map.fromList [(["foo","bar","baz" :: Text], 'a')]
[[["foo","bar","baz"],"a"]]
The default implementation of ToJSONKey
chooses this method of
encoding a key, using the ToJSON
instance of the type.
To use your own data type as the key in a map, all that is needed
is to write a ToJSONKey
(and possibly a FromJSONKey
) instance
for it. If the type cannot be trivially converted to and from Text
,
it is recommended that ToJSONKeyValue
is used. Since the default
implementations of the typeclass methods can build this from a
ToJSON
instance, there is nothing that needs to be written:
data Foo = Foo { fooAge :: Int, fooName :: Text } deriving (Eq,Ord,Generic) instance ToJSON Foo instance ToJSONKey Foo
That's it. We can now write:
>>>
let m = Map.fromList [(Foo 4 "bar",'a'),(Foo 6 "arg",'b')]
>>>
LBC8.putStrLn $ encode m
[[{"fooName":"bar","fooAge":4},"a"],[{"fooName":"arg","fooAge":6},"b"]]
The next case to consider is if we have a type that is a
newtype wrapper around Text
. The recommended approach is to use
generalized newtype deriving:
newtype RecordId = RecordId { getRecordId :: Text } deriving (Eq,Ord,ToJSONKey)
Then we may write:
>>>
LBC8.putStrLn $ encode $ Map.fromList [(RecordId "abc",'a')]
{"abc":"a"}
Simple sum types are a final case worth considering. Suppose we have:
data Color = Red | Green | Blue deriving (Show,Read,Eq,Ord)
It is possible to get the ToJSONKey
instance for free as we did
with Foo
. However, in this case, we have a natural way to go to
and from Text
that does not require any escape sequences. So
ToJSONKeyText
can be used instead of ToJSONKeyValue
to encode maps
as objects instead of arrays of pairs. This instance may be
implemented using generics as follows:
instanceToJSONKey
Color wheretoJSONKey
=genericToJSONKey
defaultJSONKeyOptions
Low-level implementations
The Show
instance can be used to help write ToJSONKey
:
instance ToJSONKey Color where toJSONKey = ToJSONKeyText f g where f = Text.pack . show g = text . Text.pack . show -- text function is from Data.Aeson.Encoding
The situation of needing to turning function a -> Text
into
a ToJSONKeyFunction
is common enough that a special combinator
is provided for it. The above instance can be rewritten as:
instance ToJSONKey Color where toJSONKey = toJSONKeyText (Text.pack . show)
The performance of the above instance can be improved by
not using Value
as an intermediate step when converting to
Text
. One option for improving performance would be to use
template haskell machinery from the text-show
package. However,
even with the approach, the Encoding
(a wrapper around a bytestring
builder) is generated by encoding the Text
to a ByteString
,
an intermediate step that could be avoided. The fastest possible
implementation would be:
-- Assuming that OverloadedStrings is enabled instance ToJSONKey Color where toJSONKey = ToJSONKeyText f g where f x = case x of {Red -> "Red";Green ->"Green";Blue -> "Blue"} g x = case x of {Red -> text "Red";Green -> text "Green";Blue -> text "Blue"} -- text function is from Data.Aeson.Encoding
This works because GHC can lift the encoded values out of the case statements, which means that they are only evaluated once. This approach should only be used when there is a serious need to maximize performance.
Nothing
toJSONKey :: ToJSONKeyFunction a #
Strategy for rendering the key for a map-like container.
toJSONKeyList :: ToJSONKeyFunction [a] #
Instances
A JSON value represented as a Haskell value.
Instances
Arbitrary Value | Since: aeson-2.0.3.0 |
CoArbitrary Value | Since: aeson-2.0.3.0 |
Defined in Data.Aeson.Types.Internal coarbitrary :: Value -> Gen b -> Gen b # | |
Function Value | Since: aeson-2.0.3.0 |
FromJSON Value | |
FromString Encoding | |
Defined in Data.Aeson.Types.ToJSON fromString :: String -> Encoding | |
FromString Value | |
Defined in Data.Aeson.Types.ToJSON fromString :: String -> Value | |
KeyValue Object | Constructs a singleton |
KeyValue Pair | |
ToJSON Value | |
Defined in Data.Aeson.Types.ToJSON | |
Data Value | |
Defined in Data.Aeson.Types.Internal gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Value -> c Value # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Value # dataTypeOf :: Value -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Value) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Value) # gmapT :: (forall b. Data b => b -> b) -> Value -> Value # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Value -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Value -> r # gmapQ :: (forall d. Data d => d -> u) -> Value -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Value -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Value -> m Value # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Value -> m Value # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Value -> m Value # | |
IsString Value | |
Defined in Data.Aeson.Types.Internal fromString :: String -> Value # | |
Generic Value | |
Read Value | |
Show Value | Since version 1.5.6.0 version object values are printed in lexicographic key order
|
NFData Value | |
Defined in Data.Aeson.Types.Internal | |
Eq Value | |
Ord Value | The ordering is total, consistent with Since: aeson-1.5.2.0 |
Hashable Value | |
Defined in Data.Aeson.Types.Internal | |
Lift Value | Since: aeson-0.11.0.0 |
(GToJSON' Encoding arity a, ConsToJSON Encoding arity a, Constructor c) => SumToJSON' TwoElemArray Encoding arity (C1 c a) | |
Defined in Data.Aeson.Types.ToJSON | |
(GToJSON' Value arity a, ConsToJSON Value arity a, Constructor c) => SumToJSON' TwoElemArray Value arity (C1 c a) | |
Defined in Data.Aeson.Types.ToJSON | |
GToJSON' Encoding arity (U1 :: TYPE LiftedRep -> Type) | |
GToJSON' Value arity (U1 :: TYPE LiftedRep -> Type) | |
GToJSON' Value arity (V1 :: TYPE LiftedRep -> Type) | |
ToJSON1 f => GToJSON' Encoding One (Rec1 f) | |
ToJSON1 f => GToJSON' Value One (Rec1 f) | |
(EncodeProduct arity a, EncodeProduct arity b) => GToJSON' Encoding arity (a :*: b) | |
ToJSON a => GToJSON' Encoding arity (K1 i a :: TYPE LiftedRep -> Type) | |
(WriteProduct arity a, WriteProduct arity b, ProductSize a, ProductSize b) => GToJSON' Value arity (a :*: b) | |
ToJSON a => GToJSON' Value arity (K1 i a :: TYPE LiftedRep -> Type) | |
(ToJSON1 f, GToJSON' Encoding One g) => GToJSON' Encoding One (f :.: g) | |
(ToJSON1 f, GToJSON' Value One g) => GToJSON' Value One (f :.: g) | |
FromPairs Value (DList Pair) | |
Defined in Data.Aeson.Types.ToJSON | |
v ~ Value => KeyValuePair v (DList Pair) | |
Defined in Data.Aeson.Types.ToJSON | |
type Rep Value | |
Defined in Data.Aeson.Types.Internal type Rep Value = D1 ('MetaData "Value" "Data.Aeson.Types.Internal" "aeson-2.0.3.0-JsfPu3yjR3HGiW0fNjQdVR" 'False) ((C1 ('MetaCons "Object" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Object)) :+: (C1 ('MetaCons "Array" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Array)) :+: C1 ('MetaCons "String" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Text)))) :+: (C1 ('MetaCons "Number" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Scientific)) :+: (C1 ('MetaCons "Bool" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Bool)) :+: C1 ('MetaCons "Null" 'PrefixI 'False) (U1 :: Type -> Type)))) |
genericParseJSON :: (Generic a, GFromJSON Zero (Rep a)) => Options -> Value -> Parser a #
A configurable generic JSON decoder. This function applied to
defaultOptions
is used as the default for parseJSON
when the
type is an instance of Generic
.
genericToJSON :: (Generic a, GToJSON' Value Zero (Rep a)) => Options -> a -> Value #
A configurable generic JSON creator. This function applied to
defaultOptions
is used as the default for toJSON
when the type
is an instance of Generic
.
Default encoding Options
:
Options
{fieldLabelModifier
= id ,constructorTagModifier
= id ,allNullaryToStringTag
= True ,omitNothingFields
= False ,sumEncoding
=defaultTaggedObject
,unwrapUnaryRecords
= False ,tagSingleConstructors
= False ,rejectUnknownFields
= False }
omitNothingFields :: Options -> Bool #
If True
, record fields with a Nothing
value will be
omitted from the resulting object. If False
, the resulting
object will include those fields mapping to null
.
Note that this does not affect parsing: Maybe
fields are
optional regardless of the value of omitNothingFields
, subject
to the note below.
Note
Setting omitNothingFields
to True
only affects fields which are of
type Maybe
uniformly in the ToJSON
instance.
In particular, if the type of a field is declared as a type variable, it
will not be omitted from the JSON object, unless the field is
specialized upfront in the instance.
The same holds for Maybe
fields being optional in the FromJSON
instance.
Example
The generic instance for the following type Fruit
depends on whether
the instance head is Fruit a
or Fruit (Maybe a)
.
data Fruit a = Fruit { apples :: a -- A field whose type is a type variable. , oranges ::Maybe
Int } derivingGeneric
-- apples required, oranges optional -- Even iffromJSON
is then specialized to (Fruit (Maybe
a)). instanceFromJSON
a =>FromJSON
(Fruit a) -- apples optional, oranges optional -- In this instance, the field apples is uniformly of type (Maybe
a). instanceFromJSON
a =>FromJSON
(Fruit (Maybe
a)) options ::Options
options =defaultOptions
{omitNothingFields
=True
} -- apples always present in the output, oranges is omitted ifNothing
instanceToJSON
a =>ToJSON
(Fruit a) wheretoJSON
=genericToJSON
options -- both apples and oranges are omitted ifNothing
instanceToJSON
a =>ToJSON
(Fruit (Maybe
a)) wheretoJSON
=genericToJSON
options
encodeJSON :: ToJSON a => a -> ByteString Source #
decodeJSON :: FromJSON a => ByteString -> Either String a Source #
aeson helpers
A convenient wrapper to decode json value with custom error message.
Instances
Foldable Decoder Source # | |
Defined in ZuulWeeder.Prelude fold :: Monoid m => Decoder m -> m # foldMap :: Monoid m => (a -> m) -> Decoder a -> m # foldMap' :: Monoid m => (a -> m) -> Decoder a -> m # foldr :: (a -> b -> b) -> b -> Decoder a -> b # foldr' :: (a -> b -> b) -> b -> Decoder a -> b # foldl :: (b -> a -> b) -> b -> Decoder a -> b # foldl' :: (b -> a -> b) -> b -> Decoder a -> b # foldr1 :: (a -> a -> a) -> Decoder a -> a # foldl1 :: (a -> a -> a) -> Decoder a -> a # elem :: Eq a => a -> Decoder a -> Bool # maximum :: Ord a => Decoder a -> a # minimum :: Ord a => Decoder a -> a # | |
Traversable Decoder Source # | |
Applicative Decoder Source # | |
Functor Decoder Source # | |
Monad Decoder Source # | |
Show a => Show (Decoder a) Source # | |
decodeObjectAttribute :: Key -> Object -> Decoder Value Source #
Decode a json object attribute value.
decodeAsList :: Key -> (Text -> a) -> Object -> Decoder [a] Source #
Decode a json object attribute value as a list.
s :: QuasiQuoter #
QuasiQuoter for a non-interpolating IsString literal. The pattern portion is undefined.
with-utf8
withUtf8 :: (MonadIO m, MonadMask m) => m r -> m r #
Make standard handles safe to write anything to them and change program-global default file handle encoding to UTF-8.
This function will:
- Adjust the encoding of
stdin
,stdout
, andstderr
to enable transliteration, likewithStdTerminalHandles
does. - Call
setLocaleEncoding
to change the program-global locale encoding to UTF-8. - Undo everything when the wrapped action finishes.
utilities
fromEither :: Show a => Either a b -> b Source #
Die with on the Left case
base concurrent
forkIO :: IO () -> IO ThreadId #
Creates a new thread to run the IO
computation passed as the
first argument, and returns the ThreadId
of the newly created
thread.
The new thread will be a lightweight, unbound thread. Foreign calls
made by this thread are not guaranteed to be made by any particular OS
thread; if you need foreign calls to be made by a particular OS
thread, then use forkOS
instead.
The new thread inherits the masked state of the parent (see
mask
).
The newly created thread has an exception handler that discards the
exceptions BlockedIndefinitelyOnMVar
, BlockedIndefinitelyOnSTM
, and
ThreadKilled
, and passes all other exceptions to the uncaught
exception handler.
threadDelay :: Int -> IO () #
Suspends the current thread for a given number of microseconds (GHC only).
There is no guarantee that the thread will be rescheduled promptly when the delay has expired, but the thread will never continue to run earlier than specified.
A mutable variable in the IO
monad
writeIORef :: IORef a -> a -> IO () #
Write a new value into an IORef
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.
modifyMVar :: MVar a -> (a -> IO (a, b)) -> IO b #
A slight variation on modifyMVar_
that allows a value to be
returned (b
) in addition to the modified value of the MVar
.
base list
\(\mathcal{O}(n^2)\). The nub
function removes duplicate elements from a
list. In particular, it keeps only the first occurrence of each element. (The
name nub
means `essence'.) It is a special case of nubBy
, which allows
the programmer to supply their own equality test.
>>>
nub [1,2,3,4,3,2,1,2,4,3,5]
[1,2,3,4,5]
Non-empty (and non-strict) list type.
Since: base-4.9.0.0
Instances
base data
64-bit signed integer type
Instances
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,
is a safer alternative to the
Proxy
:: Proxy
a
idiom.undefined
:: a
>>>
Proxy :: Proxy (Void, Int -> Int)
Proxy
Proxy can even hold types of higher kinds,
>>>
Proxy :: Proxy Either
Proxy
>>>
Proxy :: Proxy Functor
Proxy
>>>
Proxy :: Proxy complicatedStructure
Proxy
Instances
Generic1 (Proxy :: k -> Type) | |
Representable (Proxy :: Type -> Type) | |
FromJSON1 (Proxy :: Type -> Type) | |
ToJSON1 (Proxy :: TYPE LiftedRep -> Type) | |
Defined in Data.Aeson.Types.ToJSON liftToJSON :: (a -> Value) -> ([a] -> Value) -> Proxy a -> Value # liftToJSONList :: (a -> Value) -> ([a] -> Value) -> [Proxy a] -> Value # liftToEncoding :: (a -> Encoding) -> ([a] -> Encoding) -> Proxy a -> Encoding # liftToEncodingList :: (a -> Encoding) -> ([a] -> Encoding) -> [Proxy a] -> Encoding # | |
Foldable (Proxy :: TYPE LiftedRep -> Type) | Since: base-4.7.0.0 |
Defined in Data.Foldable fold :: Monoid m => Proxy m -> m # foldMap :: Monoid m => (a -> m) -> Proxy a -> m # foldMap' :: Monoid m => (a -> m) -> Proxy a -> m # foldr :: (a -> b -> b) -> b -> Proxy a -> b # foldr' :: (a -> b -> b) -> b -> Proxy a -> b # foldl :: (b -> a -> b) -> b -> Proxy a -> b # foldl' :: (b -> a -> b) -> b -> Proxy a -> b # foldr1 :: (a -> a -> a) -> Proxy a -> a # foldl1 :: (a -> a -> a) -> Proxy a -> a # elem :: Eq a => a -> Proxy a -> Bool # maximum :: Ord a => Proxy a -> a # minimum :: Ord a => Proxy a -> a # | |
Eq1 (Proxy :: Type -> Type) | Since: base-4.9.0.0 |
Ord1 (Proxy :: Type -> Type) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
Read1 (Proxy :: Type -> Type) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
Show1 (Proxy :: TYPE LiftedRep -> Type) | Since: base-4.9.0.0 |
Traversable (Proxy :: Type -> Type) | Since: base-4.7.0.0 |
Alternative (Proxy :: Type -> Type) | Since: base-4.9.0.0 |
Applicative (Proxy :: Type -> Type) | Since: base-4.7.0.0 |
Functor (Proxy :: Type -> Type) | Since: base-4.7.0.0 |
Monad (Proxy :: Type -> Type) | Since: base-4.7.0.0 |
MonadPlus (Proxy :: Type -> Type) | Since: base-4.9.0.0 |
Hashable1 (Proxy :: Type -> Type) | |
Defined in Data.Hashable.Class | |
FromJSON (Proxy a) | |
ToJSON (Proxy a) | |
Defined in Data.Aeson.Types.ToJSON | |
Monoid (Proxy s) | Since: base-4.7.0.0 |
Semigroup (Proxy s) | Since: base-4.9.0.0 |
Bounded (Proxy t) | Since: base-4.7.0.0 |
Enum (Proxy s) | Since: base-4.7.0.0 |
Generic (Proxy t) | |
Ix (Proxy s) | Since: base-4.7.0.0 |
Defined in Data.Proxy | |
Read (Proxy t) | Since: base-4.7.0.0 |
Show (Proxy s) | Since: base-4.7.0.0 |
Eq (Proxy s) | Since: base-4.7.0.0 |
Ord (Proxy s) | Since: base-4.7.0.0 |
Hashable (Proxy a) | |
Defined in Data.Hashable.Class | |
type Rep1 (Proxy :: k -> Type) | Since: base-4.6.0.0 |
type Rep (Proxy :: Type -> Type) | |
type Rep (Proxy t) | Since: base-4.6.0.0 |
Case analysis for the Bool
type.
evaluates to bool
x y px
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 pif 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
traverse_ :: (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:
>>>
traverse_ print ["Hello", "world", "!"]
"Hello" "world" "!"
foldl' :: Foldable t => (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
Since: base-4.6.0.0
catMaybes :: [Maybe a] -> [a] #
The catMaybes
function takes a list of Maybe
s and returns
a list of all the Just
values.
Examples
Basic usage:
>>>
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):
>>>
import 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]
mapMaybe :: (a -> Maybe b) -> [a] -> [b] #
The mapMaybe
function is a version of map
which can throw
out elements. In particular, the functional argument returns
something of type
. If this is Maybe
bNothing
, no element
is added on to the result list. If it is
, then Just
bb
is
included in the result list.
Examples
Using
is a shortcut for mapMaybe
f x
in most cases:catMaybes
$ map
f x
>>>
import Text.Read ( readMaybe )
>>>
let readMaybeInt = readMaybe :: String -> Maybe Int
>>>
mapMaybe readMaybeInt ["1", "Foo", "3"]
[1,3]>>>
catMaybes $ map readMaybeInt ["1", "Foo", "3"]
[1,3]
If we map the Just
constructor, the entire list should be returned:
>>>
mapMaybe Just [1,2,3]
[1,2,3]
fromMaybe :: 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:
>>>
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
fromRight :: b -> Either a b -> b #
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
base control
foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b #
The foldM
function is analogous to foldl
, except that its result is
encapsulated in a monad. Note that foldM
works from left-to-right over
the list arguments. This could be an issue where (
and the `folded
function' are not commutative.>>
)
foldM f a1 [x1, x2, ..., xm] == do a2 <- f a1 x1 a3 <- f a2 x2 ... f am xm
If right-to-left evaluation is required, the input list should be reversed.
unless :: Applicative f => Bool -> f () -> f () #
The reverse of when
.
when :: Applicative f => Bool -> f () -> f () #
Conditional execution of Applicative
expressions. For example,
when debug (putStrLn "Debugging")
will output the string Debugging
if the Boolean value debug
is True
, and otherwise do nothing.
void :: Functor f => f a -> f () #
discards or ignores the result of evaluation, such
as the return value of an void
valueIO
action.
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
liftIO :: MonadIO m => IO a -> m a #
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
, we would have ended up with this error:liftIO
• 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
and returns an IO
a(m a)
:
,
enabling us to run the program and see the expected results:liftIO
> evalStateT printState "hello" "hello" > evalStateT printState 3 3
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 #
Left-to-right composition of Kleisli arrows.
'(bs
' can be understood as the >=>
cs) ado
expression
do b <- bs a cs b
(<|>) :: Alternative f => f a -> f a -> f a infixl 3 #
An associative binary operation
base debug
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.
>>>
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.
printf :: PrintfType r => String -> r #
Format a variable number of arguments with the C-style formatting string.
>>>
printf "%s, %d, %.4f" "hello" 123 pi
hello, 123, 3.1416
The return value is either String
or (
(which
should be IO
a)(
, but Haskell's type system
makes this hard).IO
())
The format string consists of ordinary characters and
conversion specifications, which specify how to format
one of the arguments to printf
in the output string. A
format specification is introduced by the %
character;
this character can be self-escaped into the format string
using %%
. A format specification ends with a
format character that provides the primary information about
how to format the value. The rest of the conversion
specification is optional. In order, one may have flag
characters, a width specifier, a precision specifier, and
type-specific modifier characters.
Unlike C printf(3)
, the formatting of this printf
is driven by the argument type; formatting is type specific. The
types formatted by printf
"out of the box" are:
printf
is also extensible to support other types: see below.
A conversion specification begins with the
character %
, followed by zero or more of the following flags:
- left adjust (default is right adjust) + always use a sign (+ or -) for signed conversions space leading space for positive numbers in signed conversions 0 pad with zeros rather than spaces # use an \"alternate form\": see below
When both flags are given, -
overrides 0
and +
overrides space.
A negative width specifier in a *
conversion is treated as
positive but implies the left adjust flag.
The "alternate form" for unsigned radix conversions is
as in C printf(3)
:
%o prefix with a leading 0 if needed %x prefix with a leading 0x if nonzero %X prefix with a leading 0X if nonzero %b prefix with a leading 0b if nonzero %[eEfFgG] ensure that the number contains a decimal point
Any flags are followed optionally by a field width:
num field width * as num, but taken from argument list
The field width is a minimum, not a maximum: it will be expanded as needed to avoid mutilating a value.
Any field width is followed optionally by a precision:
.num precision . same as .0 .* as num, but taken from argument list
Negative precision is taken as 0. The meaning of the precision depends on the conversion type.
Integral minimum number of digits to show RealFloat number of digits after the decimal point String maximum number of characters
The precision for Integral types is accomplished by zero-padding. If both precision and zero-pad are given for an Integral field, the zero-pad is ignored.
Any precision is followed optionally for Integral types by a width modifier; the only use of this modifier being to set the implicit size of the operand for conversion of a negative operand to unsigned:
hh Int8 h Int16 l Int32 ll Int64 L Int64
The specification ends with a format character:
c character Integral d decimal Integral o octal Integral x hexadecimal Integral X hexadecimal Integral b binary Integral u unsigned decimal Integral f floating point RealFloat F floating point RealFloat g general format float RealFloat G general format float RealFloat e exponent format float RealFloat E exponent format float RealFloat s string String v default format any type
The "%v" specifier is provided for all built-in types, and should be provided for user-defined type formatters as well. It picks a "best" representation for the given type. For the built-in types the "%v" specifier is converted as follows:
c Char u other unsigned Integral d other signed Integral g RealFloat s String
Mismatch between the argument types and the format string, as well as any other syntactic or semantic errors in the format string, will cause an exception to be thrown at runtime.
Note that the formatting for RealFloat
types is
currently a bit different from that of C printf(3)
,
conforming instead to showEFloat
,
showFFloat
and showGFloat
(and their
alternate versions showFFloatAlt
and
showGFloatAlt
). This is hard to fix: the fixed
versions would format in a backward-incompatible way.
In any case the Haskell behavior is generally more
sensible than the C behavior. A brief summary of some
key differences:
- Haskell
printf
never uses the default "6-digit" precision used by C printf. - Haskell
printf
treats the "precision" specifier as indicating the number of digits after the decimal point. - Haskell
printf
prints the exponent of e-format numbers without a gratuitous plus sign, and with the minimum possible number of digits. - Haskell
printf
will place a zero after a decimal point when possible.
type HasCallStack = ?callStack :: CallStack #
Request a CallStack.
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.
Since: base-4.9.0.0
base system
showVersion :: Version -> String #
Provides one possible concrete representation for Version
. For
a version with versionBranch
= [1,2,3]
and versionTags
= ["tag1","tag2"]
, the output will be 1.2.3-tag1-tag2
.
lookupEnv :: String -> IO (Maybe String) #
Return the value of the environment variable var
, or Nothing
if
there is no such value.
For POSIX users, this is equivalent to getEnv
.
Since: base-4.6.0.0
Computation getArgs
returns a list of the program's command
line arguments (not including the program name).
timeout :: Int -> IO a -> IO (Maybe a) #
Wrap an IO
computation to time out and return Nothing
in case no result
is available within n
microseconds (1/10^6
seconds). In case a result
is available before the timeout expires, Just a
is returned. A negative
timeout interval means "wait indefinitely". When specifying long timeouts,
be careful not to exceed maxBound :: Int
.
>>>
timeout 1000000 (threadDelay 1000 *> pure "finished on time")
Just "finished on time"
>>>
timeout 10000 (threadDelay 100000 *> pure "finished on time")
Nothing
The design of this combinator was guided by the objective that timeout n f
should behave exactly the same as f
as long as f
doesn't time out. This
means that f
has the same myThreadId
it would have without the timeout
wrapper. Any exceptions f
might throw cancel the timeout and propagate
further up. It also possible for f
to receive exceptions thrown to it by
another thread.
A tricky implementation detail is the question of how to abort an IO
computation. This combinator relies on asynchronous exceptions internally
(namely throwing the computation the Timeout
exception). The technique
works very well for computations executing inside of the Haskell runtime
system, but it doesn't work at all for non-Haskell code. Foreign function
calls, for example, cannot be timed out with this combinator simply because
an arbitrary C function cannot receive asynchronous exceptions. When
timeout
is used to wrap an FFI call that blocks, no timeout event can be
delivered until the FFI call returns, which pretty much negates the purpose
of the combinator. In practice, however, this limitation is less severe than
it may sound. Standard I/O functions like hGetBuf
,
hPutBuf
, Network.Socket.accept, or hWaitForInput
appear to be blocking, but they really don't because the runtime system uses
scheduling mechanisms like select(2)
to perform asynchronous I/O, so it
is possible to interrupt standard socket I/O or file I/O using this
combinator.
hashable
hash :: Hashable a => a -> Int #
Like hashWithSalt
, but no salt is used. The default
implementation uses hashWithSalt
with some default salt.
Instances might want to implement this method to provide a more
efficient implementation than the default implementation.
The class of types that can be converted to a hash value.
Minimal implementation: hashWithSalt
.
Note: the hash is not guaranteed to be stable across library versions, operating systems or architectures. For stable hashing use named hashes: SHA256, CRC32 etc.
If you are looking for Hashable
instance in time
package,
check time-compat
Instances
base
module Prelude
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