Safe Haskell | None |
---|---|
Language | Haskell2010 |
- The Original Prelude
- Monoids
- Maybe
- Applicative
- Monads
- Arrows
- Mutable Variables In IO
- Default
- Lens
- State monads
- Painless String Types
- Generalized String Operations
- String Case Conversions
- I/O
- Environment
- Generalized I/O
- Printf
- Filename And File System Manipulation
- Type Forcers
- Container Types With Unified Interfaces
- JSON
- Base-64
- Concurrency And Exception Handling
- Generics
- Functions
- Date and Time
- module Prelude
- module Data.Monoid
- concat :: Monoid a => [a] -> a
- append :: Monoid a => a -> a -> a
- empty :: Monoid a => a
- module Data.Maybe
- (<|>) :: Alternative f => forall a. f a -> f a -> f a
- module Control.Monad
- module Control.Arrow
- module Data.IORef
- module Control.Concurrent.MVar
- module Control.Concurrent.Chan
- module Data.Default
- module Control.Lens
- module Control.Monad.State
- s :: (ToString a, FromString b) => a -> b
- class ToString a where
- class FromString a
- class IsString a where
- type Text = Text
- type LText = Text
- type ByteString = ByteString
- type LByteString = ByteString
- trim :: (FromString a, ToString a) => a -> a
- ltrim :: (FromString a, ToString a) => a -> a
- rtrim :: (FromString a, ToString a) => a -> a
- words :: (FromString a, ToString a) => a -> [a]
- lines :: (FromString a, ToString a) => a -> [a]
- module Data.Char
- kebab :: String -> String
- snake :: String -> String
- pascal :: String -> String
- stderr :: Handle
- stdout :: Handle
- stdin :: Handle
- data Handle :: *
- module System.Environment
- class StringIO a where
- module Text.Printf
- module System.FilePath
- module System.Directory
- asString :: String -> String
- asText :: Text -> Text
- asLText :: LText -> LText
- asByteString :: ByteString -> ByteString
- asLByteString :: LByteString -> LByteString
- asHashMap :: HashMap k v -> HashMap k v
- module Data.Foldable
- newtype AList k v = AList {
- unAList :: [(k, v)]
- type HashMap = HashMap
- data LHashMap k v
- type HashSet = HashSet
- data Map k a :: * -> * -> *
- data Set a :: * -> *
- data Vector a :: * -> *
- class Hashable a where
- class Lookup m k | m -> k where
- class ListLike m a | m -> a where
- class DictLike m k where
- class SetLike m v | m -> v where
- class Filterable m where
- cull :: Filterable m => (v -> Bool) -> m v -> m v
- startsWith :: (Eq a, ListLike a e) => a -> a -> Bool
- endsWith :: (Eq a, ListLike a e) => a -> a -> Bool
- intercalate :: (Monoid a, Foldable m, ListLike (m a) a) => a -> m a -> a
- class ToJSON a where
- class FromJSON a where
- data Value :: *
- object :: [Pair] -> Value
- prettyJsonOptions :: Options
- derivePrettyJSON :: Name -> Q [Dec]
- deriveJSON :: Options -> Name -> Q [Dec]
- encodeJSON :: ToJSON a => a -> LByteString
- decodeJSON :: FromJSON a => LByteString -> Maybe a
- encodeJSONStrict :: ToJSON a => a -> ByteString
- decodeJSONStrict :: FromJSON a => ByteString -> Maybe a
- (~>) :: ToJSON a => Text -> a -> (Text, Value)
- encodeBase64 :: ByteString -> ByteString
- decodeBase64 :: ByteString -> ByteString
- threadDelay :: Int -> IO ()
- forkIO :: IO () -> IO ThreadId
- bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
- bracket_ :: IO a -> IO b -> IO c -> IO c
- throw :: Exception e => e -> a
- catch :: Exception e => IO a -> (e -> IO a) -> IO a
- catches :: IO a -> [Handler a] -> IO a
- class Generic a
- chain :: Traversable t => t (a -> a) -> a -> a
- module Data.Function
- newtype Day :: * = ModifiedJulianDay {}
- data TimeOfDay :: * = TimeOfDay {}
- data UTCTime :: * = UTCTime {
- utctDay :: Day
- utctDayTime :: DiffTime
- data LocalTime :: * = LocalTime {}
- data TimeZone :: * = TimeZone {}
- data ZonedTime :: * = ZonedTime {}
- data TimeLocale :: * = TimeLocale {}
- data DiffTime :: *
- data NominalDiffTime :: *
- secondsToDiffTime :: Integer -> DiffTime
- picosecondsToDiffTime :: Integer -> DiffTime
- addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime
- diffUTCTime :: UTCTime -> UTCTime -> NominalDiffTime
- getCurrentTime :: IO UTCTime
- defaultTimeLocale :: TimeLocale
- toGregorian :: Day -> (Integer, Int, Int)
- fromGregorian :: Integer -> Int -> Int -> Day
- formatTime :: FormatTime t => TimeLocale -> String -> t -> String
The Original Prelude
module Prelude
Monoids
module Data.Monoid
Maybe
module Data.Maybe
Applicative
(<|>) :: Alternative f => forall a. f a -> f a -> f a #
An associative binary operation
Monads
module Control.Monad
Arrows
module Control.Arrow
Mutable Variables In IO
module Data.IORef
module Control.Concurrent.MVar
module Control.Concurrent.Chan
Default
module Data.Default
Lens
module Control.Lens
State monads
module Control.Monad.State
Painless String Types
s :: (ToString a, FromString b) => a -> b #
Defines how a given type should be converted to String. If at all possible, the conversion should be loss-less, and if encodings are involved, UTF-8 should be the default.
class FromString a #
Class for string-like datastructures; used by the overloaded string extension (-XOverloadedStrings in GHC).
fromString :: String -> a #
type ByteString = ByteString Source #
type LByteString = ByteString Source #
Generalized String Operations
trim :: (FromString a, ToString a) => a -> a Source #
ltrim :: (FromString a, ToString a) => a -> a Source #
rtrim :: (FromString a, ToString a) => a -> a Source #
words :: (FromString a, ToString a) => a -> [a] Source #
lines :: (FromString a, ToString a) => a -> [a] Source #
module Data.Char
String Case Conversions
I/O
Haskell defines operations to read and write characters from and to files,
represented by values of type Handle
. Each value of this type is a
handle: a record used by the Haskell run-time system to manage I/O
with file system objects. A handle has at least the following properties:
- whether it manages input or output or both;
- whether it is open, closed or semi-closed;
- whether the object is seekable;
- whether buffering is disabled, or enabled on a line or block basis;
- a buffer (whose length may be zero).
Most handles will also have a current I/O position indicating where the next
input or output operation will occur. A handle is readable if it
manages only input or both input and output; likewise, it is writable if
it manages only output or both input and output. A handle is open when
first allocated.
Once it is closed it can no longer be used for either input or output,
though an implementation cannot re-use its storage while references
remain to it. Handles are in the Show
and Eq
classes. The string
produced by showing a handle is system dependent; it should include
enough information to identify the handle for debugging. A handle is
equal according to ==
only to itself; no attempt
is made to compare the internal state of different handles for equality.
Environment
module System.Environment
Generalized I/O
class StringIO a where Source #
Types that can be written to / read from file descriptors.
Printf
module Text.Printf
Filename And File System Manipulation
module System.FilePath
module System.Directory
Type Forcers
asByteString :: ByteString -> ByteString Source #
Container Types With Unified Interfaces
module Data.Foldable
Eq k => DictLike AList k Source # | |
Functor (AList k) Source # | |
Eq k => Lookup (AList k) k Source # | |
(Eq v, Eq k) => Eq (AList k v) Source # | |
(Ord v, Ord k) => Ord (AList k v) Source # | |
(Read v, Read k) => Read (AList k v) Source # | |
(Show v, Show k) => Show (AList k v) Source # | |
Generic (AList k v) Source # | |
type Rep (AList k v) Source # | |
A lazy hash map. Because HashMap
is actually the exact
same type as HashMap
, we wrap it in a newtype so that
we can tie laziness into the type itself (similar to how it works
for Text
and ByteString
).
(Eq k, Hashable k) => DictLike LHashMap k Source # | |
Functor (LHashMap k) Source # | |
Foldable (LHashMap k) Source # | |
Traversable (LHashMap k) Source # | |
Filterable (LHashMap k) Source # | |
(Eq k, Hashable k) => Lookup (LHashMap k) k Source # | |
(Eq v, Eq k) => Eq (LHashMap k v) Source # | |
(Hashable k, Eq k, Data v, Data k) => Data (LHashMap k v) Source # | |
(Read v, Read k, Hashable k, Eq k) => Read (LHashMap k v) Source # | |
(Show v, Show k) => Show (LHashMap k v) Source # | |
Generic (LHashMap k v) Source # | |
(Hashable k, Eq k) => Semigroup (LHashMap k v) Source # | |
(Hashable k, Eq k) => Monoid (LHashMap k v) Source # | |
(Hashable v, Hashable k) => Hashable (LHashMap k v) Source # | |
(NFData v, NFData k) => NFData (LHashMap k v) Source # | |
(Eq k, Hashable k) => SetLike (LHashMap k v) (k, v) Source # | |
type Rep (LHashMap k v) Source # | |
A Map from keys k
to values a
.
(Eq k, Ord k) => DictLike Map k Source # | |
Functor (Map k) | |
Foldable (Map k) | |
Traversable (Map k) | |
ToJSONKey k => ToJSON1 (Map k) | |
(FromJSONKey k, Ord k) => FromJSON1 (Map k) | |
Filterable (Map k) Source # | |
(Eq k, Ord k) => Lookup (Map k) k Source # | |
Ord k => IsList (Map k v) | |
(Eq k, Eq a) => Eq (Map k a) | |
(Data k, Data a, Ord k) => Data (Map k a) | |
(Ord k, Ord v) => Ord (Map k v) | |
(Ord k, Read k, Read e) => Read (Map k e) | |
(Show k, Show a) => Show (Map k a) | |
Ord k => Semigroup (Map k v) | |
Ord k => Monoid (Map k v) | |
(ToJSON v, ToJSONKey k) => ToJSON (Map k v) | |
(FromJSONKey k, Ord k, FromJSON v) => FromJSON (Map k v) | |
(NFData k, NFData a) => NFData (Map k a) | |
Ord k => Ixed (Map k a) | |
Ord k => At (Map k a) | |
Ord k => Wrapped (Map k a) | |
((~) * t (Map k' a'), Ord k) => Rewrapped (Map k a) t | Use |
(Eq k, Ord k) => SetLike (Map k v) (k, v) Source # | |
type Item (Map k v) | |
type Index (Map k a) | |
type IxValue (Map k a) | |
type Unwrapped (Map k a) | |
A set of values a
.
Foldable Set | |
ToJSON1 Set | |
Filterable Set Source # | |
Ord a => IsList (Set a) | |
Eq a => Eq (Set a) | |
(Data a, Ord a) => Data (Set a) | |
Ord a => Ord (Set a) | |
(Read a, Ord a) => Read (Set a) | |
Show a => Show (Set a) | |
Ord a => Semigroup (Set a) | |
Ord a => Monoid (Set a) | |
ToJSON a => ToJSON (Set a) | |
(Ord a, FromJSON a) => FromJSON (Set a) | |
NFData a => NFData (Set a) | |
Ord a => Contains (Set a) | |
Ord k => Ixed (Set k) | |
Ord k => At (Set k) | |
Ord a => Wrapped (Set a) | |
((~) * t (Set a'), Ord a) => Rewrapped (Set a) t | Use |
(Eq v, Ord v) => SetLike (Set v) v Source # | |
type Item (Set a) | |
type Index (Set a) | |
type IxValue (Set k) | |
type Unwrapped (Set a) | |
Boxed vectors, supporting efficient slicing.
Monad Vector | |
Functor Vector | |
Applicative Vector | |
Foldable Vector | |
Traversable Vector | |
ToJSON1 Vector | |
FromJSON1 Vector | |
Alternative Vector | |
MonadPlus Vector | |
Filterable Vector Source # | |
Vector Vector a | |
Lookup Vector Int Source # | |
IsList (Vector a) | |
Eq a => Eq (Vector a) | |
Data a => Data (Vector a) | |
Ord a => Ord (Vector a) | |
Read a => Read (Vector a) | |
Show a => Show (Vector a) | |
Monoid (Vector a) | |
ToJSON a => ToJSON (Vector a) | |
FromJSON a => FromJSON (Vector a) | |
NFData a => NFData (Vector a) | |
Ixed (Vector a) | |
Wrapped (Vector a) | |
(~) * t (Vector a') => Rewrapped (Vector a) t | |
Eq a => SetLike (Vector a) a Source # | |
ListLike (Vector a) a Source # | |
type Mutable Vector | |
type Item (Vector a) | |
type Index (Vector a) | |
type IxValue (Vector a) | |
type Unwrapped (Vector a) | |
The class of types that can be converted to a hash value.
Minimal implementation: hashWithSalt
.
hashWithSalt :: Int -> a -> Int infixl 0 #
Return a hash value for the argument, using the given salt.
The general contract of hashWithSalt
is:
- If two values are equal according to the
==
method, then applying thehashWithSalt
method on each of the two values must produce the same integer result if the same salt is used in each case. - It is not required that if two values are unequal
according to the
==
method, then applying thehashWithSalt
method on each of the two values must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal values may improve the performance of hashing-based data structures. - This method can be used to compute different hash values for
the same input by providing a different salt in each
application of the method. This implies that any instance
that defines
hashWithSalt
must make use of the salt in its implementation.
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.
class DictLike m k where Source #
Things that behave like key-value dictionaries.
insert :: k -> v -> m k v -> m k v Source #
Add or overwrite an element at a key.
delete :: k -> m k v -> m k v Source #
Delete by key
update :: k -> (v -> Maybe v) -> m k v -> m k v Source #
Modify an element at a key
pairs :: m k v -> [(k, v)] Source #
Convert to an association list (list of key/value pairs)
fromPairs :: [(k, v)] -> m k v Source #
Convert from an association list (list of key/value pairs)
Get the keys, discard the values
elems :: m k v -> [v] Source #
Get the values, discard the keys
singletonMap :: k -> v -> m k v Source #
Create a singleton dictionary (just one key-value pair)
member :: k -> m k v -> Bool Source #
Test whether the dictionary contains a given key
class SetLike m v | m -> v where Source #
Things that behave like sets.
Conjoin: add an element to a set. For ordered sets, the end at which the new element is inserted is unspecified.
remove :: v -> m -> m Source #
Remove all occurrences of the element from the set.
elem :: v -> m -> Bool Source #
Test if the element is in the set.
Test if the set is empty.
Convert the set to a list of elements. The ordering is unspecified.
fromItems :: [v] -> m Source #
Create a set from a list of elements. Duplicate list elements may be skipped at the implementation's discretion.
Create a singleton (one-element) set.
Get the number of elements in the set.
Eq a => SetLike [a] a Source # | |
(Eq v, Ord v) => SetLike (Set v) v Source # | |
Eq a => SetLike (Vector a) a Source # | |
(Eq v, Hashable v) => SetLike (HashSet v) v Source # | |
(Eq k, Ord k) => SetLike (Map k v) (k, v) Source # | |
(Eq k, Hashable k) => SetLike (LHashMap k v) (k, v) Source # | |
(Eq k, Hashable k) => SetLike (HashMap k v) (k, v) Source # | |
class Filterable m where Source #
Things that can be filtered
filter :: (v -> Bool) -> m v -> m v Source #
Filter the set to retain only the elements that match the predicate.
Filterable [] Source # | |
Filterable Set Source # | |
Filterable Vector Source # | |
Filterable HashSet Source # | |
Filterable (Map k) Source # | |
Filterable (LHashMap k) Source # | |
Filterable (HashMap k) Source # | |
cull :: Filterable m => (v -> Bool) -> m v -> m v Source #
JSON
A type that can be converted to JSON.
An example type and instance:
-- Allow ourselves to writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instance ToJSON Coord where toJSON (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 will probably be more efficient than the following two options:
- 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 for your datatype without giving
definitions for toJSON
or toEncoding
.
For example, the previous example can be simplified to a more minimal instance:
{-# LANGUAGE DeriveGeneric #-} import GHC.Generics data Coord = Coord { x :: Double, y :: Double } derivingGeneric
instance ToJSON Coord where toEncoding =genericToEncoding
defaultOptions
Why do we provide an implementation for toEncoding
here? The
toEncoding
function is a relatively new addition to this class.
To allow users of older versions of this library to upgrade without
having to edit all of their instances or encounter surprising
incompatibilities, the default implementation of toEncoding
uses
toJSON
. This produces correct results, but since it performs an
intermediate conversion to a Value
, it will be less efficient
than directly emitting an Encoding
. Our one-liner definition of
toEncoding
above bypasses the intermediate Value
.
If DefaultSignatures
doesn't give exactly the results you want,
you can customize the generic encoding with only a tiny amount of
effort, using genericToJSON
and genericToEncoding
with your
preferred Options
:
instance ToJSON Coord where toJSON =genericToJSON
defaultOptions
toEncoding =genericToEncoding
defaultOptions
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.
instance ToJSON Coord where toEncoding =genericToEncoding
defaultOptions
toJSONList :: [a] -> Value #
toEncodingList :: [a] -> Encoding #
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:
empty
andmzero
work, but are terse and uninformativefail
yields a custom error messagetypeMismatch
produces an informative message for cases when the value encountered is not of the expected type
An example type and instance:
-- Allow ourselves to writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instance FromJSON Coord where parseJSON (Object
v) = Coord<$>
v.:
"x"<*>
v.:
"y" -- We do not expect a non-Object
value here. -- We could usemzero
to fail, buttypeMismatch
-- gives a much more informative error message. parseJSON invalid =typeMismatch
"Coord" invalid
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 will probably be more efficient than the following two options:
- 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 } deriving Generic
instance FromJSON Coord
If DefaultSignatures
doesn't give exactly the results you want,
you can customize the generic decoding with only a tiny amount of
effort, using genericParseJSON
with your preferred Options
:
instance FromJSON Coord where parseJSON =genericParseJSON
defaultOptions
A JSON value represented as a Haskell value.
:: Options | Encoding options. |
-> Name | Name of the type for which to generate |
-> Q [Dec] |
Generates both ToJSON
and FromJSON
instance declarations for the given
data type or data family instance constructor.
This is a convienience function which is equivalent to calling both
deriveToJSON
and deriveFromJSON
.
encodeJSON :: ToJSON a => a -> LByteString Source #
decodeJSON :: FromJSON a => LByteString -> Maybe a Source #
encodeJSONStrict :: ToJSON a => a -> ByteString Source #
decodeJSONStrict :: FromJSON a => ByteString -> Maybe a Source #
Base-64
encodeBase64 :: ByteString -> ByteString Source #
decodeBase64 :: ByteString -> ByteString Source #
Concurrency And Exception Handling
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.
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.
:: IO a | computation to run first ("acquire resource") |
-> (a -> IO b) | computation to run last ("release resource") |
-> (a -> IO c) | computation to run in-between |
-> IO c |
When you want to acquire a resource, do some work with it, and
then release the resource, it is a good idea to use bracket
,
because bracket
will install the necessary exception handler to
release the resource in the event that an exception is raised
during the computation. If an exception is raised, then bracket
will
re-raise the exception (after performing the release).
A common example is opening a file:
bracket (openFile "filename" ReadMode) (hClose) (\fileHandle -> do { ... })
The arguments to bracket
are in this order so that we can partially apply
it, e.g.:
withFile name mode = bracket (openFile name mode) hClose
bracket_ :: IO a -> IO b -> IO c -> IO c #
A variant of bracket
where the return value from the first computation
is not required.
throw :: Exception e => e -> a #
Throw an exception. Exceptions may be thrown from purely
functional code, but may only be caught within the IO
monad.
:: Exception e | |
=> IO a | The computation to run |
-> (e -> IO a) | Handler to invoke if an exception is raised |
-> IO a |
This is the simplest of the exception-catching functions. It takes a single argument, runs it, and if an exception is raised the "handler" is executed, with the value of the exception passed as an argument. Otherwise, the result is returned as normal. For example:
catch (readFile f) (\e -> do let err = show (e :: IOException) hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err) return "")
Note that we have to give a type signature to e
, or the program
will not typecheck as the type is ambiguous. While it is possible
to catch exceptions of any type, see the section "Catching all
exceptions" (in Control.Exception) for an explanation of the problems with doing so.
For catching exceptions in pure (non-IO
) expressions, see the
function evaluate
.
Note that due to Haskell's unspecified evaluation order, an
expression may throw one of several possible exceptions: consider
the expression (error "urk") + (1 `div` 0)
. Does
the expression throw
ErrorCall "urk"
, or DivideByZero
?
The answer is "it might throw either"; the choice is
non-deterministic. If you are catching any type of exception then you
might catch either. If you are calling catch
with type
IO Int -> (ArithException -> IO Int) -> IO Int
then the handler may
get run with DivideByZero
as an argument, or an ErrorCall "urk"
exception may be propogated further up. If you call it again, you
might get a the opposite behaviour. This is ok, because catch
is an
IO
computation.
catches :: IO a -> [Handler a] -> IO a #
Sometimes you want to catch two different sorts of exception. You could do something like
f = expr `catch` \ (ex :: ArithException) -> handleArith ex `catch` \ (ex :: IOException) -> handleIO ex
However, there are a couple of problems with this approach. The first is
that having two exception handlers is inefficient. However, the more
serious issue is that the second exception handler will catch exceptions
in the first, e.g. in the example above, if handleArith
throws an
IOException
then the second exception handler will catch it.
Instead, we provide a function catches
, which would be used thus:
f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex), Handler (\ (ex :: IOException) -> handleIO ex)]
Generics
Representable types of kind *. This class is derivable in GHC with the DeriveGeneric flag on.
Functions
chain :: Traversable t => t (a -> a) -> a -> a Source #
module Data.Function
Date and Time
The Modified Julian Day is a standard count of days, with zero being the day 1858-11-17.
Time of day as represented in hour, minute and second (with picoseconds), typically used to express local time of day.
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.
UTCTime | |
|
A simple day and time aggregate, where the day is of the specified parameter, and the time is a TimeOfDay. Conversion of this (as local civil time) to UTC depends on the time zone. Conversion of this (as local mean time) to UT1 depends on the longitude.
A TimeZone is a whole number of minutes offset from UTC, together with a name and a "just for summer" flag.
TimeZone | |
|
A local time together with a TimeZone.
data TimeLocale :: * #
TimeLocale | |
|
This is a length of time, as measured by a clock. Conversion functions will treat it as seconds. It has a precision of 10^-12 s.
data NominalDiffTime :: * #
This is a length of time, as measured by UTC. Conversion functions will treat it as seconds. It has a precision of 10^-12 s. It ignores leap-seconds, so it's not necessarily a fixed amount of clock time. For instance, 23:00 UTC + 2 hours of NominalDiffTime = 01:00 UTC (+ 1 day), regardless of whether a leap-second intervened.
Enum NominalDiffTime | |
Eq NominalDiffTime | |
Fractional NominalDiffTime | |
Data NominalDiffTime | |
Num NominalDiffTime | |
Ord NominalDiffTime | |
Real NominalDiffTime | |
RealFrac NominalDiffTime | |
Show NominalDiffTime | |
ToJSON NominalDiffTime | |
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
|
NFData NominalDiffTime | |
secondsToDiffTime :: Integer -> DiffTime #
Create a DiffTime
which represents an integral number of seconds.
picosecondsToDiffTime :: Integer -> DiffTime #
Create a DiffTime
from a number of picoseconds.
addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime #
addUTCTime a b = a + b
diffUTCTime :: UTCTime -> UTCTime -> NominalDiffTime #
diffUTCTime a b = a - b
getCurrentTime :: IO UTCTime #
Get the current UTC time from the system clock.
defaultTimeLocale :: TimeLocale #
Locale representing American usage.
knownTimeZones
contains only the ten time-zones mentioned in RFC 822 sec. 5:
"UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT".
Note that the parsing functions will regardless parse single-letter military time-zones and +HHMM format.
toGregorian :: Day -> (Integer, Int, Int) #
convert to proleptic Gregorian calendar. First element of result is year, second month number (1-12), third day (1-31).
fromGregorian :: Integer -> Int -> Int -> Day #
convert from proleptic Gregorian calendar. First argument is year, second month number (1-12), third day (1-31). Invalid values will be clipped to the correct range, month first, then day.
formatTime :: FormatTime t => TimeLocale -> String -> t -> String #
Substitute various time-related information for each %-code in the string, as per formatCharacter
.
For all types (note these three are done here, not by formatCharacter
):
%%
%
%t
- tab
%n
- newline
glibc-style modifiers can be used before the letter (here marked as z
):
%-z
- no padding
%_z
- pad with spaces
%0z
- pad with zeros
%^z
- convert to upper case
%#z
- convert to lower case (consistently, unlike glibc)
For TimeZone
(and ZonedTime
and UTCTime
):
%z
- timezone offset in the format
-HHMM
. %Z
- timezone name
For LocalTime
(and ZonedTime
and UTCTime
and UniversalTime
):
%c
- as
dateTimeFmt
locale
(e.g.%a %b %e %H:%M:%S %Z %Y
)
For TimeOfDay
(and LocalTime
and ZonedTime
and UTCTime
and UniversalTime
):
%R
- same as
%H:%M
%T
- same as
%H:%M:%S
%X
- as
timeFmt
locale
(e.g.%H:%M:%S
) %r
- as
time12Fmt
locale
(e.g.%I:%M:%S %p
) %P
- day-half of day from (
amPm
locale
), converted to lowercase,am
,pm
%p
- day-half of day from (
amPm
locale
),AM
,PM
%H
- hour of day (24-hour), 0-padded to two chars,
00
-23
%k
- hour of day (24-hour), space-padded to two chars,
0
-23
%I
- hour of day-half (12-hour), 0-padded to two chars,
01
-12
%l
- hour of day-half (12-hour), space-padded to two chars,
1
-12
%M
- minute of hour, 0-padded to two chars,
00
-59
%S
- second of minute (without decimal part), 0-padded to two chars,
00
-60
%q
- picosecond of second, 0-padded to twelve chars,
000000000000
-999999999999
. %Q
- decimal point and fraction of second, up to 12 second decimals, without trailing zeros.
For a whole number of seconds,
%Q
produces the empty string.
%s
- number of whole seconds since the Unix epoch. For times before
the Unix epoch, this is a negative number. Note that in
%s.%q
and%s%Q
the decimals are positive, not negative. For example, 0.9 seconds before the Unix epoch is formatted as-1.1
with%s%Q
.
For Day
(and LocalTime
and ZonedTime
and UTCTime
and UniversalTime
):
%D
- same as
%m/%d/%y
%F
- same as
%Y-%m-%d
%x
- as
dateFmt
locale
(e.g.%m/%d/%y
) %Y
- year, no padding. Note
%0Y
and%_Y
pad to four chars %y
- year of century, 0-padded to two chars,
00
-99
%C
- century, no padding. Note
%0C
and%_C
pad to two chars %B
- month name, long form (
fst
frommonths
locale
),January
-December
%b
,%h
- month name, short form (
snd
frommonths
locale
),Jan
-Dec
%m
- month of year, 0-padded to two chars,
01
-12
%d
- day of month, 0-padded to two chars,
01
-31
%e
- day of month, space-padded to two chars,
1
-31
%j
- day of year, 0-padded to three chars,
001
-366
%G
- year for Week Date format, no padding. Note
%0G
and%_G
pad to four chars %g
- year of century for Week Date format, 0-padded to two chars,
00
-99
%f
- century for Week Date format, no padding. Note
%0f
and%_f
pad to two chars %V
- week of year for Week Date format, 0-padded to two chars,
01
-53
%u
- day of week for Week Date format,
1
-7
%a
- day of week, short form (
snd
fromwDays
locale
),Sun
-Sat
%A
- day of week, long form (
fst
fromwDays
locale
),Sunday
-Saturday
%U
- week of year where weeks start on Sunday (as
sundayStartWeek
), 0-padded to two chars,00
-53
%w
- day of week number,
0
(= Sunday) -6
(= Saturday) %W
- week of year where weeks start on Monday (as
mondayStartWeek
), 0-padded to two chars,00
-53