-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Vector and Text utilities -- -- Please see the README on GitHub at -- https://github.com/akashche/vt-utils#readme @package vt-utils @version 1.1.0.0 -- | Date format utilities module VtUtils.Date -- | Formats a date into a Text string using specified formatting string -- -- Arguments: -- --
-- data Foo = Foo
-- { foo :: Int
-- , bar :: Text
-- } deriving Generic
-- instance FromJSON Foo
-- instance ToJSON Foo
--
module VtUtils.JSON
-- | Parses contents of a specified JSON file into a typed data
--
-- Data type should be specified with a type annotation:
--
-- Example:
--
-- -- dt <- jsonDecodeFile "path/to/foo.json" :: IO Foo ---- -- Data must be an instance of FromJSON -- -- File contents are decoded as UTF-8 -- -- Throws an error if file cannot be read or data cannot be decoded -- -- Arguments: -- --
-- let dt = jsonDecodeText text :: Foo ---- -- Data must be an instance of FromJSON -- -- Throws an error if data cannot be decoded -- -- Arguments: -- --
-- let obj = object
-- [ "foo" .= (42 :: Int)
-- , "bar" .= ("baz" :: Text)
-- ]
-- let fooval = jsonGet obj "foo" :: Int
-- let barval = jsonGet obj "bar" :: Text
--
--
-- Arguments:
--
-- -- -- -- -- test queries -- -- -- -- /** selectFoo */ -- select foo -- from bar -- -- /** updateBar */ -- update bar -- set foo = 42 ---- -- Note: there must be an empty line after the initial comment lines on -- the top of the file -- -- Throws an error on file IO error or parsing error -- -- Arguments: -- --
-- stack test --ta "GroupName testName" ---- -- If no arguments are specified - all test are run.grlabel -- -- If single argument is specified - it is interpreted as a name of the -- group.grlabel -- -- If two argument are specified - first one is interpreted as a group -- name, and second one as a test name -- -- Throws an error on invalid command line argument -- -- Tests results are printed to stdout -- -- Arguments: -- --
-- dt <- httpRequestBodyJSON req :: IO Foo ---- -- Data must be an instance of FromJSON -- -- Arguments: -- --
-- dt <- httpResponseBodyJSON label resp 1024 :: IO Foo ---- -- Data must be an instance of FromJSON -- -- Arguments: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> s -- Left "foo" -- -- >>> let n = Right 3 :: Either String Int -- -- >>> n -- Right 3 -- -- >>> :type s -- s :: Either String Int -- -- >>> :type n -- n :: Either String Int ---- -- The fmap from our Functor instance will ignore -- Left values, but will apply the supplied function to values -- contained in a Right: -- --
-- >>> let s = Left "foo" :: Either String Int -- -- >>> let n = Right 3 :: Either String Int -- -- >>> fmap (*2) s -- Left "foo" -- -- >>> fmap (*2) n -- Right 6 ---- -- The Monad instance for Either allows us to chain -- together multiple actions which may fail, and fail overall if any of -- the individual steps failed. First we'll write a function that can -- either parse an Int from a Char, or fail. -- --
-- >>> import Data.Char ( digitToInt, isDigit )
--
-- >>> :{
-- let parseEither :: Char -> Either String Int
-- parseEither c
-- | isDigit c = Right (digitToInt c)
-- | otherwise = Left "parse error"
--
-- >>> :}
--
--
-- The following should work, since both '1' and '2'
-- can be parsed as Ints.
--
--
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither '1'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Right 3 ---- -- But the following should fail overall, since the first operation where -- we attempt to parse 'm' as an Int will fail: -- --
-- >>> :{
-- let parseMultiple :: Either String Int
-- parseMultiple = do
-- x <- parseEither 'm'
-- y <- parseEither '2'
-- return (x + y)
--
-- >>> :}
--
--
-- -- >>> parseMultiple -- Left "parse error" --data Either a b Left :: a -> Either a b Right :: b -> Either a b -- | The Eq class defines equality (==) and inequality -- (/=). All the basic datatypes exported by the Prelude -- are instances of Eq, and Eq may be derived for any -- datatype whose constituents are also instances of Eq. -- -- The Haskell Report defines no laws for Eq. However, == -- is customarily expected to implement an equivalence relationship where -- two values comparing equal are indistinguishable by "public" -- functions, with a "public" function being one not allowing to see -- implementation details. For example, for a type representing -- non-normalised natural numbers modulo 100, a "public" function doesn't -- make the difference between 1 and 201. It is expected to have the -- following properties: -- --
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Read in Haskell 2010 is equivalent to -- --
-- instance (Read a) => Read (Tree a) where
--
-- readsPrec d r = readParen (d > app_prec)
-- (\r -> [(Leaf m,t) |
-- ("Leaf",s) <- lex r,
-- (m,t) <- readsPrec (app_prec+1) s]) r
--
-- ++ readParen (d > up_prec)
-- (\r -> [(u:^:v,w) |
-- (u,s) <- readsPrec (up_prec+1) r,
-- (":^:",t) <- lex s,
-- (v,w) <- readsPrec (up_prec+1) t]) r
--
-- where app_prec = 10
-- up_prec = 5
--
--
-- Note that right-associativity of :^: is unused.
--
-- The derived instance in GHC is equivalent to
--
-- -- instance (Read a) => Read (Tree a) where -- -- readPrec = parens $ (prec app_prec $ do -- Ident "Leaf" <- lexP -- m <- step readPrec -- return (Leaf m)) -- -- +++ (prec up_prec $ do -- u <- step readPrec -- Symbol ":^:" <- lexP -- v <- step readPrec -- return (u :^: v)) -- -- where app_prec = 10 -- up_prec = 5 -- -- readListPrec = readListPrecDefault ---- -- Why do both readsPrec and readPrec exist, and why does -- GHC opt to implement readPrec in derived Read instances -- instead of readsPrec? The reason is that readsPrec is -- based on the ReadS type, and although ReadS is mentioned -- in the Haskell 2010 Report, it is not a very efficient parser data -- structure. -- -- readPrec, on the other hand, is based on a much more efficient -- ReadPrec datatype (a.k.a "new-style parsers"), but its -- definition relies on the use of the RankNTypes language -- extension. Therefore, readPrec (and its cousin, -- readListPrec) are marked as GHC-only. Nevertheless, it is -- recommended to use readPrec instead of readsPrec -- whenever possible for the efficiency improvements it brings. -- -- As mentioned above, derived Read instances in GHC will -- implement readPrec instead of readsPrec. The default -- implementations of readsPrec (and its cousin, readList) -- will simply use readPrec under the hood. If you are writing a -- Read instance by hand, it is recommended to write it like so: -- --
-- instance Read T where -- readPrec = ... -- readListPrec = readListPrecDefault --class Read a -- | Conversion of values to readable Strings. -- -- Derived instances of Show have the following properties, which -- are compatible with derived instances of Read: -- --
-- infixr 5 :^: -- data Tree a = Leaf a | Tree a :^: Tree a ---- -- the derived instance of Show is equivalent to -- --
-- instance (Show a) => Show (Tree a) where -- -- showsPrec d (Leaf m) = showParen (d > app_prec) $ -- showString "Leaf " . showsPrec (app_prec+1) m -- where app_prec = 10 -- -- showsPrec d (u :^: v) = showParen (d > up_prec) $ -- showsPrec (up_prec+1) u . -- showString " :^: " . -- showsPrec (up_prec+1) v -- where up_prec = 5 ---- -- Note that right-associativity of :^: is ignored. For example, -- --
-- f $ g $ h x = f (g (h x)) ---- -- It is also useful in higher-order situations, such as map -- ($ 0) xs, or zipWith ($) fs xs. -- -- Note that ($) is levity-polymorphic in its result type, so -- that foo $ True where foo :: Bool -> Int# is well-typed ($) :: () => (a -> b) -> a -> b infixr 0 $ (<) :: Ord a => a -> a -> Bool infix 4 < (>=) :: Ord a => a -> a -> Bool infix 4 >= (<=) :: Ord a => a -> a -> Bool infix 4 <= (==) :: Eq a => a -> a -> Bool infix 4 == (/=) :: Eq a => a -> a -> Bool infix 4 /= -- | Strict (call-by-value) application operator. It takes a function and -- an argument, evaluates the argument to weak head normal form (WHNF), -- then calls the function with that value. ($!) :: () => (a -> b) -> a -> b infixr 0 $! -- | Sequentially compose two actions, discarding any value produced by the -- first, like sequencing operators (such as the semicolon) in imperative -- languages. (>>) :: Monad m => m a -> m b -> m b infixl 1 >> -- | Sequentially compose two actions, passing any value produced by the -- first as an argument to the second. (>>=) :: Monad m => m a -> (a -> m b) -> m b infixl 1 >>= -- | Boolean "and" (&&) :: Bool -> Bool -> Bool infixr 3 && -- | Boolean "or" (||) :: Bool -> Bool -> Bool infixr 2 || -- | An infix synonym for fmap. -- -- The name of this operator is an allusion to $. Note the -- similarities between their types: -- --
-- ($) :: (a -> b) -> a -> b -- (<$>) :: Functor f => (a -> b) -> f a -> f b ---- -- Whereas $ is function application, <$> is -- function application lifted over a Functor. -- --
-- >>> show <$> Nothing -- Nothing -- -- >>> show <$> Just 3 -- Just "3" ---- -- Convert from an Either Int Int to -- an Either Int String using -- show: -- --
-- >>> show <$> Left 17 -- Left 17 -- -- >>> show <$> Right 17 -- Right "17" ---- -- Double each element of a list: -- --
-- >>> (*2) <$> [1,2,3] -- [2,4,6] ---- -- Apply even to the second element of a pair: -- --
-- >>> even <$> (2,2) -- (2,True) --(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 <$> -- | Sequential application. -- -- A few functors support an implementation of <*> that is -- more efficient than the default one. (<*>) :: Applicative f => f (a -> b) -> f a -> f b infixl 4 <*> -- | Absolute value. abs :: Num a => a -> a -- | ceiling x returns the least integer not less than -- x ceiling :: (RealFrac a, Integral b) => a -> b -- | integer division truncated toward negative infinity div :: Integral a => a -> a -> a infixl 7 `div` -- | error stops execution and displays an error message. error :: HasCallStack => [Char] -> a -- | flip f takes its (first) two arguments in the reverse -- order of f. -- --
-- >>> flip (++) "hello" "world" -- "worldhello" --flip :: () => (a -> b -> c) -> b -> a -> c -- | floor x returns the greatest integer not greater than -- x floor :: (RealFrac a, Integral b) => a -> b fmap :: Functor f => (a -> b) -> f a -> f b -- | general coercion from integral types fromIntegral :: (Integral a, Num b) => a -> b -- | Extract the first component of a pair. fst :: () => (a, b) -> a -- | Identity function. -- --
-- id x = x --id :: () => a -> a -- | Returns the size/length of a finite structure as an Int. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. length :: Foldable t => t a -> Int -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and collect the results. For a version -- that ignores the results see mapM_. mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b) -- | Map each element of a structure to a monadic action, evaluate these -- actions from left to right, and ignore the results. For a version that -- doesn't ignore the results see mapM. -- -- As of base 4.8.0.0, mapM_ is just traverse_, specialized -- to Monad. mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () -- | integer modulus, satisfying -- --
-- (x `div` y)*y + (x `mod` y) == x --mod :: Integral a => a -> a -> a infixl 7 `mod` -- | Boolean "not" not :: Bool -> Bool -- | otherwise is defined as the value True. It helps to make -- guards more readable. eg. -- --
-- f x | x < 0 = ... -- | otherwise = ... --otherwise :: Bool -- | Lift a value. pure :: Applicative f => a -> f a -- | The read function reads input from a string, which must be -- completely consumed by the input process. read fails with an -- error if the parse is unsuccessful, and it is therefore -- discouraged from being used in real applications. Use readMaybe -- or readEither for safe alternatives. -- --
-- >>> read "123" :: Int -- 123 ---- --
-- >>> read "hello" :: Int -- *** Exception: Prelude.read: no parse --read :: Read a => String -> a -- | Inject a value into the monadic type. return :: Monad m => a -> m a -- | The value of seq a b is bottom if a is bottom, and -- otherwise equal to b. In other words, it evaluates the first -- argument a to weak head normal form (WHNF). seq is -- usually introduced to improve performance by avoiding unneeded -- laziness. -- -- A note on evaluation order: the expression seq a b does -- not guarantee that a will be evaluated before -- b. The only guarantee given by seq is that the both -- a and b will be evaluated before seq -- returns a value. In particular, this means that b may be -- evaluated before a. If you need to guarantee a specific order -- of evaluation, you must use the function pseq from the -- "parallel" package. seq :: () => a -> b -> b -- | Evaluate each monadic action in the structure from left to right, and -- collect the results. For a version that ignores the results see -- sequence_. sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) -- | Evaluate each monadic action in the structure from left to right, and -- ignore the results. For a version that doesn't ignore the results see -- sequence. -- -- As of base 4.8.0.0, sequence_ is just sequenceA_, -- specialized to Monad. sequence_ :: (Foldable t, Monad m) => t (m a) -> m () -- | A specialised variant of showsPrec, using precedence context -- zero, and returning an ordinary String. show :: Show a => a -> String -- | Extract the second component of a pair. snd :: () => (a, b) -> b -- | take n, applied to a list xs, returns the -- prefix of xs of length n, or xs itself if -- n > length xs: -- --
-- take 5 "Hello World!" == "Hello" -- take 3 [1,2,3,4,5] == [1,2,3] -- take 3 [1,2] == [1,2] -- take 3 [] == [] -- take (-1) [1,2] == [] -- take 0 [1,2] == [] ---- -- It is an instance of the more general genericTake, in which -- n may be of any integral type. take :: () => Int -> [a] -> [a] -- | A special case of error. It is expected that compilers will -- recognize this and insert error messages which are more appropriate to -- the context in which undefined appears. undefined :: HasCallStack => a -- | 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. forkIO :: IO () -> IO ThreadId -- | Like forkIO, this sparks off a new thread to run the IO -- computation passed as the first argument, and returns the -- ThreadId of the newly created thread. -- -- However, forkOS creates a bound thread, which is -- necessary if you need to call foreign (non-Haskell) libraries that -- make use of thread-local state, such as OpenGL (see -- Control.Concurrent#boundthreads). -- -- Using forkOS instead of forkIO makes no difference at -- all to the scheduling behaviour of the Haskell runtime system. It is a -- common misconception that you need to use forkOS instead of -- forkIO to avoid blocking all the Haskell threads when making a -- foreign call; this isn't the case. To allow foreign calls to be made -- without blocking all the Haskell threads (with GHC), it is only -- necessary to use the -threaded option when linking your -- program, and to make sure the foreign import is not marked -- unsafe. forkOS :: IO () -> IO ThreadId -- | 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. data SomeException -- | 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 -> (a -> IO b) -> (a -> IO c) -> IO c -- | A variant of bracket where the return value from the first -- computation is not required. bracket_ :: () => IO a -> IO b -> IO c -> IO c -- | Throw an exception. Exceptions may be thrown from purely functional -- code, but may only be caught within the IO monad. throw :: Exception e => e -> a -- | Similar to catch, but returns an Either result which is -- (Right a) if no exception of type e was -- raised, or (Left ex) if an exception of type -- e was raised and its value is ex. If any other type -- of exception is raised than it will be propogated up to the next -- enclosing exception handler. -- --
-- try a = catch (Right `liftM` a) (return . Left) --try :: Exception e => IO a -> IO (Either e a) -- | forM is mapM with its arguments flipped. For a version -- that ignores the results see forM_. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) -- | forM_ is mapM_ with its arguments flipped. For a version -- that doesn't ignore the results see forM. -- -- As of base 4.8.0.0, forM_ is just for_, specialized to -- Monad. forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m () -- | Direct MonadPlus equivalent of filter. -- --
-- filter = ( mfilter :: (a -> Bool) -> [a] -> [a] ) ---- -- An example using mfilter with the Maybe monad: -- --
-- >>> mfilter odd (Just 1) -- Just 1 -- >>> mfilter odd (Just 2) -- Nothing --mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- | The reverse of when. unless :: 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. when :: Applicative f => Bool -> f () -> f () -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Return the value computed by a state transformer computation. The -- forall ensures that the internal state used by the ST -- computation is inaccessible to the rest of the program. runST :: () => (forall s. () => ST s a) -> a -- | Lift a computation from the argument monad to the constructed monad. lift :: (MonadTrans t, Monad m) => m a -> t m a -- | 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: -- --
-- -- Allow ourselves to write Text 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 use mzero to fail, but typeMismatch
-- -- gives a much more informative error message.
-- parseJSON invalid = 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:
--
-- -- instance FromJSON Coord where -- parseJSON = withObject "Coord" $ \v -> Coord -- <$> v .: "x" -- <*> v .: "y" ---- -- Instead of manually writing your FromJSON instance, there are -- two options to do it automatically: -- --
-- {-# 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 =
-- genericParseJSON defaultOptions; If you need
-- different options, you can customize the generic decoding by defining:
--
--
-- customOptions = defaultOptions
-- { fieldLabelModifier = map toUpper
-- }
--
-- instance FromJSON Coord where
-- parseJSON = genericParseJSON customOptions
--
class FromJSON a
-- | 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 write Text 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:
--
--
-- {-# 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 = map toUpper
-- }
--
-- instance ToJSON Coord where
-- toJSON = genericToJSON customOptions
-- toEncoding = genericToEncoding customOptions
--
--
-- Previous versions of this library only had the toJSON method.
-- Adding toEncoding had two reasons:
--
-- -- foldl f z = foldl' f z . toList --foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b -- | Right-associative fold of a structure, but with strict application of -- the operator. foldr' :: Foldable t => (a -> b -> b) -> b -> t a -> b -- | A map from keys to values. A map cannot contain duplicate keys; each -- key can map to at most one value. data HashMap k v -- | O(log n) Return the value to which the specified key is mapped, -- or Nothing if this map contains no mapping for the key. lookup :: (Eq k, Hashable k) => k -> HashMap k v -> Maybe v -- | 64-bit signed integer type data Int64 -- | The fromJust function extracts the element out of a Just -- and throws an error if its argument is Nothing. -- --
-- >>> fromJust (Just 1) -- 1 ---- --
-- >>> 2 * (fromJust (Just 10)) -- 20 ---- --
-- >>> 2 * (fromJust Nothing) -- *** Exception: Maybe.fromJust: Nothing --fromJust :: () => Maybe a -> a -- | The isJust function returns True iff its argument is of -- the form Just _. -- --
-- >>> isJust (Just 3) -- True ---- --
-- >>> isJust (Just ()) -- True ---- --
-- >>> isJust Nothing -- False ---- -- Only the outer constructor is taken into consideration: -- --
-- >>> isJust (Just Nothing) -- True --isJust :: () => Maybe a -> Bool -- | An associative operation. (<>) :: Semigroup a => a -> a -> a infixr 6 <> -- | Fold a list using the monoid. -- -- For most types, the default definition for mconcat will be -- used, but the function is included in the class definition so that an -- optimized version can be provided for specific types. mconcat :: Monoid a => [a] -> a -- | A space efficient, packed, unboxed Unicode text type. data Text -- | O(n) Convert a String into a Text. Subject to -- fusion. Performs replacement on invalid scalar values. pack :: String -> Text -- | O(n) Convert a Text into a String. Subject to -- fusion. unpack :: Text -> String -- | Decode a ByteString containing UTF-8 encoded text that is known -- to be valid. -- -- If the input contains any invalid UTF-8 data, an exception will be -- thrown that cannot be caught in pure code. For more control over the -- handling of invalid data, use decodeUtf8' or -- decodeUtf8With. decodeUtf8 :: ByteString -> Text -- | Encode text using UTF-8 encoding. encodeUtf8 :: Text -> ByteString -- | Write a string the end of a file. appendFile :: FilePath -> Text -> IO () -- | Read a single line of user input from stdin. getLine :: IO Text -- | Write a string to stdout, followed by a newline. putStrLn :: Text -> IO () -- | The readFile function reads a file and returns the contents of -- the file as a string. The entire file is read strictly, as with -- getContents. readFile :: FilePath -> IO Text -- | Write a string to a file. The file is truncated to zero length before -- writing begins. writeFile :: FilePath -> Text -> IO () -- | O(n) Convert a lazy Text into a strict Text. toStrict :: Text -> Text -- | A Builder is an efficient way to build lazy Text -- values. There are several functions for constructing builders, but -- only one to inspect them: to extract any data, you have to turn them -- into lazy Text values using toLazyText. -- -- Internally, a builder constructs a lazy Text by filling -- arrays piece by piece. As each buffer is filled, it is 'popped' off, -- to become a new chunk of the resulting lazy Text. All this is -- hidden from the user of the Builder. data Builder -- | O(1). A Builder taking a Text, satisfying -- --
toLazyText (fromText t) = fromChunks -- [t]
toLazyText (fromLazyText t) = t
toLazyText (fromString s) = fromChunks -- [S.pack s]
-- >>> 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.
trace :: () => String -> a -> a
-- | A value of type Ptr a represents a pointer to an
-- object, or an array of objects, which may be marshalled to or from
-- Haskell values of type a.
--
-- The type a will often be an instance of class Storable
-- which provides the marshalling operations. However this is not
-- essential, and you can provide your own operations to access the
-- pointer. For example you might write small foreign functions to get or
-- set the fields of a C struct.
data Ptr a
-- | The castPtr function casts a pointer from one type to another.
castPtr :: () => Ptr a -> Ptr b
-- | Turns a plain memory reference into a foreign pointer that may be
-- associated with finalizers by using addForeignPtrFinalizer.
newForeignPtr_ :: () => Ptr a -> IO (ForeignPtr a)
-- | The constant nullPtr contains a distinguished value of
-- Ptr that is not associated with a valid memory location.
nullPtr :: () => Ptr a
-- | Read a value from the given memory location.
--
-- Note that the peek and poke functions might require properly aligned
-- addresses to function correctly. This is architecture dependent; thus,
-- portable code should ensure that when peeking or poking values of some
-- type a, the alignment constraint for a, as given by
-- the function alignment is fulfilled.
peek :: Storable a => Ptr a -> IO a
-- | Write the given value to the given memory location. Alignment
-- restrictions might apply; see peek.
poke :: Storable a => Ptr a -> a -> IO ()
-- | Advances the given address by the given offset in bytes.
plusPtr :: () => Ptr a -> Int -> Ptr b
-- | casts a Ptr to an IntPtr
ptrToIntPtr :: () => Ptr a -> IntPtr
-- | A C string is a reference to an array of C characters terminated by
-- NUL.
type CString = Ptr CChar
-- | A string with explicit length information in bytes instead of a
-- terminating NUL (allowing NUL characters in the middle of the string).
type CStringLen = (Ptr CChar, Int)
-- | Haskell type representing the C char type.
newtype CChar
CChar :: Int8 -> CChar
-- | Haskell type representing the C int type.
newtype CInt
CInt :: Int32 -> CInt
-- | Haskell type representing the C long type.
newtype CLong
CLong :: Int64 -> CLong
-- | Haskell type representing the C short type.
newtype CShort
CShort :: Int16 -> CShort
-- | Haskell type representing the C size_t type.
newtype CSize
CSize :: Word64 -> CSize
-- | Haskell type representing the C unsigned char type.
newtype CUChar
CUChar :: Word8 -> CUChar
-- | Haskell type representing the C unsigned int type.
newtype CUInt
CUInt :: Word32 -> CUInt
-- | Haskell type representing the C unsigned long type.
newtype CULong
CULong :: Word64 -> CULong
-- | Haskell type representing the C unsigned short type.
newtype CUShort
CUShort :: Word16 -> CUShort
-- | Copies the given number of bytes from the second area (source) into
-- the first (destination); the copied areas may not overlap
copyBytes :: () => Ptr a -> Ptr a -> Int -> IO ()
-- | The member functions of this class facilitate writing values of
-- primitive types to raw memory (which may have been allocated with the
-- above mentioned routines) and reading values from blocks of raw
-- memory. The class, furthermore, includes support for computing the
-- storage requirements and alignment restrictions of storable types.
--
-- Memory addresses are represented as values of type Ptr
-- a, for some a which is an instance of class
-- Storable. The type argument to Ptr helps provide some
-- valuable type safety in FFI code (you can't mix pointers of different
-- types without an explicit cast), while helping the Haskell type system
-- figure out which marshalling method is needed for a given pointer.
--
-- All marshalling between Haskell and a foreign language ultimately
-- boils down to translating Haskell data structures into the binary
-- representation of a corresponding data structure of the foreign
-- language and vice versa. To code this marshalling in Haskell, it is
-- necessary to manipulate primitive data types stored in unstructured
-- memory blocks. The class Storable facilitates this manipulation
-- on all types for which it is instantiated, which are the standard
-- basic types of Haskell, the fixed size Int types
-- (Int8, Int16, Int32, Int64), the fixed
-- size Word types (Word8, Word16, Word32,
-- Word64), StablePtr, all types from
-- Foreign.C.Types, as well as Ptr.
class Storable a
-- | Computes the alignment constraint of the argument. An alignment
-- constraint x is fulfilled by any address divisible by
-- x. The value of the argument is not used.
alignment :: Storable a => a -> Int
-- | Read a value from a memory location given by a base address and
-- offset. The following equality holds:
--
-- -- peekByteOff addr off = peek (addr `plusPtr` off) --peekByteOff :: Storable a => Ptr b -> Int -> IO a -- | Write a value to a memory location given by a base address and offset. -- The following equality holds: -- --
-- pokeByteOff addr off x = poke (addr `plusPtr` off) x --pokeByteOff :: Storable a => Ptr b -> Int -> a -> IO () -- | Computes the storage requirements (in bytes) of the argument. The -- value of the argument is not used. sizeOf :: Storable a => a -> Int -- | 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 --class Generic a -- | Keeps track of open connections for keep-alive. -- -- If possible, you should share a single Manager between multiple -- threads and requests. -- -- Since 0.1.0 data Manager -- | Create a Manager. The Manager will be shut down -- automatically via garbage collection. -- -- Creating a new Manager is a relatively expensive operation, you -- are advised to share a single Manager between requests instead. -- -- The first argument to this function is often -- defaultManagerSettings, though add-on libraries may provide a -- recommended replacement. -- -- Since 0.1.0 newManager :: ManagerSettings -> IO Manager -- | Same as parseRequest, but parse errors cause an impure -- exception. Mostly useful for static strings which are known to be -- correctly formatted. parseRequest_ :: String -> Request -- | Perform a Request using a connection acquired from the given -- Manager, and then provide the Response to the given -- function. This function is fully exception safe, guaranteeing that the -- response will be closed when the inner function exits. It is defined -- as: -- --
-- withResponse req man f = bracket (responseOpen req man) responseClose f ---- -- It is recommended that you use this function in place of explicit -- calls to responseOpen and responseClose. -- -- You will need to use functions such as brRead to consume the -- response body. -- -- Since 0.1.0 withResponse :: () => Request -> Manager -> (Response BodyReader -> IO a) -> IO a -- | The WAI application. -- -- Note that, since WAI 3.0, this type is structured in continuation -- passing style to allow for proper safe resource handling. This was -- handled in the past via other means (e.g., ResourceT). As a -- demonstration: -- --
-- app :: Application -- app req respond = bracket_ -- (putStrLn "Allocating scarce resource") -- (putStrLn "Cleaning up") -- (respond $ responseLBS status200 [] "Hello World") --type Application = Request -> Response -> IO ResponseReceived -> IO ResponseReceived -- | Information on the request sent by the client. This abstracts away the -- details of the underlying implementation. data Request -- | The size of the request body. In the case of chunked bodies, the size -- will not be known. -- -- Since 1.4.0 data RequestBodyLength ChunkedBody :: RequestBodyLength KnownLength :: Word64 -> RequestBodyLength -- | Get the request body as a lazy ByteString. This uses lazy I/O under -- the surface, and therefore all typical warnings regarding lazy I/O -- apply. -- -- Since 1.4.1 lazyRequestBody :: Request -> IO ByteString -- | Parsed query string information. queryString :: Request -> Query -- | Extra path information sent by the client. The meaning varies slightly -- depending on backend; in a standalone server setting, this is most -- likely all information after the domain name. In a CGI application, -- this would be the information following the path to the CGI executable -- itself. -- -- Middlewares and routing tools should not modify this raw value, as it -- may be used for such things as creating redirect destinations by -- applications. Instead, if you are writing a middleware or routing -- framework, modify the pathInfo instead. This is the approach -- taken by systems like Yesod subsites. -- -- Note: At the time of writing this documentation, there is at -- least one system (Network.Wai.UrlMap from wai-extra) -- that does not follow the above recommendation. Therefore, it is -- recommended that you test the behavior of your application when using -- rawPathInfo and any form of library that might modify the -- Request. rawPathInfo :: Request -> ByteString -- | The size of the request body. In the case of a chunked request body, -- this may be unknown. -- -- Since 1.4.0 requestBodyLength :: Request -> RequestBodyLength -- | A list of headers (a pair of key and value) in an HTTP request. requestHeaders :: Request -> RequestHeaders -- | Request method such as GET. requestMethod :: Request -> Method -- | Creating Response from ByteString. This is a wrapper for -- responseBuilder. responseLBS :: Status -> ResponseHeaders -> ByteString -> Response -- | This combinator implements choice. The parser p <|> q -- first applies p. If it succeeds, the value of p is -- returned. If p fails without consuming any input, -- parser q is tried. This combinator is defined equal to the -- mplus member of the MonadPlus class and the -- (<|>) member of Alternative. -- -- The parser is called predictive since q is only tried -- when parser p didn't consume any input (i.e.. the look ahead -- is 1). This non-backtracking behaviour allows for both an efficient -- implementation of the parser combinators and the generation of good -- error messages. (<|>) :: () => ParsecT s u m a -> ParsecT s u m a -> ParsecT s u m a infixr 1 <|> -- | The parser p <?> msg behaves as parser p, but -- whenever the parser p fails without consuming any -- input, it replaces expect error messages with the expect error -- message msg. -- -- This is normally used at the end of a set alternatives where we want -- to return an error message in terms of a higher level construct rather -- than returning all possible characters. For example, if the -- expr parser from the try example would fail, the error -- message is: '...: expecting expression'. Without the -- (<?>) combinator, the message would be like '...: -- expecting "let" or letter', which is less friendly. (>) :: () => ParsecT s u m a -> String -> ParsecT s u m a infix 0 > -- | Formats a date into a Text string using specified formatting string -- -- Arguments: -- --
-- dt <- httpRequestBodyJSON req :: IO Foo ---- -- Data must be an instance of FromJSON -- -- Arguments: -- --
-- dt <- jsonDecodeFile "path/to/foo.json" :: IO Foo ---- -- Data must be an instance of FromJSON -- -- File contents are decoded as UTF-8 -- -- Throws an error if file cannot be read or data cannot be decoded -- -- Arguments: -- --
-- let dt = jsonDecodeText text :: Foo ---- -- Data must be an instance of FromJSON -- -- Throws an error if data cannot be decoded -- -- Arguments: -- --
-- let obj = object
-- [ "foo" .= (42 :: Int)
-- , "bar" .= ("baz" :: Text)
-- ]
-- let fooval = jsonGet obj "foo" :: Int
-- let barval = jsonGet obj "bar" :: Text
--
--
-- Arguments:
--
--