| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
Yam.Import
Contents
- data Text :: *
- pack :: String -> Text
- cs :: ConvertibleStrings a b => a -> b
- showText :: Show a => a -> Text
- lift :: MonadTrans t => forall (m :: * -> *) a. Monad m => m a -> t m a
- join :: Monad m => m (m a) -> m a
- class Monad m => MonadIO (m :: * -> *) where
- liftIO :: MonadIO m => forall a. IO a -> m a
- when :: Applicative f => Bool -> f () -> f ()
- unless :: Applicative f => Bool -> f () -> f ()
- forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
- void :: Functor f => f a -> f ()
- (<>) :: Monoid m => m -> m -> m
- myThreadId :: IO ThreadId
- data ThreadId :: *
- killThread :: ThreadId -> IO ()
- fromMaybe :: a -> Maybe a -> a
- maybe :: b -> (a -> b) -> Maybe a -> b
- mapMaybe :: (a -> Maybe b) -> [a] -> [b]
- catMaybes :: [Maybe a] -> [a]
- selectMaybe :: [Maybe a] -> Maybe a
- mergeMaybe :: Monoid a => Maybe a -> Maybe a -> Maybe a
- isNothing :: Maybe a -> Bool
- isJust :: Maybe a -> Bool
- finally :: MonadMask m => m a -> m b -> m a
- class MonadCatch m => MonadMask (m :: * -> *)
- class Monad m => MonadThrow (m :: * -> *)
- class MonadThrow m => MonadCatch (m :: * -> *)
- catchAll :: MonadCatch m => m a -> (SomeException -> m a) -> m a
- throwM :: (Exception e, HasCallStack, MonadThrow m) => e -> m a
- runReaderT :: ReaderT k r m a -> r -> m a
- data ReaderT k r (m :: k -> *) (a :: k) :: forall k. * -> (k -> *) -> k -> *
- ask :: Monad m => ReaderT * r m r
- class Generic a
- data UTCTime :: *
- addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime
- fromTime :: Text -> UTCTime -> IO Text
- millisToUTC :: Integer -> UTCTime
- randomHex :: Int -> IO Text
- data Proxy k (t :: k) :: forall k. k -> * = Proxy
- encodeToText :: ToJSON e => e -> Text
- class FromJSON a where
- class ToJSON a where
- typeMismatch :: String -> Value -> Parser a
- decode :: FromJSON a => ByteString -> Maybe a
- class Default a where
- class MonadBase b m => MonadBaseControl (b :: * -> *) (m :: * -> *) | m -> b
- class (Typeable * e, Show e) => Exception e
Documentation
A space efficient, packed, unboxed Unicode text type.
Instances
cs :: ConvertibleStrings a b => a -> b #
lift :: MonadTrans t => forall (m :: * -> *) a. Monad m => m a -> t m a #
Lift a computation from the argument monad to the constructed monad.
join :: 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.
class Monad m => MonadIO (m :: * -> *) where #
Monads in which IO computations may be embedded.
Any monad built by applying a sequence of monad transformers to the
IO monad will be an instance of this class.
Instances should satisfy the following laws, which state that liftIO
is a transformer of monads:
Minimal complete definition
Instances
| MonadIO IO | Since: 4.9.0.0 |
| MonadIO Acquire | |
| MonadIO m => MonadIO (MaybeT m) | |
| MonadIO m => MonadIO (ListT m) | |
| MonadIO m => MonadIO (NoLoggingT m) | |
| MonadIO m => MonadIO (LoggingT m) | |
| MonadIO m => MonadIO (ResourceT m) | |
| (Monoid w, MonadIO m) => MonadIO (WriterT w m) | |
| (Monoid w, MonadIO m) => MonadIO (WriterT w m) | |
| MonadIO m => MonadIO (StateT s m) | |
| MonadIO m => MonadIO (StateT s m) | |
| (Error e, MonadIO m) => MonadIO (ErrorT e m) | |
| MonadIO m => MonadIO (ExceptT e m) | |
| MonadIO m => MonadIO (IdentityT * m) | |
| MonadIO m => MonadIO (ReaderT * r m) | |
| MonadIO m => MonadIO (ConduitM i o m) | |
| MonadIO m => MonadIO (ContT * r m) | |
| (Monoid w, MonadIO m) => MonadIO (RWST r w s m) | |
| (Monoid w, MonadIO m) => MonadIO (RWST r w s m) | |
| MonadIO m => MonadIO (Pipe l i o u m) | |
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.
unless :: Applicative f => Bool -> f () -> f () #
The reverse of when.
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 NothingNothing>>>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
myThreadId :: IO ThreadId #
Returns the ThreadId of the calling thread (GHC only).
A ThreadId is an abstract type representing a handle to a thread.
ThreadId is an instance of Eq, Ord and Show, where
the Ord instance implements an arbitrary total ordering over
ThreadIds. The Show instance lets you convert an arbitrary-valued
ThreadId to string form; showing a ThreadId value is occasionally
useful when debugging or diagnosing the behaviour of a concurrent
program.
Note: in GHC, if you have a ThreadId, you essentially have
a pointer to the thread itself. This means the thread itself can't be
garbage collected until you drop the ThreadId.
This misfeature will hopefully be corrected at a later date.
killThread :: ThreadId -> IO () #
killThread raises the ThreadKilled exception in the given
thread (GHC only).
killThread tid = throwTo tid ThreadKilled
fromMaybe :: a -> Maybe a -> a #
The fromMaybe function takes a default value and and Maybe
value. If the Maybe is Nothing, it returns the default values;
otherwise, it returns the value contained in the Maybe.
Examples
Basic usage:
>>>fromMaybe "" (Just "Hello, World!")"Hello, World!"
>>>fromMaybe "" Nothing""
Read an integer from a string using readMaybe. If we fail to
parse an integer, we want to return 0 by default:
>>>import Text.Read ( readMaybe )>>>fromMaybe 0 (readMaybe "5")5>>>fromMaybe 0 (readMaybe "")0
maybe :: b -> (a -> b) -> Maybe a -> b #
The maybe function takes a default value, a function, and a Maybe
value. If the Maybe value is Nothing, the function returns the
default value. Otherwise, it applies the function to the value inside
the Just and returns the result.
Examples
Basic usage:
>>>maybe False odd (Just 3)True
>>>maybe False odd NothingFalse
Read an integer from a string using readMaybe. If we succeed,
return twice the integer; that is, apply (*2) to it. If instead
we fail to parse an integer, return 0 by default:
>>>import Text.Read ( readMaybe )>>>maybe 0 (*2) (readMaybe "5")10>>>maybe 0 (*2) (readMaybe "")0
Apply show to a Maybe Int. If we have Just n, we want to show
the underlying Int n. But if we have Nothing, we return the
empty string instead of (for example) "Nothing":
>>>maybe "" show (Just 5)"5">>>maybe "" show Nothing""
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]
catMaybes :: [Maybe a] -> [a] #
The catMaybes function takes a list of Maybes 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]
selectMaybe :: [Maybe a] -> Maybe a Source #
finally :: MonadMask m => m a -> m b -> m a #
Perform an action with a finalizer action that is run, even if an exception occurs.
class MonadCatch m => MonadMask (m :: * -> *) #
A class for monads which provide for the ability to account for all
possible exit points from a computation, and to mask asynchronous
exceptions. Continuation-based monads, and stacks such as ErrorT e IO
which provide for multiple failure modes, are invalid instances of this
class.
Note that this package does provide a MonadMask instance for CatchT.
This instance is only valid if the base monad provides no ability to
provide multiple exit. For example, IO or Either would be invalid base
monads, but Reader or State would be acceptable.
Instances should ensure that, in the following code:
f `finally` g
The action g is called regardless of what occurs within f, including
async exceptions.
Minimal complete definition
Instances
| MonadMask IO | |
| (~) * e SomeException => MonadMask (Either e) | Since: 0.8.3 |
| MonadMask m => MonadMask (NoLoggingT m) | |
| MonadMask m => MonadMask (LoggingT m) | |
| MonadMask m => MonadMask (ResourceT m) | |
| (MonadMask m, Monoid w) => MonadMask (WriterT w m) | |
| (MonadMask m, Monoid w) => MonadMask (WriterT w m) | |
| MonadMask m => MonadMask (StateT s m) | |
| MonadMask m => MonadMask (StateT s m) | |
| MonadMask m => MonadMask (IdentityT * m) | |
| MonadMask m => MonadMask (ReaderT * r m) | |
| (MonadMask m, Monoid w) => MonadMask (RWST r w s m) | |
| (MonadMask m, Monoid w) => MonadMask (RWST r w s m) | |
class Monad m => MonadThrow (m :: * -> *) #
A class for monads in which exceptions may be thrown.
Instances should obey the following law:
throwM e >> x = throwM e
In other words, throwing an exception short-circuits the rest of the monadic computation.
Minimal complete definition
Instances
class MonadThrow m => MonadCatch (m :: * -> *) #
A class for monads which allow exceptions to be caught, in particular
exceptions which were thrown by throwM.
Instances should obey the following law:
catch (throwM e) f = f e
Note that the ability to catch an exception does not guarantee that we can
deal with all possible exit points from a computation. Some monads, such as
continuation-based stacks, allow for more than just a success/failure
strategy, and therefore catch cannot be used by those monads to properly
implement a function such as finally. For more information, see
MonadMask.
Minimal complete definition
Instances
| MonadCatch IO | |
| MonadCatch STM | |
| (~) * e SomeException => MonadCatch (Either e) | Since: 0.8.3 |
| MonadCatch m => MonadCatch (MaybeT m) | Catches exceptions from the base monad. |
| MonadCatch m => MonadCatch (ListT m) | |
| MonadCatch m => MonadCatch (NoLoggingT m) | |
| MonadCatch m => MonadCatch (LoggingT m) | |
| MonadCatch m => MonadCatch (ResourceT m) | |
| (MonadCatch m, Monoid w) => MonadCatch (WriterT w m) | |
| (MonadCatch m, Monoid w) => MonadCatch (WriterT w m) | |
| MonadCatch m => MonadCatch (StateT s m) | |
| MonadCatch m => MonadCatch (StateT s m) | |
| (Error e, MonadCatch m) => MonadCatch (ErrorT e m) | Catches exceptions from the base monad. |
| MonadCatch m => MonadCatch (ExceptT e m) | Catches exceptions from the base monad. |
| MonadCatch m => MonadCatch (IdentityT * m) | |
| MonadCatch m => MonadCatch (ReaderT * r m) | |
| MonadCatch m => MonadCatch (ConduitM i o m) | |
| (MonadCatch m, Monoid w) => MonadCatch (RWST r w s m) | |
| (MonadCatch m, Monoid w) => MonadCatch (RWST r w s m) | |
| MonadCatch m => MonadCatch (Pipe l i o u m) | |
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.
throwM :: (Exception e, HasCallStack, MonadThrow m) => e -> m a Source #
runReaderT :: ReaderT k r m a -> r -> m a #
data ReaderT k r (m :: k -> *) (a :: k) :: forall k. * -> (k -> *) -> k -> * #
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
| MonadBaseControl b m => MonadBaseControl b (ReaderT * r m) | |
| MonadBase b m => MonadBase b (ReaderT * r m) | |
| MonadTrans (ReaderT * r) | |
| MonadTransControl (ReaderT * r) | |
| Monad m => Monad (ReaderT * r m) | |
| Functor m => Functor (ReaderT * r m) | |
| MonadFix m => MonadFix (ReaderT * r m) | |
| MonadFail m => MonadFail (ReaderT * r m) | |
| Applicative m => Applicative (ReaderT * r m) | |
| Alternative m => Alternative (ReaderT * r m) | |
| MonadPlus m => MonadPlus (ReaderT * r m) | |
| MonadZip m => MonadZip (ReaderT * r m) | |
| MonadIO m => MonadIO (ReaderT * r m) | |
| MonadThrow m => MonadThrow (ReaderT * r m) | |
| MonadCatch m => MonadCatch (ReaderT * r m) | |
| MonadMask m => MonadMask (ReaderT * r m) | |
| MonadLogger m => MonadLogger (ReaderT * r m) | |
| MonadLoggerIO m => MonadLoggerIO (ReaderT * r m) | |
| PrimMonad m => PrimMonad (ReaderT * r m) | |
| MonadResource m => MonadResource (ReaderT * r m) | |
| MonadIO m => MonadYamLogger (ReaderT * LoggerConfig m) Source # | |
| type StT (ReaderT * r) a | |
| type PrimState (ReaderT * r m) | |
| type StM (ReaderT * r m) a | |
Representable types of kind *. This class is derivable in GHC with the DeriveGeneric flag on.
Instances
This is the simplest representation of UTC. It consists of the day number, and a time offset from midnight. Note that if a day has a leap second added to it, it will have 86401 seconds.
addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime #
addUTCTime a b = a + b
millisToUTC :: Integer -> UTCTime Source #
data Proxy k (t :: k) :: forall k. k -> * #
A concrete, poly-kinded proxy type
Constructors
| Proxy |
Instances
| Generic1 k (Proxy k) | |
| Monad (Proxy *) | Since: 4.7.0.0 |
| Functor (Proxy *) | Since: 4.7.0.0 |
| Applicative (Proxy *) | Since: 4.7.0.0 |
| Foldable (Proxy *) | Since: 4.7.0.0 |
| Traversable (Proxy *) | Since: 4.7.0.0 |
| ToJSON1 (Proxy *) | |
| FromJSON1 (Proxy *) | |
| Alternative (Proxy *) | Since: 4.9.0.0 |
| MonadPlus (Proxy *) | Since: 4.9.0.0 |
| Eq1 (Proxy *) | Since: 4.9.0.0 |
| Ord1 (Proxy *) | Since: 4.9.0.0 |
| Read1 (Proxy *) | Since: 4.9.0.0 |
| Show1 (Proxy *) | Since: 4.9.0.0 |
| Hashable1 (Proxy *) | |
| Bounded (Proxy k t) | |
| Enum (Proxy k s) | Since: 4.7.0.0 |
| Eq (Proxy k s) | Since: 4.7.0.0 |
| Ord (Proxy k s) | Since: 4.7.0.0 |
| Read (Proxy k s) | Since: 4.7.0.0 |
| Show (Proxy k s) | Since: 4.7.0.0 |
| Ix (Proxy k s) | Since: 4.7.0.0 |
| Generic (Proxy k t) | |
| Semigroup (Proxy k s) | Since: 4.9.0.0 |
| Monoid (Proxy k s) | Since: 4.7.0.0 |
| Hashable (Proxy k a) | |
| ToJSON (Proxy k a) | |
| FromJSON (Proxy k a) | |
| type Rep1 k (Proxy k) | |
| type Rep (Proxy k t) | |
encodeToText :: ToJSON e => e -> Text Source #
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:
emptyandmzerowork, but are terse and uninformative;failyields a custom error message;typeMismatchproduces an informative message for cases when the value encountered is not of the expected type.
An example type and instance using typeMismatch:
-- Allow ourselves to writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceFromJSONCoord whereparseJSON(Objectv) = Coord<$>v.:"x"<*>v.:"y" -- We do not expect a non-Objectvalue here. -- We could usemzeroto fail, buttypeMismatch-- gives a much more informative error message.parseJSONinvalid =typeMismatch"Coord" invalid
For this common case of only being concerned with a single
type of JSON value, the functions withObject, withNumber, 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:
instanceFromJSONCoord 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 GenericFromJSON 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 } deriving Generic
instance FromJSON 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=maptoUpper} instanceFromJSONCoord whereparseJSON=genericParseJSONcustomOptions
Instances
| FromJSON Bool | |
| FromJSON Char | |
| FromJSON Double | |
| FromJSON Float | |
| FromJSON Int | |
| FromJSON Int8 | |
| FromJSON Int16 | |
| FromJSON Int32 | |
| FromJSON Int64 | |
| FromJSON Integer | WARNING: Only parse Integers from trusted input since an
attacker could easily fill up the memory of the target system by
specifying a scientific number with a big exponent like
|
| FromJSON Natural | |
| FromJSON Ordering | |
| FromJSON Word | |
| FromJSON Word8 | |
| FromJSON Word16 | |
| FromJSON Word32 | |
| FromJSON Word64 | |
| FromJSON () | |
| FromJSON Scientific | |
| FromJSON Number | |
| FromJSON Text | |
| FromJSON UTCTime | |
| FromJSON Value | |
| FromJSON DotNetTime | |
| FromJSON Text | |
| FromJSON Version | |
| FromJSON CTime | |
| FromJSON IntSet | |
| FromJSON PersistValue | |
| FromJSON SqliteConf | |
| FromJSON SqliteConnectionInfo | |
| FromJSON ZonedTime | Supported string formats:
The first space may instead be a |
| FromJSON LocalTime | |
| FromJSON TimeOfDay | |
| FromJSON NominalDiffTime | WARNING: Only parse lengths of time from trusted input
since an attacker could easily fill up the memory of the target
system by specifying a scientific number with a big exponent like
|
| FromJSON DiffTime | WARNING: Only parse lengths of time from trusted input
since an attacker could easily fill up the memory of the target
system by specifying a scientific number with a big exponent like
|
| FromJSON Day | |
| FromJSON UUID | |
| FromJSON LogRank # | |
| FromJSON DataSource # | |
| FromJSON RunMode # | |
| FromJSON a => FromJSON [a] | |
| FromJSON a => FromJSON (Maybe a) | |
| (FromJSON a, Integral a) => FromJSON (Ratio a) | |
| HasResolution a => FromJSON (Fixed a) | WARNING: Only parse fixed-precision numbers from trusted input
since an attacker could easily fill up the memory of the target
system by specifying a scientific number with a big exponent like
|
| FromJSON a => FromJSON (Min a) | |
| FromJSON a => FromJSON (Max a) | |
| FromJSON a => FromJSON (First a) | |
| FromJSON a => FromJSON (Last a) | |
| FromJSON a => FromJSON (WrappedMonoid a) | |
| FromJSON a => FromJSON (Option a) | |
| FromJSON a => FromJSON (NonEmpty a) | |
| FromJSON a => FromJSON (Identity a) | |
| FromJSON a => FromJSON (Dual a) | |
| FromJSON a => FromJSON (First a) | |
| FromJSON a => FromJSON (Last a) | |
| FromJSON a => FromJSON (IntMap a) | |
| FromJSON v => FromJSON (Tree v) | |
| FromJSON a => FromJSON (Seq a) | |
| (Ord a, FromJSON a) => FromJSON (Set a) | |
| FromJSON a => FromJSON (DList a) | |
| (Eq a, Hashable a, FromJSON a) => FromJSON (HashSet a) | |
| (Vector Vector a, FromJSON a) => FromJSON (Vector a) | |
| (Storable a, FromJSON a) => FromJSON (Vector a) | |
| (Prim a, FromJSON a) => FromJSON (Vector a) | |
| FromJSON a => FromJSON (Vector a) | |
| (FromJSON a, FromJSON b) => FromJSON (Either a b) | |
| (FromJSON a, FromJSON b) => FromJSON (a, b) | |
| (FromJSON v, FromJSONKey k, Eq k, Hashable k) => FromJSON (HashMap k v) | |
| (FromJSONKey k, Ord k, FromJSON v) => FromJSON (Map k v) | |
| FromJSON (Proxy k a) | |
| (FromJSON a, FromJSON b, FromJSON c) => FromJSON (a, b, c) | |
| FromJSON a => FromJSON (Const k a b) | |
| FromJSON b => FromJSON (Tagged k a b) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d) => FromJSON (a, b, c, d) | |
| (FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Product * f g a) | |
| (FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Sum * f g a) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e) => FromJSON (a, b, c, d, e) | |
| (FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Compose * * f g a) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f) => FromJSON (a, b, c, d, e, f) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g) => FromJSON (a, b, c, d, e, f, g) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h) => FromJSON (a, b, c, d, e, f, g, h) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i) => FromJSON (a, b, c, d, e, f, g, h, i) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j) => FromJSON (a, b, c, d, e, f, g, h, i, j) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k) => FromJSON (a, b, c, d, e, f, g, h, i, j, k) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m, FromJSON n) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n) | |
| (FromJSON a, FromJSON b, FromJSON c, FromJSON d, FromJSON e, FromJSON f, FromJSON g, FromJSON h, FromJSON i, FromJSON j, FromJSON k, FromJSON l, FromJSON m, FromJSON n, FromJSON o) => FromJSON (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) | |
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 writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceToJSONCoord 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 GenericToJSON 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 } deriving Generic
instance ToJSON Coord where
toEncoding = genericToEncoding defaultOptions
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions =defaultOptions{fieldLabelModifier=maptoUpper} instanceToJSONCoord wheretoJSON=genericToJSONcustomOptionstoEncoding=genericToEncodingcustomOptions
Previous versions of this library only had the toJSON method. Adding
toEncoding had to reasons:
- toEncoding is more efficient for the common case that the output of
toJSONis 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
toEncodingstill compile and have the correct semantics. This is ensured by making the default implementation oftoEncodingusetoJSON. 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 Coordwould be sufficient as a generically decoding instance, but there probably exists no good reason to not specifytoEncodingin new instances.)
Methods
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.
instanceToJSONCoord wheretoEncoding=genericToEncodingdefaultOptions
toJSONList :: [a] -> Value #
toEncodingList :: [a] -> Encoding #
Instances
Arguments
| :: String | The name of the type you are trying to parse. |
| -> Value | The actual value encountered. |
| -> Parser a |
Fail parsing due to a type mismatch, with a descriptive message.
Example usage:
instance FromJSON Coord where parseJSON (Objectv) = {- type matches, life is good -} parseJSON wat =typeMismatch"Coord" wat
decode :: FromJSON a => ByteString -> Maybe a #
Efficiently deserialize a JSON value from a lazy ByteString.
If this fails due to incomplete or invalid input, Nothing is
returned.
The input must consist solely of a JSON document, with no trailing data except for whitespace.
This function parses immediately, but defers conversion. See
json for details.
A class for types with a default value.
Instances
class MonadBase b m => MonadBaseControl (b :: * -> *) (m :: * -> *) | m -> b #
Writing instances
The usual way to write a instance for a transformer
stack over a base monad MonadBaseControlB is to write an instance MonadBaseControl B B
for the base monad, and MonadTransControl T instances for every transformer
T. Instances for are then simply implemented using
MonadBaseControl, ComposeSt, defaultLiftBaseWith.defaultRestoreM
Minimal complete definition
Instances
class (Typeable * e, Show e) => Exception e #
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 MyExceptionThe 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 = frontendExceptionFromExceptionWe can now catch a MismatchedParentheses exception as
MismatchedParentheses, SomeFrontendException or
SomeCompilerException, but not other types, e.g. IOException:
*Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: SomeFrontendException)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: SomeCompilerException)) Caught MismatchedParentheses *Main> throw MismatchedParenthesescatche -> putStrLn ("Caught " ++ show (e :: IOException)) *** Exception: MismatchedParentheses
Instances
| Exception Void | Since: 4.8.0.0 |
| Exception Dynamic | Since: 4.0.0.0 |
| Exception ErrorCall | Since: 4.0.0.0 |
| Exception ArithException | Since: 4.0.0.0 |
| Exception SomeException | Since: 3.0 |
| Exception PersistentSqlException | |
| Exception PersistException | |
| Exception UpdateException | |
| Exception OnlyUniqueException | |
| Exception InvalidAccess | |
| Exception YamContextException # | |
| Exception DataSourceException # | |