| Safe Haskell | Safe-Inferred |
|---|---|
| Language | Haskell2010 |
Hledger.Cli.Script
Description
A convenient module to import in hledger scripts, aiming to provide the most useful imports and reduce boilerplate. |
Synopsis
- (++) :: [a] -> [a] -> [a]
- filter :: (a -> Bool) -> [a] -> [a]
- zip :: [a] -> [b] -> [(a, b)]
- print :: Show a => a -> IO ()
- trace :: String -> a -> a
- map :: (a -> b) -> [a] -> [b]
- guard :: Alternative f => Bool -> f ()
- join :: Monad m => m (m a) -> m a
- class Applicative m => Monad (m :: Type -> Type) where
- class Functor (f :: Type -> Type) where
- class Eq a => Ord a where
- class Monad m => MonadFail (m :: Type -> Type) where
- class Functor f => Applicative (f :: Type -> Type) where
- sum :: (Foldable t, Num a) => t a -> a
- product :: (Foldable t, Num a) => t a -> a
- minimum :: (Foldable t, Ord a) => t a -> a
- maximum :: (Foldable t, Ord a) => t a -> a
- foldr1 :: Foldable t => (a -> a -> a) -> t a -> a
- foldl1 :: Foldable t => (a -> a -> a) -> t a -> a
- elem :: (Foldable t, Eq a) => a -> t a -> Bool
- length :: Foldable t => t a -> Int
- foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b
- foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
- foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
- null :: Foldable t => t a -> Bool
- mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)
- sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)
- data Char
- data Maybe a
- data Ordering
- data IO a
- data Either a b
- getCurrentDirectory :: IO FilePath
- type FilePath = String
- span :: (a -> Bool) -> [a] -> ([a], [a])
- (<$>) :: Functor f => (a -> b) -> f a -> f b
- toLower :: Char -> Char
- data UTCTime = UTCTime {
- utctDay :: Day
- utctDayTime :: DiffTime
- data Text
- liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
- when :: Applicative f => Bool -> f () -> f ()
- class Applicative f => Alternative (f :: Type -> Type) where
- ($>) :: Functor f => f a -> b -> f b
- void :: Functor f => f a -> f ()
- catMaybes :: [Maybe a] -> [a]
- fromMaybe :: a -> Maybe a -> a
- mapMaybe :: (a -> Maybe b) -> [a] -> [b]
- newtype Const a (b :: k) = Const {
- getConst :: a
- unless :: Applicative f => Bool -> f () -> f ()
- stdin :: Handle
- stdout :: Handle
- data Handle
- forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
- mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
- forkOnWithUnmask :: Int -> ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId
- forkIOWithUnmask :: ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId
- forkOn :: Int -> IO () -> IO ThreadId
- forkOS :: IO () -> IO ThreadId
- forkIO :: IO () -> IO ThreadId
- data ThreadId
- isSpace :: Char -> Bool
- isAlpha :: Char -> Bool
- isDigit :: Char -> Bool
- class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where
- threadWaitWriteSTM :: Fd -> IO (STM (), IO ())
- threadWaitWrite :: Fd -> IO ()
- threadWaitReadSTM :: Fd -> IO (STM (), IO ())
- threadWaitRead :: Fd -> IO ()
- runInUnboundThread :: IO a -> IO a
- runInBoundThread :: IO a -> IO a
- rtsSupportsBoundThreads :: Bool
- isCurrentThreadBound :: IO Bool
- forkOSWithUnmask :: ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId
- forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
- data Chan a
- writeList2Chan :: Chan a -> [a] -> IO ()
- writeChan :: Chan a -> a -> IO ()
- readChan :: Chan a -> IO a
- newChan :: IO (Chan a)
- getChanContents :: Chan a -> IO [a]
- dupChan :: Chan a -> IO (Chan a)
- data QSem
- waitQSem :: QSem -> IO ()
- signalQSem :: QSem -> IO ()
- newQSem :: Int -> IO QSem
- data QSemN
- waitQSemN :: QSemN -> Int -> IO ()
- signalQSemN :: QSemN -> Int -> IO ()
- newQSemN :: Int -> IO QSemN
- withProgName :: String -> IO a -> IO a
- withArgs :: [String] -> IO a -> IO a
- unsetEnv :: String -> IO ()
- setEnv :: String -> String -> IO ()
- lookupEnv :: String -> IO (Maybe String)
- getProgName :: IO String
- getEnvironment :: IO [(String, String)]
- getEnv :: String -> IO String
- getArgs :: IO [String]
- getExecutablePath :: IO FilePath
- exitWith :: ExitCode -> IO a
- exitSuccess :: IO a
- exitFailure :: IO a
- die :: String -> IO a
- class PrintfType t
- class PrintfArg a where
- formatArg :: a -> FieldFormatter
- parseFormat :: a -> ModifierParser
- type ModifierParser = String -> FormatParse
- class IsChar c where
- class HPrintfType t
- data FormatSign
- data FormatParse = FormatParse {}
- data FormatAdjustment
- type FieldFormatter = FieldFormat -> ShowS
- data FieldFormat = FieldFormat {}
- vFmt :: Char -> FieldFormat -> FieldFormat
- printf :: PrintfType r => String -> r
- perror :: String -> a
- hPrintf :: HPrintfType r => Handle -> String -> r
- formatRealFloat :: RealFloat a => a -> FieldFormatter
- formatInteger :: Integer -> FieldFormatter
- formatInt :: (Integral a, Bounded a) => a -> FieldFormatter
- formatChar :: Char -> FieldFormatter
- errorShortFormat :: a
- errorMissingArgument :: a
- errorBadFormat :: Char -> a
- errorBadArgument :: a
- zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m ()
- zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c]
- replicateM_ :: Applicative m => Int -> m a -> m ()
- replicateM :: Applicative m => Int -> m a -> m [a]
- mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
- mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c])
- forever :: Applicative f => f a -> f b
- foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m ()
- foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
- filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
- (<$!>) :: Monad m => (a -> b) -> m a -> m b
- traceShowId :: Show a => a -> a
- traceIO :: String -> IO ()
- isSubsequenceOf :: Eq a => [a] -> [a] -> Bool
- mapAccumR :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b)
- mapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b)
- forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
- newtype ZipList a = ZipList {
- getZipList :: [a]
- newtype WrappedMonad (m :: Type -> Type) a = WrapMonad {
- unwrapMonad :: m a
- newtype WrappedArrow (a :: Type -> Type -> Type) b c = WrapArrow {
- unwrapArrow :: a b c
- optional :: Alternative f => f a -> f (Maybe a)
- writeFile :: FilePath -> String -> IO ()
- readLn :: Read a => IO a
- readIO :: Read a => String -> IO a
- readFile' :: FilePath -> IO String
- readFile :: FilePath -> IO String
- putStrLn :: String -> IO ()
- putStr :: String -> IO ()
- putChar :: Char -> IO ()
- openTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle)
- openTempFile :: FilePath -> String -> IO (FilePath, Handle)
- openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle)
- openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
- localeEncoding :: TextEncoding
- interact :: (String -> String) -> IO ()
- hReady :: Handle -> IO Bool
- hPrint :: Show a => Handle -> a -> IO ()
- getLine :: IO String
- getContents' :: IO String
- getContents :: IO String
- getChar :: IO Char
- fixIO :: (a -> IO a) -> IO a
- appendFile :: FilePath -> String -> IO ()
- data HandlePosn
- isEOF :: IO Bool
- hTell :: Handle -> IO Integer
- hShow :: Handle -> IO String
- hSetPosn :: HandlePosn -> IO ()
- hSetNewlineMode :: Handle -> NewlineMode -> IO ()
- hSetFileSize :: Handle -> Integer -> IO ()
- hSetEncoding :: Handle -> TextEncoding -> IO ()
- hSetEcho :: Handle -> Bool -> IO ()
- hSetBuffering :: Handle -> BufferMode -> IO ()
- hSetBinaryMode :: Handle -> Bool -> IO ()
- hSeek :: Handle -> SeekMode -> Integer -> IO ()
- hLookAhead :: Handle -> IO Char
- hIsWritable :: Handle -> IO Bool
- hIsTerminalDevice :: Handle -> IO Bool
- hIsSeekable :: Handle -> IO Bool
- hIsReadable :: Handle -> IO Bool
- hIsOpen :: Handle -> IO Bool
- hIsEOF :: Handle -> IO Bool
- hIsClosed :: Handle -> IO Bool
- hGetPosn :: Handle -> IO HandlePosn
- hGetEncoding :: Handle -> IO (Maybe TextEncoding)
- hGetEcho :: Handle -> IO Bool
- hGetBuffering :: Handle -> IO BufferMode
- hFileSize :: Handle -> IO Integer
- hClose :: Handle -> IO ()
- withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
- withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
- stderr :: Handle
- openFile :: FilePath -> IOMode -> IO Handle
- openBinaryFile :: FilePath -> IOMode -> IO Handle
- threadDelay :: Int -> IO ()
- withMVarMasked :: MVar a -> (a -> IO b) -> IO b
- withMVar :: MVar a -> (a -> IO b) -> IO b
- swapMVar :: MVar a -> a -> IO a
- modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
- modifyMVarMasked_ :: MVar a -> (a -> IO a) -> IO ()
- modifyMVarMasked :: MVar a -> (a -> IO (a, b)) -> IO b
- modifyMVar :: MVar a -> (a -> IO (a, b)) -> IO b
- mkWeakMVar :: MVar a -> IO () -> IO (Weak (MVar a))
- addMVarFinalizer :: MVar a -> IO () -> IO ()
- hWaitForInput :: Handle -> Int -> IO Bool
- hPutStrLn :: Handle -> String -> IO ()
- hPutStr :: Handle -> String -> IO ()
- hPutChar :: Handle -> Char -> IO ()
- hPutBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
- hPutBuf :: Handle -> Ptr a -> Int -> IO ()
- hGetLine :: Handle -> IO String
- hGetContents' :: Handle -> IO String
- hGetContents :: Handle -> IO String
- hGetChar :: Handle -> IO Char
- hGetBufSome :: Handle -> Ptr a -> Int -> IO Int
- hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
- hGetBuf :: Handle -> Ptr a -> Int -> IO Int
- utf8_bom :: TextEncoding
- utf8 :: TextEncoding
- utf32le :: TextEncoding
- utf32be :: TextEncoding
- utf32 :: TextEncoding
- utf16le :: TextEncoding
- utf16be :: TextEncoding
- utf16 :: TextEncoding
- mkTextEncoding :: String -> IO TextEncoding
- latin1 :: TextEncoding
- char8 :: TextEncoding
- userErrorType :: IOErrorType
- tryIOError :: IO a -> IO (Either IOError a)
- resourceVanishedErrorType :: IOErrorType
- permissionErrorType :: IOErrorType
- modifyIOError :: (IOError -> IOError) -> IO a -> IO a
- mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError
- isUserErrorType :: IOErrorType -> Bool
- isUserError :: IOError -> Bool
- isResourceVanishedErrorType :: IOErrorType -> Bool
- isResourceVanishedError :: IOError -> Bool
- isPermissionErrorType :: IOErrorType -> Bool
- isPermissionError :: IOError -> Bool
- isIllegalOperationErrorType :: IOErrorType -> Bool
- isIllegalOperation :: IOError -> Bool
- isFullErrorType :: IOErrorType -> Bool
- isFullError :: IOError -> Bool
- isEOFErrorType :: IOErrorType -> Bool
- isEOFError :: IOError -> Bool
- isDoesNotExistErrorType :: IOErrorType -> Bool
- isDoesNotExistError :: IOError -> Bool
- isAlreadyInUseErrorType :: IOErrorType -> Bool
- isAlreadyInUseError :: IOError -> Bool
- isAlreadyExistsErrorType :: IOErrorType -> Bool
- isAlreadyExistsError :: IOError -> Bool
- ioeSetLocation :: IOError -> String -> IOError
- ioeSetHandle :: IOError -> Handle -> IOError
- ioeSetFileName :: IOError -> FilePath -> IOError
- ioeSetErrorType :: IOError -> IOErrorType -> IOError
- ioeSetErrorString :: IOError -> String -> IOError
- ioeGetLocation :: IOError -> String
- ioeGetHandle :: IOError -> Maybe Handle
- ioeGetFileName :: IOError -> Maybe FilePath
- ioeGetErrorType :: IOError -> IOErrorType
- ioeGetErrorString :: IOError -> String
- illegalOperationErrorType :: IOErrorType
- fullErrorType :: IOErrorType
- eofErrorType :: IOErrorType
- doesNotExistErrorType :: IOErrorType
- catchIOError :: IO a -> (IOError -> IO a) -> IO a
- annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError
- alreadyInUseErrorType :: IOErrorType
- alreadyExistsErrorType :: IOErrorType
- yield :: IO ()
- throwTo :: Exception e => ThreadId -> e -> IO ()
- threadCapability :: ThreadId -> IO (Int, Bool)
- setNumCapabilities :: Int -> IO ()
- myThreadId :: IO ThreadId
- mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)
- killThread :: ThreadId -> IO ()
- getNumCapabilities :: IO Int
- data IOErrorType
- data ExitCode
- ioError :: IOError -> IO a
- hFlush :: Handle -> IO ()
- data NewlineMode = NewlineMode {}
- data Newline
- data BufferMode
- universalNewlineMode :: NewlineMode
- noNewlineTranslation :: NewlineMode
- nativeNewlineMode :: NewlineMode
- nativeNewline :: Newline
- data SeekMode
- data TextEncoding
- type IOError = IOException
- userError :: String -> IOError
- sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()
- or :: Foldable t => t Bool -> Bool
- notElem :: (Foldable t, Eq a) => a -> t a -> Bool
- msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
- minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
- maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
- find :: Foldable t => (a -> Bool) -> t a -> Maybe a
- concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
- concat :: Foldable t => t [a] -> [a]
- asum :: (Foldable t, Alternative f) => t (f a) -> f a
- any :: Foldable t => (a -> Bool) -> t a -> Bool
- and :: Foldable t => t Bool -> Bool
- all :: Foldable t => (a -> Bool) -> t a -> Bool
- zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]
- zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]
- zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]
- zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
- zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]
- zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]
- zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]
- zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
- words :: String -> [String]
- unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])
- unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])
- unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])
- unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])
- unwords :: [String] -> String
- unlines :: [String] -> String
- unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- union :: Eq a => [a] -> [a] -> [a]
- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
- transpose :: [[a]] -> [[a]]
- tails :: [a] -> [[a]]
- subsequences :: [a] -> [[a]]
- stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
- sortOn :: Ord b => (a -> b) -> [a] -> [a]
- sortBy :: (a -> a -> Ordering) -> [a] -> [a]
- sort :: Ord a => [a] -> [a]
- singleton :: a -> [a]
- permutations :: [a] -> [[a]]
- partition :: (a -> Bool) -> [a] -> ([a], [a])
- nubBy :: (a -> a -> Bool) -> [a] -> [a]
- nub :: Eq a => [a] -> [a]
- lines :: String -> [String]
- isSuffixOf :: Eq a => [a] -> [a] -> Bool
- isPrefixOf :: Eq a => [a] -> [a] -> Bool
- isInfixOf :: Eq a => [a] -> [a] -> Bool
- intersperse :: a -> [a] -> [a]
- intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- intersect :: Eq a => [a] -> [a] -> [a]
- intercalate :: [a] -> [[a]] -> [a]
- insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
- insert :: Ord a => a -> [a] -> [a]
- inits :: [a] -> [[a]]
- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
- group :: Eq a => [a] -> [[a]]
- genericTake :: Integral i => i -> [a] -> [a]
- genericSplitAt :: Integral i => i -> [a] -> ([a], [a])
- genericReplicate :: Integral i => i -> a -> [a]
- genericLength :: Num i => [a] -> i
- genericIndex :: Integral i => [a] -> i -> a
- genericDrop :: Integral i => i -> [a] -> [a]
- findIndices :: (a -> Bool) -> [a] -> [Int]
- findIndex :: (a -> Bool) -> [a] -> Maybe Int
- elemIndices :: Eq a => a -> [a] -> [Int]
- elemIndex :: Eq a => a -> [a] -> Maybe Int
- dropWhileEnd :: (a -> Bool) -> [a] -> [a]
- deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
- delete :: Eq a => a -> [a] -> [a]
- (\\) :: Eq a => [a] -> [a] -> [a]
- newtype Down a = Down {
- getDown :: a
- comparing :: Ord a => (b -> a) -> b -> b -> Ordering
- clamp :: Ord a => (a, a) -> a -> a
- isSeparator :: Char -> Bool
- isNumber :: Char -> Bool
- isMark :: Char -> Bool
- isLetter :: Char -> Bool
- digitToInt :: Char -> Int
- rights :: [Either a b] -> [b]
- partitionEithers :: [Either a b] -> ([a], [b])
- lefts :: [Either a b] -> [a]
- isRight :: Either a b -> Bool
- isLeft :: Either a b -> Bool
- fromRight :: b -> Either a b -> b
- fromLeft :: a -> Either a b -> a
- either :: (a -> c) -> (b -> c) -> Either a b -> c
- data IOMode
- readLitChar :: ReadS Char
- lexLitChar :: ReadS String
- data GeneralCategory
- = UppercaseLetter
- | LowercaseLetter
- | TitlecaseLetter
- | ModifierLetter
- | OtherLetter
- | NonSpacingMark
- | SpacingCombiningMark
- | EnclosingMark
- | DecimalNumber
- | LetterNumber
- | OtherNumber
- | ConnectorPunctuation
- | DashPunctuation
- | OpenPunctuation
- | ClosePunctuation
- | InitialQuote
- | FinalQuote
- | OtherPunctuation
- | MathSymbol
- | CurrencySymbol
- | ModifierSymbol
- | OtherSymbol
- | Space
- | LineSeparator
- | ParagraphSeparator
- | Control
- | Format
- | Surrogate
- | PrivateUse
- | NotAssigned
- toUpper :: Char -> Char
- toTitle :: Char -> Char
- isUpper :: Char -> Bool
- isSymbol :: Char -> Bool
- isPunctuation :: Char -> Bool
- isPrint :: Char -> Bool
- isOctDigit :: Char -> Bool
- isLower :: Char -> Bool
- isLatin1 :: Char -> Bool
- isHexDigit :: Char -> Bool
- isControl :: Char -> Bool
- isAsciiUpper :: Char -> Bool
- isAsciiLower :: Char -> Bool
- isAscii :: Char -> Bool
- isAlphaNum :: Char -> Bool
- generalCategory :: Char -> GeneralCategory
- chr :: Int -> Char
- showLitChar :: Char -> ShowS
- intToDigit :: Int -> Char
- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
- zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
- unzip3 :: [(a, b, c)] -> ([a], [b], [c])
- unzip :: [(a, b)] -> ([a], [b])
- uncons :: [a] -> Maybe (a, [a])
- takeWhile :: (a -> Bool) -> [a] -> [a]
- take :: Int -> [a] -> [a]
- tail :: [a] -> [a]
- splitAt :: Int -> [a] -> ([a], [a])
- scanr1 :: (a -> a -> a) -> [a] -> [a]
- scanr :: (a -> b -> b) -> b -> [a] -> [b]
- scanl1 :: (a -> a -> a) -> [a] -> [a]
- scanl' :: (b -> a -> b) -> b -> [a] -> [b]
- scanl :: (b -> a -> b) -> b -> [a] -> [b]
- reverse :: [a] -> [a]
- replicate :: Int -> a -> [a]
- repeat :: a -> [a]
- lookup :: Eq a => a -> [(a, b)] -> Maybe b
- last :: [a] -> a
- iterate' :: (a -> a) -> a -> [a]
- iterate :: (a -> a) -> a -> [a]
- init :: [a] -> [a]
- head :: [a] -> a
- foldl1' :: (a -> a -> a) -> [a] -> a
- dropWhile :: (a -> Bool) -> [a] -> [a]
- drop :: Int -> [a] -> [a]
- cycle :: [a] -> [a]
- break :: (a -> Bool) -> [a] -> ([a], [a])
- (!!) :: [a] -> Int -> a
- maybeToList :: Maybe a -> [a]
- maybe :: b -> (a -> b) -> Maybe a -> b
- listToMaybe :: [a] -> Maybe a
- isNothing :: Maybe a -> Bool
- isJust :: Maybe a -> Bool
- fromJust :: HasCallStack => Maybe a -> a
- (<&>) :: Functor f => f a -> (a -> b) -> f b
- data MVar a
- tryTakeMVar :: MVar a -> IO (Maybe a)
- tryReadMVar :: MVar a -> IO (Maybe a)
- tryPutMVar :: MVar a -> a -> IO Bool
- takeMVar :: MVar a -> IO a
- readMVar :: MVar a -> IO a
- putMVar :: MVar a -> a -> IO ()
- newMVar :: a -> IO (MVar a)
- newEmptyMVar :: IO (MVar a)
- isEmptyMVar :: MVar a -> IO Bool
- ord :: Char -> Int
- liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
- liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
- liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
- liftM :: Monad m => (a1 -> r) -> m a1 -> m r
- liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
- liftA :: Applicative f => (a -> b) -> f a -> f b
- ap :: Monad m => m (a -> b) -> m a -> m b
- (=<<) :: Monad m => (a -> m b) -> m a -> m b
- (<**>) :: Applicative f => f a -> f (a -> b) -> f b
- type HasCallStack = ?callStack :: CallStack
- flagsVerbosity :: (Verbosity -> a -> a) -> [Flag a]
- flagNumericVersion :: (a -> a) -> Flag a
- flagVersion :: (a -> a) -> Flag a
- flagHelpFormat :: (HelpFormat -> TextFormat -> a -> a) -> Flag a
- flagHelpSimple :: (a -> a) -> Flag a
- processValueIO :: Mode a -> [String] -> IO a
- processValue :: Mode a -> [String] -> a
- processArgs :: Mode a -> IO a
- helpText :: [String] -> HelpFormat -> Mode a -> [Text]
- data HelpFormat
- complete :: Mode a -> [String] -> (Int, Int) -> [Complete]
- data Complete
- process :: Mode a -> [String] -> Either String a
- flagBool :: [Name] -> (Bool -> a -> a) -> Help -> Flag a
- flagArg :: Update a -> FlagHelp -> Arg a
- flagReq :: [Name] -> Update a -> FlagHelp -> Help -> Flag a
- flagOpt :: String -> [Name] -> Update a -> FlagHelp -> Help -> Flag a
- flagNone :: [Name] -> (a -> a) -> Help -> Flag a
- modes :: String -> a -> Help -> [Mode a] -> Mode a
- mode :: Name -> a -> Help -> Arg a -> [Flag a] -> Mode a
- modeEmpty :: a -> Mode a
- remapUpdate :: (a -> b) -> (b -> (a, a -> b)) -> Update a -> Update b
- remap2 :: Remap m => (a -> b) -> (b -> a) -> m a -> m b
- checkMode :: Mode a -> Maybe String
- fromFlagOpt :: FlagInfo -> String
- modeFlags :: Mode a -> [Flag a]
- modeModes :: Mode a -> [Mode a]
- toGroup :: [a] -> Group a
- fromGroup :: Group a -> [a]
- parseBool :: String -> Maybe Bool
- type Name = String
- type Help = String
- type FlagHelp = String
- data Group a = Group {
- groupUnnamed :: [a]
- groupHidden :: [a]
- groupNamed :: [(Help, [a])]
- data Mode a = Mode {
- modeGroupModes :: Group (Mode a)
- modeNames :: [Name]
- modeValue :: a
- modeCheck :: a -> Either String a
- modeReform :: a -> Maybe [String]
- modeExpandAt :: Bool
- modeHelp :: Help
- modeHelpSuffix :: [String]
- modeArgs :: ([Arg a], Maybe (Arg a))
- modeGroupFlags :: Group (Flag a)
- data FlagInfo
- type Update a = String -> a -> Either String a
- data Flag a = Flag {}
- data Arg a = Arg {}
- class Remap (m :: TYPE LiftedRep -> Type) where
- remap :: (a -> b) -> (b -> (a, a -> b)) -> m a -> m b
- splitArgs :: String -> [String]
- joinArgs :: [String] -> String
- expandArgsAt :: [String] -> IO [String]
- data ProcessHandle
- data StdStream
- data CmdSpec
- data CreateProcess = CreateProcess {
- cmdspec :: CmdSpec
- cwd :: Maybe FilePath
- env :: Maybe [(String, String)]
- std_in :: StdStream
- std_out :: StdStream
- std_err :: StdStream
- close_fds :: Bool
- create_group :: Bool
- delegate_ctlc :: Bool
- detach_console :: Bool
- create_new_console :: Bool
- new_session :: Bool
- child_group :: Maybe GroupID
- child_user :: Maybe UserID
- use_process_jobs :: Bool
- createProcess_ :: String -> CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
- createPipe :: IO (Handle, Handle)
- createPipeFd :: IO (FD, FD)
- interruptProcessGroupOf :: ProcessHandle -> IO ()
- type Pid = CPid
- proc :: FilePath -> [String] -> CreateProcess
- shell :: String -> CreateProcess
- createProcess :: CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
- withCreateProcess :: CreateProcess -> (Maybe Handle -> Maybe Handle -> Maybe Handle -> ProcessHandle -> IO a) -> IO a
- cleanupProcess :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> IO ()
- spawnProcess :: FilePath -> [String] -> IO ProcessHandle
- spawnCommand :: String -> IO ProcessHandle
- callProcess :: FilePath -> [String] -> IO ()
- callCommand :: String -> IO ()
- readProcess :: FilePath -> [String] -> String -> IO String
- readCreateProcess :: CreateProcess -> String -> IO String
- readProcessWithExitCode :: FilePath -> [String] -> String -> IO (ExitCode, String, String)
- readCreateProcessWithExitCode :: CreateProcess -> String -> IO (ExitCode, String, String)
- showCommandForUser :: FilePath -> [String] -> String
- getPid :: ProcessHandle -> IO (Maybe Pid)
- getCurrentPid :: IO Pid
- waitForProcess :: ProcessHandle -> IO ExitCode
- getProcessExitCode :: ProcessHandle -> IO (Maybe ExitCode)
- terminateProcess :: ProcessHandle -> IO ()
- runCommand :: String -> IO ProcessHandle
- runProcess :: FilePath -> [String] -> Maybe FilePath -> Maybe [(String, String)] -> Maybe Handle -> Maybe Handle -> Maybe Handle -> IO ProcessHandle
- runInteractiveCommand :: String -> IO (Handle, Handle, Handle, ProcessHandle)
- runInteractiveProcess :: FilePath -> [String] -> Maybe FilePath -> Maybe [(String, String)] -> IO (Handle, Handle, Handle, ProcessHandle)
- system :: String -> IO ExitCode
- rawSystem :: String -> [String] -> IO ExitCode
- getTemporaryDirectory :: IO FilePath
- getUserDocumentsDirectory :: IO FilePath
- getAppUserDataDirectory :: FilePath -> IO FilePath
- getXdgDirectoryList :: XdgDirectoryList -> IO [FilePath]
- getXdgDirectory :: XdgDirectory -> FilePath -> IO FilePath
- getHomeDirectory :: IO FilePath
- setModificationTime :: FilePath -> UTCTime -> IO ()
- setAccessTime :: FilePath -> UTCTime -> IO ()
- getModificationTime :: FilePath -> IO UTCTime
- getAccessTime :: FilePath -> IO UTCTime
- getSymbolicLinkTarget :: FilePath -> IO FilePath
- isSymbolicLink :: FilePath -> IO Bool
- pathIsSymbolicLink :: FilePath -> IO Bool
- removeDirectoryLink :: FilePath -> IO ()
- createDirectoryLink :: FilePath -> FilePath -> IO ()
- createFileLink :: FilePath -> FilePath -> IO ()
- doesFileExist :: FilePath -> IO Bool
- doesDirectoryExist :: FilePath -> IO Bool
- doesPathExist :: FilePath -> IO Bool
- getFileSize :: FilePath -> IO Integer
- withCurrentDirectory :: FilePath -> IO a -> IO a
- setCurrentDirectory :: FilePath -> IO ()
- listDirectory :: FilePath -> IO [FilePath]
- getDirectoryContents :: FilePath -> IO [FilePath]
- exeExtension :: String
- findFilesWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO [FilePath]
- findFileWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO (Maybe FilePath)
- findFiles :: [FilePath] -> String -> IO [FilePath]
- findFile :: [FilePath] -> String -> IO (Maybe FilePath)
- findExecutablesInDirectories :: [FilePath] -> String -> IO [FilePath]
- findExecutables :: String -> IO [FilePath]
- findExecutable :: String -> IO (Maybe FilePath)
- makeRelativeToCurrentDirectory :: FilePath -> IO FilePath
- makeAbsolute :: FilePath -> IO FilePath
- canonicalizePath :: FilePath -> IO FilePath
- copyFileWithMetadata :: FilePath -> FilePath -> IO ()
- copyFile :: FilePath -> FilePath -> IO ()
- renamePath :: FilePath -> FilePath -> IO ()
- renameFile :: FilePath -> FilePath -> IO ()
- renameDirectory :: FilePath -> FilePath -> IO ()
- removeFile :: FilePath -> IO ()
- removePathForcibly :: FilePath -> IO ()
- removeDirectoryRecursive :: FilePath -> IO ()
- removeDirectory :: FilePath -> IO ()
- createDirectoryIfMissing :: Bool -> FilePath -> IO ()
- createDirectory :: FilePath -> IO ()
- copyPermissions :: FilePath -> FilePath -> IO ()
- setPermissions :: FilePath -> Permissions -> IO ()
- getPermissions :: FilePath -> IO Permissions
- setOwnerSearchable :: Bool -> Permissions -> Permissions
- setOwnerExecutable :: Bool -> Permissions -> Permissions
- setOwnerWritable :: Bool -> Permissions -> Permissions
- setOwnerReadable :: Bool -> Permissions -> Permissions
- emptyPermissions :: Permissions
- data Permissions
- data XdgDirectory
- data XdgDirectoryList
- charWidth :: Char -> Int
- isAbsolute :: FilePath -> Bool
- isRelative :: FilePath -> Bool
- makeValid :: FilePath -> FilePath
- isValid :: FilePath -> Bool
- normalise :: FilePath -> FilePath
- makeRelative :: FilePath -> FilePath -> FilePath
- equalFilePath :: FilePath -> FilePath -> Bool
- joinPath :: [FilePath] -> FilePath
- splitDirectories :: FilePath -> [FilePath]
- splitPath :: FilePath -> [FilePath]
- (</>) :: FilePath -> FilePath -> FilePath
- combine :: FilePath -> FilePath -> FilePath
- replaceDirectory :: FilePath -> String -> FilePath
- takeDirectory :: FilePath -> FilePath
- dropTrailingPathSeparator :: FilePath -> FilePath
- addTrailingPathSeparator :: FilePath -> FilePath
- hasTrailingPathSeparator :: FilePath -> Bool
- replaceBaseName :: FilePath -> String -> FilePath
- takeBaseName :: FilePath -> String
- takeFileName :: FilePath -> FilePath
- dropFileName :: FilePath -> FilePath
- replaceFileName :: FilePath -> String -> FilePath
- splitFileName :: FilePath -> (String, String)
- isDrive :: FilePath -> Bool
- hasDrive :: FilePath -> Bool
- dropDrive :: FilePath -> FilePath
- takeDrive :: FilePath -> FilePath
- joinDrive :: FilePath -> FilePath -> FilePath
- splitDrive :: FilePath -> (FilePath, FilePath)
- replaceExtensions :: FilePath -> String -> FilePath
- takeExtensions :: FilePath -> String
- dropExtensions :: FilePath -> FilePath
- splitExtensions :: FilePath -> (FilePath, String)
- stripExtension :: String -> FilePath -> Maybe FilePath
- isExtensionOf :: String -> FilePath -> Bool
- hasExtension :: FilePath -> Bool
- addExtension :: FilePath -> String -> FilePath
- dropExtension :: FilePath -> FilePath
- (<.>) :: FilePath -> String -> FilePath
- replaceExtension :: FilePath -> String -> FilePath
- (-<.>) :: FilePath -> String -> FilePath
- takeExtension :: FilePath -> String
- splitExtension :: FilePath -> (String, String)
- getSearchPath :: IO [FilePath]
- splitSearchPath :: String -> [FilePath]
- isExtSeparator :: Char -> Bool
- extSeparator :: Char
- isSearchPathSeparator :: Char -> Bool
- searchPathSeparator :: Char
- isPathSeparator :: Char -> Bool
- pathSeparators :: [Char]
- pathSeparator :: Char
- type AssertionPredicate = IO Bool
- class Assertable t where
- data HUnitFailure = HUnitFailure (Maybe SrcLoc) String
- class AssertionPredicable t where
- assertionPredicate :: t -> IO Bool
- assertFailure :: HasCallStack => String -> IO a
- assertBool :: HasCallStack => String -> Bool -> Assertion
- assertEqual :: (Eq a, Show a, HasCallStack) => String -> a -> a -> Assertion
- (@=?) :: (Eq a, Show a, HasCallStack) => a -> a -> Assertion
- (@?=) :: (Eq a, Show a, HasCallStack) => a -> a -> Assertion
- (@?) :: (AssertionPredicable t, HasCallStack) => t -> String -> Assertion
- assertString :: HasCallStack => String -> Assertion
- testCaseSteps :: TestName -> ((String -> IO ()) -> Assertion) -> TestTree
- testCase :: TestName -> Assertion -> TestTree
- testCaseInfo :: TestName -> IO String -> TestTree
- type Assertion = IO ()
- tests_Hledger :: TestTree
- tests_Read :: TestTree
- saveLatestDatesForFiles :: [LatestDatesForFile] -> IO ()
- saveLatestDates :: LatestDates -> FilePath -> IO ()
- ensureJournalFileExists :: FilePath -> IO ()
- requireJournalFileExists :: FilePath -> IO ()
- orDieTrying :: MonadIO m => ExceptT String m a -> m a
- readJournalFiles' :: [PrefixedFilePath] -> IO Journal
- readJournalFile' :: PrefixedFilePath -> IO Journal
- readJournal' :: Text -> IO Journal
- journalStrictChecks :: Journal -> Either String ()
- readJournalFilesAndLatestDates :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO (Journal, [LatestDatesForFile])
- readJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal
- readJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal
- readJournal :: InputOpts -> Maybe FilePath -> Text -> ExceptT String IO Journal
- defaultJournalPath :: IO String
- defaultJournal :: IO Journal
- type PrefixedFilePath = FilePath
- tmpostingrulep :: forall (m :: Type -> Type). Maybe Year -> JournalParser m TMPostingRule
- splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath)
- findReader :: forall (m :: Type -> Type). MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)
- runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a)
- tests_Common :: TestTree
- accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias
- aliasesFromOpts :: InputOpts -> [AccountAlias]
- bracketeddatetagsp :: forall (m :: Type -> Type). Maybe Year -> TextParser m [(TagName, Day)]
- postingcommentp :: forall (m :: Type -> Type). Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day)
- commenttagsp :: forall (m :: Type -> Type). TextParser m [Tag]
- transactioncommentp :: forall (m :: Type -> Type). TextParser m (Text, [Tag])
- followingcommentp :: forall (m :: Type -> Type). TextParser m Text
- isSameLineCommentStart :: Char -> Bool
- isLineCommentStart :: Char -> Bool
- emptyorcommentlinep :: forall (m :: Type -> Type). TextParser m ()
- multilinecommentp :: forall (m :: Type -> Type). TextParser m ()
- rawnumberp :: forall (m :: Type -> Type). TextParser m (Either AmbiguousNumber RawNumber)
- fromRawNumber :: RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
- numberp :: forall (m :: Type -> Type). Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
- lotcostp :: forall (m :: Type -> Type). JournalParser m ()
- balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion
- costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountPrice
- commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol
- parsemixedamount' :: String -> MixedAmount
- parsemixedamount :: String -> Either HledgerParseErrors MixedAmount
- parseamount' :: String -> Amount
- parseamount :: String -> Either HledgerParseErrors Amount
- amountp' :: forall (m :: Type -> Type). Bool -> JournalParser m Amount
- amountp :: forall (m :: Type -> Type). JournalParser m Amount
- spaceandamountormissingp :: forall (m :: Type -> Type). JournalParser m MixedAmount
- singlespacep :: forall (m :: Type -> Type). TextParser m ()
- singlespacedtextsatisfying1p :: forall (m :: Type -> Type). (Char -> Bool) -> TextParser m Text
- singlespacednoncommenttext1p :: forall (m :: Type -> Type). TextParser m Text
- singlespacedtext1p :: forall (m :: Type -> Type). TextParser m Text
- noncommenttext1p :: forall (m :: Type -> Type). TextParser m Text
- noncommenttextp :: forall (m :: Type -> Type). TextParser m Text
- doublequotedtextp :: forall (m :: Type -> Type). TextParser m Text
- accountnamep :: forall (m :: Type -> Type). TextParser m AccountName
- modifiedaccountnamep :: forall (m :: Type -> Type). JournalParser m AccountName
- secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day
- datetimep :: forall (m :: Type -> Type). JournalParser m LocalTime
- datep :: forall (m :: Type -> Type). JournalParser m Day
- descriptionp :: forall (m :: Type -> Type). TextParser m Text
- codep :: forall (m :: Type -> Type). TextParser m Text
- statusp :: forall (m :: Type -> Type). TextParser m Status
- journalAddFile :: (FilePath, Text) -> Journal -> Journal
- clearAccountAliases :: MonadState Journal m => m ()
- getAccountAliases :: MonadState Journal m => m [AccountAlias]
- addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
- getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName
- popParentAccount :: forall (m :: Type -> Type). JournalParser m ()
- pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m ()
- addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m ()
- addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m ()
- getAmountStyle :: forall (m :: Type -> Type). CommoditySymbol -> JournalParser m (Maybe AmountStyle)
- getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle)
- getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle))
- setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m ()
- getYear :: forall (m :: Type -> Type). JournalParser m (Maybe Year)
- setYear :: forall (m :: Type -> Type). Year -> JournalParser m ()
- journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal
- journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal
- journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal
- initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal
- parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal
- rawOptsToInputOpts :: Day -> RawOpts -> InputOpts
- data Reader (m :: Type -> Type) = Reader {
- rFormat :: StorageFormat
- rExtensions :: [String]
- rReadFn :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal
- rParser :: MonadIO m => ErroringJournalParser m ParsedJournal
- tests_Reports :: TestTree
- tests_AccountTransactionsReport :: TestTree
- accountTransactionsReportByCommodity :: AccountTransactionsReport -> [(CommoditySymbol, AccountTransactionsReport)]
- transactionRegisterDate :: WhichDate -> Query -> Query -> Transaction -> Day
- accountTransactionsReportItems :: Query -> Query -> MixedAmount -> (MixedAmount -> MixedAmount) -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)] -> [AccountTransactionsReportItem]
- accountTransactionsReport :: ReportSpec -> Journal -> Query -> AccountTransactionsReport
- triCommodityBalance :: CommoditySymbol -> (a, b, c, d, e, MixedAmount) -> MixedAmount
- triCommodityAmount :: CommoditySymbol -> (a, b, c, d, MixedAmount, f) -> MixedAmount
- triBalance :: (a, b, c, d, e, f) -> f
- triAmount :: (a, b, c, d, e, f) -> e
- triDate :: (a, Transaction, c, d, e, f) -> Day
- triOrigTransaction :: (a, b, c, d, e, f) -> a
- type AccountTransactionsReport = [AccountTransactionsReportItem]
- type AccountTransactionsReportItem = (Transaction, Transaction, Bool, Text, MixedAmount, MixedAmount)
- tests_BalanceReport :: TestTree
- balanceReport :: ReportSpec -> Journal -> BalanceReport
- flatShowsExclusiveBalance :: Bool
- type BalanceReport = ([BalanceReportItem], MixedAmount)
- type BalanceReportItem = (AccountName, AccountName, Int, MixedAmount)
- tests_BudgetReport :: TestTree
- budgetReportAsCsv :: ReportOpts -> BudgetReport -> [[Text]]
- budgetReportAsTable :: ReportOpts -> BudgetReport -> Table Text Text WideBuilder
- budgetReportAsText :: ReportOpts -> BudgetReport -> Text
- combineBudgetAndActual :: ReportOpts -> Journal -> MultiBalanceReport -> MultiBalanceReport -> BudgetReport
- budgetReport :: ReportSpec -> BalancingOpts -> DateSpan -> Journal -> BudgetReport
- type BudgetGoal = Change
- type BudgetTotal = Total
- type BudgetAverage = Average
- type BudgetCell = (Maybe Change, Maybe BudgetGoal)
- type BudgetReportRow = PeriodicReportRow DisplayName BudgetCell
- type BudgetReport = PeriodicReport DisplayName BudgetCell
- tests_EntriesReport :: TestTree
- entriesReport :: ReportSpec -> Journal -> EntriesReport
- type EntriesReport = [EntriesReportItem]
- type EntriesReportItem = Transaction
- tests_MultiBalanceReport :: TestTree
- balanceReportTableAsText :: ReportOpts -> Table Text Text WideBuilder -> Builder
- sortRowsLike :: [AccountName] -> [PeriodicReportRow DisplayName b] -> [PeriodicReportRow DisplayName b]
- sortRows :: ReportOpts -> Journal -> [MultiBalanceReportRow] -> [MultiBalanceReportRow]
- generateMultiBalanceReport :: ReportSpec -> Journal -> PriceOracle -> Set AccountName -> [(DateSpan, [Posting])] -> HashMap AccountName Account -> MultiBalanceReport
- getPostings :: ReportSpec -> Journal -> PriceOracle -> [Posting]
- getPostingsByColumn :: ReportSpec -> Journal -> PriceOracle -> [DateSpan] -> [(DateSpan, [Posting])]
- makeReportQuery :: ReportSpec -> DateSpan -> ReportSpec
- startingPostings :: ReportSpec -> Journal -> PriceOracle -> DateSpan -> [Posting]
- compoundBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount
- compoundBalanceReport :: ReportSpec -> Journal -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount
- multiBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> Set AccountName -> MultiBalanceReport
- multiBalanceReport :: ReportSpec -> Journal -> MultiBalanceReport
- type MultiBalanceReport = PeriodicReport DisplayName MixedAmount
- type MultiBalanceReportRow = PeriodicReportRow DisplayName MixedAmount
- tests_PostingsReport :: TestTree
- mkpostingsReportItem :: Bool -> Bool -> WhichDate -> Maybe Period -> Posting -> MixedAmount -> PostingsReportItem
- postingsReport :: ReportSpec -> Journal -> PostingsReport
- type PostingsReport = [PostingsReportItem]
- type PostingsReportItem = (Maybe Day, Maybe Period, Maybe Text, Posting, MixedAmount)
- prrDepth :: PeriodicReportRow DisplayName a -> Int
- prrDisplayName :: PeriodicReportRow DisplayName a -> AccountName
- prrFullName :: PeriodicReportRow DisplayName a -> AccountName
- treeDisplayName :: AccountName -> DisplayName
- flatDisplayName :: AccountName -> DisplayName
- prMapMaybeName :: (a -> Maybe b) -> PeriodicReport a c -> PeriodicReport b c
- prMapName :: (a -> b) -> PeriodicReport a c -> PeriodicReport b c
- periodicReportSpan :: PeriodicReport a b -> DateSpan
- prrAdd :: Semigroup b => PeriodicReportRow a b -> PeriodicReportRow a b -> PeriodicReportRow a b
- type Percentage = Decimal
- type Change = MixedAmount
- type Balance = MixedAmount
- type Total = MixedAmount
- type Average = MixedAmount
- data PeriodicReport a b = PeriodicReport {
- prDates :: [DateSpan]
- prRows :: [PeriodicReportRow a b]
- prTotals :: PeriodicReportRow () b
- data PeriodicReportRow a b = PeriodicReportRow {
- prrName :: a
- prrAmounts :: [b]
- prrTotal :: b
- prrAverage :: b
- data CompoundPeriodicReport a b = CompoundPeriodicReport {
- cbrTitle :: Text
- cbrDates :: [DateSpan]
- cbrSubreports :: [(Text, PeriodicReport a b, Bool)]
- cbrTotals :: PeriodicReportRow () b
- data CBCSubreportSpec a = CBCSubreportSpec {}
- data DisplayName = DisplayName {}
- rawOptsToReportSpec :: Day -> RawOpts -> Either String ReportSpec
- updateReportSpecWith :: (ReportOpts -> ReportOpts) -> ReportSpec -> Either String ReportSpec
- updateReportSpec :: ReportOpts -> ReportSpec -> Either String ReportSpec
- reportOptsToSpec :: Day -> ReportOpts -> Either String ReportSpec
- class HasReportSpec c where
- reportSpec :: Lens' c ReportSpec
- rsDay :: Lens' c Day
- rsQuery :: Lens' c Query
- rsQueryOpts :: Lens' c [QueryOpt]
- rsReportOpts :: Lens' c ReportOpts
- class HasReportOptsNoUpdate a => HasReportOpts a where
- reportOpts :: ReportableLens' a ReportOpts
- period :: ReportableLens' a Period
- statuses :: ReportableLens' a [Status]
- depth :: ReportableLens' a (Maybe Int)
- date2 :: ReportableLens' a Bool
- real :: ReportableLens' a Bool
- querystring :: ReportableLens' a [Text]
- class HasReportOptsNoUpdate c where
- reportOptsNoUpdate :: Lens' c ReportOpts
- accountlistmode :: Lens' c AccountListMode
- average :: Lens' c Bool
- balanceaccum :: Lens' c BalanceAccumulation
- balancecalc :: Lens' c BalanceCalculation
- budgetpat :: Lens' c (Maybe Text)
- color__ :: Lens' c Bool
- conversionop :: Lens' c (Maybe ConversionOp)
- date2NoUpdate :: Lens' c Bool
- declared :: Lens' c Bool
- depthNoUpdate :: Lens' c (Maybe Int)
- drop__ :: Lens' c Int
- empty__ :: Lens' c Bool
- format :: Lens' c StringFormat
- infer_prices :: Lens' c Bool
- interval :: Lens' c Interval
- invert :: Lens' c Bool
- layout :: Lens' c Layout
- no_elide :: Lens' c Bool
- no_total :: Lens' c Bool
- normalbalance :: Lens' c (Maybe NormalSign)
- percent :: Lens' c Bool
- periodNoUpdate :: Lens' c Period
- pretty :: Lens' c Bool
- querystringNoUpdate :: Lens' c [Text]
- realNoUpdate :: Lens' c Bool
- related :: Lens' c Bool
- row_total :: Lens' c Bool
- show_costs :: Lens' c Bool
- sort_amount :: Lens' c Bool
- statusesNoUpdate :: Lens' c [Status]
- summary_only :: Lens' c Bool
- transpose__ :: Lens' c Bool
- txn_dates :: Lens' c Bool
- value :: Lens' c (Maybe ValuationType)
- setEither :: ((a -> Either e b) -> s -> Either e t) -> b -> s -> Either e t
- overEither :: ((a -> Either e b) -> s -> Either e t) -> (a -> b) -> s -> Either e t
- reportPeriodName :: BalanceAccumulation -> [DateSpan] -> DateSpan -> Text
- reportPeriodOrJournalLastDay :: ReportSpec -> Journal -> Maybe Day
- reportPeriodLastDay :: ReportSpec -> Maybe Day
- reportPeriodOrJournalStart :: ReportSpec -> Journal -> Maybe Day
- reportPeriodStart :: ReportSpec -> Maybe Day
- reportEndDate :: Journal -> ReportSpec -> Maybe Day
- reportStartDate :: Journal -> ReportSpec -> Maybe Day
- reportSpanBothDates :: Journal -> ReportSpec -> (DateSpan, [DateSpan])
- reportSpan :: Journal -> ReportSpec -> (DateSpan, [DateSpan])
- queryFromFlags :: ReportOpts -> Query
- valuationAfterSum :: ReportOpts -> Maybe (Maybe CommoditySymbol)
- mixedAmountApplyValuationAfterSumFromOptsWith :: ReportOpts -> Journal -> PriceOracle -> DateSpan -> MixedAmount -> MixedAmount
- journalApplyValuationFromOptsWith :: ReportSpec -> Journal -> PriceOracle -> Journal
- journalApplyValuationFromOpts :: ReportSpec -> Journal -> Journal
- journalValueAndFilterPostingsWith :: ReportSpec -> Journal -> PriceOracle -> Journal
- journalValueAndFilterPostings :: ReportSpec -> Journal -> Journal
- flat_ :: ReportOpts -> Bool
- tree_ :: ReportOpts -> Bool
- whichDate :: ReportOpts -> WhichDate
- postingDateFn :: ReportOpts -> Posting -> Day
- transactionDateFn :: ReportOpts -> Transaction -> Day
- reportOptsToggleStatus :: Status -> ReportOpts -> ReportOpts
- simplifyStatuses :: Ord a => [a] -> [a]
- intervalFromRawOpts :: RawOpts -> Interval
- balanceAccumulationOverride :: RawOpts -> Maybe BalanceAccumulation
- setDefaultConversionOp :: ConversionOp -> ReportSpec -> ReportSpec
- defreportspec :: ReportSpec
- rawOptsToReportOpts :: Day -> RawOpts -> ReportOpts
- defreportopts :: ReportOpts
- data BalanceCalculation
- data BalanceAccumulation
- data AccountListMode
- data Layout
- = LayoutWide (Maybe Int)
- | LayoutTall
- | LayoutBare
- | LayoutTidy
- data ReportOpts = ReportOpts {
- period_ :: Period
- interval_ :: Interval
- statuses_ :: [Status]
- conversionop_ :: Maybe ConversionOp
- value_ :: Maybe ValuationType
- infer_prices_ :: Bool
- depth_ :: Maybe Int
- date2_ :: Bool
- empty_ :: Bool
- no_elide_ :: Bool
- real_ :: Bool
- format_ :: StringFormat
- pretty_ :: Bool
- querystring_ :: [Text]
- average_ :: Bool
- related_ :: Bool
- txn_dates_ :: Bool
- balancecalc_ :: BalanceCalculation
- balanceaccum_ :: BalanceAccumulation
- budgetpat_ :: Maybe Text
- accountlistmode_ :: AccountListMode
- drop_ :: Int
- declared_ :: Bool
- row_total_ :: Bool
- no_total_ :: Bool
- summary_only_ :: Bool
- show_costs_ :: Bool
- sort_amount_ :: Bool
- percent_ :: Bool
- invert_ :: Bool
- normalbalance_ :: Maybe NormalSign
- color_ :: Bool
- transpose_ :: Bool
- layout_ :: Layout
- data ReportSpec = ReportSpec {
- _rsReportOpts :: ReportOpts
- _rsDay :: Day
- _rsQuery :: Query
- _rsQueryOpts :: [QueryOpt]
- tests_Data :: TestTree
- tests_Ledger :: TestTree
- ledgerCommodities :: Ledger -> [CommoditySymbol]
- ledgerDateSpan :: Ledger -> DateSpan
- ledgerPostings :: Ledger -> [Posting]
- ledgerLeafAccounts :: Ledger -> [Account]
- ledgerTopAccounts :: Ledger -> [Account]
- ledgerRootAccount :: Ledger -> Account
- ledgerAccount :: Ledger -> AccountName -> Maybe Account
- ledgerAccountNames :: Ledger -> [AccountName]
- ledgerFromJournal :: Query -> Journal -> Ledger
- nullledger :: Ledger
- showAccountsBoringFlag :: Account -> String
- showAccounts :: Account -> String
- printAccounts :: Account -> IO ()
- lookupAccount :: AccountName -> [Account] -> Maybe Account
- sortAccountNamesByDeclaration :: Journal -> Bool -> [AccountName] -> [AccountName]
- accountSetDeclarationInfo :: Journal -> Account -> Account
- sortAccountTreeByAmount :: NormalSign -> Account -> Account
- filterAccounts :: (Account -> Bool) -> Account -> [Account]
- flattenAccounts :: Account -> [Account]
- pruneAccounts :: (Account -> Bool) -> Account -> Maybe Account
- clipAccountsAndAggregate :: Maybe Int -> [Account] -> [Account]
- clipAccounts :: Int -> Account -> Account
- sumAccounts :: Account -> Account
- anyAccounts :: (Account -> Bool) -> Account -> Bool
- mapAccounts :: (Account -> Account) -> Account -> Account
- accountsLevels :: Account -> [[Account]]
- parentAccounts :: Account -> [Account]
- accountTree :: AccountName -> [AccountName] -> Account
- accountsFromPostings :: [Posting] -> [Account]
- nullacct :: Account
- class HasInputOpts c where
- inputOpts :: Lens' c InputOpts
- aliases :: Lens' c [String]
- anon__ :: Lens' c Bool
- auto__ :: Lens' c Bool
- balancingopts :: Lens' c BalancingOpts
- forecast :: Lens' c (Maybe DateSpan)
- infer_costs :: Lens' c Bool
- infer_equity :: Lens' c Bool
- ioDay :: Lens' c Day
- mformat :: Lens' c (Maybe StorageFormat)
- mrules_file :: Lens' c (Maybe FilePath)
- new__ :: Lens' c Bool
- new_save :: Lens' c Bool
- pivot :: Lens' c String
- reportspan :: Lens' c DateSpan
- strict :: Lens' c Bool
- verbose_tags :: Lens' c Bool
- forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan
- definputopts :: InputOpts
- data InputOpts = InputOpts {
- mformat_ :: Maybe StorageFormat
- mrules_file_ :: Maybe FilePath
- aliases_ :: [String]
- anon_ :: Bool
- new_ :: Bool
- new_save_ :: Bool
- pivot_ :: String
- forecast_ :: Maybe DateSpan
- verbose_tags_ :: Bool
- reportspan_ :: DateSpan
- auto_ :: Bool
- infer_equity_ :: Bool
- infer_costs_ :: Bool
- balancingopts_ :: BalancingOpts
- strict_ :: Bool
- _ioDay :: Day
- tests_Balancing :: TestTree
- class HasBalancingOpts c where
- journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal
- journalCheckBalanceAssertions :: Journal -> Maybe String
- balanceTransactionHelper :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)])
- balanceTransaction :: BalancingOpts -> Transaction -> Either String Transaction
- isTransactionBalanced :: BalancingOpts -> Transaction -> Bool
- defbalancingopts :: BalancingOpts
- data BalancingOpts = BalancingOpts {}
- journalCheckRecentAssertions :: Day -> Journal -> Either String ()
- journalCheckPairedConversionPostings :: Journal -> Either String ()
- journalCheckTags :: Journal -> Either String ()
- journalCheckPayees :: Journal -> Either String ()
- journalCheckCommodities :: Journal -> Either String ()
- journalCheckAccounts :: Journal -> Either String ()
- journalCheckUniqueleafnames :: Journal -> Either String ()
- tests_Journal :: TestTree
- samplejournalMaybeExplicit :: Bool -> Journal
- samplejournal :: Journal
- journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal
- journalPivot :: Text -> Journal -> Journal
- journalLastDay :: Bool -> Journal -> Maybe Day
- journalEndDate :: Bool -> Journal -> Maybe Day
- journalStartDate :: Bool -> Journal -> Maybe Day
- journalDateSpanBothDates :: Journal -> DateSpan
- journalDateSpan :: Bool -> Journal -> DateSpan
- journalMarkRedundantCosts :: Journal -> Either String Journal
- journalInferCostsFromEquity :: Journal -> Either String Journal
- journalInferEquityFromCosts :: Bool -> Journal -> Journal
- journalToCost :: ConversionOp -> Journal -> Journal
- journalInferMarketPricesFromTransactions :: Journal -> Journal
- canonicalStyleFrom :: [AmountStyle] -> AmountStyle
- commodityStylesFromAmounts :: [Amount] -> Either String (Map CommoditySymbol AmountStyle)
- journalInferCommodityStyles :: Journal -> Either String Journal
- journalCommodityStylesWith :: Rounding -> Journal -> Map CommoditySymbol AmountStyle
- journalCommodityStyles :: Journal -> Map CommoditySymbol AmountStyle
- journalStyleAmounts :: Journal -> Either String Journal
- journalModifyTransactions :: Bool -> Day -> Journal -> Either String Journal
- journalUntieTransactions :: Transaction -> Transaction
- journalNumberTransactions :: Journal -> Journal
- journalNumberAndTieTransactions :: Journal -> Journal
- journalSetLastReadTime :: POSIXTime -> Journal -> Journal
- journalReverse :: Journal -> Journal
- journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal
- journalMapPostings :: (Posting -> Posting) -> Journal -> Journal
- journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal
- filterTransactionRelatedPostings :: Query -> Transaction -> Transaction
- filterTransactionPostingsExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Transaction
- filterTransactionPostings :: Query -> Transaction -> Transaction
- filterPostingAmount :: Query -> Posting -> Maybe Posting
- filterTransactionAmounts :: Query -> Transaction -> Transaction
- filterJournalAmounts :: Query -> Journal -> Journal
- filterJournalRelatedPostings :: Query -> Journal -> Journal
- filterJournalPostings :: Query -> Journal -> Journal
- filterJournalTransactions :: Query -> Journal -> Journal
- journalPostingsAddAccountTags :: Journal -> Journal
- journalAccountTypes :: Journal -> Map AccountName AccountType
- journalAddAccountTypes :: Journal -> Journal
- journalAccountType :: Journal -> AccountName -> Maybe AccountType
- journalConversionAccount :: Journal -> AccountName
- journalTransactionsSimilarTo :: Journal -> Text -> Query -> SimilarityScore -> Int -> [(DateWeightedSimilarityScore, Age, SimilarityScore, Transaction)]
- journalInheritedAccountTags :: Journal -> AccountName -> [Tag]
- journalAccountTags :: Journal -> AccountName -> [Tag]
- journalAccountNameTree :: Journal -> Tree AccountName
- journalLeafAccountNames :: Journal -> [AccountName]
- journalAccountNames :: Journal -> [AccountName]
- journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName]
- journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName]
- journalLeafAccountNamesDeclared :: Journal -> [AccountName]
- journalAccountNamesDeclared :: Journal -> [AccountName]
- journalAccountNamesImplied :: Journal -> [AccountName]
- journalAccountNamesUsed :: Journal -> [AccountName]
- journalTagsDeclaredOrUsed :: Journal -> [TagName]
- journalTagsUsed :: Journal -> [TagName]
- journalTagsDeclared :: Journal -> [TagName]
- journalPayeesDeclaredOrUsed :: Journal -> [Payee]
- journalPayeesUsed :: Journal -> [Payee]
- journalPayeesDeclared :: Journal -> [Payee]
- journalDescriptions :: Journal -> [Text]
- journalCommodities :: Journal -> Set CommoditySymbol
- journalCommoditiesDeclared :: Journal -> [CommoditySymbol]
- showJournalAmountsDebug :: Journal -> String
- journalPostingAmounts :: Journal -> [MixedAmount]
- journalPostings :: Journal -> [Posting]
- journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction
- journalNextTransaction :: Journal -> Transaction -> Maybe Transaction
- journalTransactionAt :: Journal -> Integer -> Maybe Transaction
- addPriceDirective :: PriceDirective -> Journal -> Journal
- addPeriodicTransaction :: PeriodicTransaction -> Journal -> Journal
- addTransactionModifier :: TransactionModifier -> Journal -> Journal
- addTransaction :: Transaction -> Journal -> Journal
- journalFilePaths :: Journal -> [FilePath]
- journalFilePath :: Journal -> FilePath
- nulljournal :: Journal
- dbgJournalAcctDeclOrder :: String -> Journal -> Journal
- journalRenumberAccountDeclarations :: Journal -> Journal
- journalConcat :: Journal -> Journal -> Journal
- type JournalParser (m :: Type -> Type) a = StateT Journal (ParsecT HledgerParseErrorData Text m) a
- type ErroringJournalParser (m :: Type -> Type) a = StateT Journal (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a
- readJsonFile :: FromJSON a => FilePath -> IO a
- writeJsonFile :: ToJSON a => FilePath -> a -> IO ()
- toJsonText :: ToJSON a => a -> Text
- checkPeriodicTransactionStartDate :: Interval -> DateSpan -> Text -> Maybe String
- runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction]
- journalCheckOrdereddates :: WhichDate -> Journal -> Either String ()
- makeBalanceAssertionErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
- makePostingAccountErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
- transactionFindPostingIndex :: (Posting -> Bool) -> Transaction -> Maybe Int
- makePostingErrorExcerpt :: Posting -> (Posting -> Transaction -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
- makeTransactionErrorExcerpt :: Transaction -> (Transaction -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
- makeAccountTagErrorExcerpt :: (AccountName, AccountDeclarationInfo) -> TagName -> (FilePath, Int, Maybe (Int, Maybe Int), Text)
- tests_Timeclock :: TestTree
- timeclockEntriesToTransactions :: LocalTime -> [TimeclockEntry] -> [Transaction]
- modifyTransactions :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Map CommoditySymbol AmountStyle -> Day -> Bool -> [TransactionModifier] -> [Transaction] -> Either String [Transaction]
- tests_Query :: TestTree
- matchesPriceDirective :: Query -> PriceDirective -> Bool
- matchesTags :: Regexp -> Maybe Regexp -> [Tag] -> Bool
- matchesPayeeWIP :: Query -> Payee -> Bool
- matchesDescription :: Query -> Text -> Bool
- matchesTransactionExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Bool
- matchesTransaction :: Query -> Transaction -> Bool
- matchesPostingExtra :: (AccountName -> Maybe AccountType) -> Query -> Posting -> Bool
- matchesPosting :: Query -> Posting -> Bool
- matchesAccountExtra :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Query -> AccountName -> Bool
- matchesAccount :: Query -> AccountName -> Bool
- matchesMixedAmount :: Query -> MixedAmount -> Bool
- matchesAmount :: Query -> Amount -> Bool
- matchesCommodity :: Query -> CommoditySymbol -> Bool
- inAccountQuery :: [QueryOpt] -> Maybe Query
- inAccount :: [QueryOpt] -> Maybe (AccountName, Bool)
- queryDepth :: Query -> Maybe Int
- queryDateSpan' :: Query -> DateSpan
- queryDateSpan :: Bool -> Query -> DateSpan
- queryEndDate :: Bool -> Query -> Maybe Day
- queryStartDate :: Bool -> Query -> Maybe Day
- queryIsTransactionRelated :: Query -> Bool
- queryIsStartDateOnly :: Bool -> Query -> Bool
- queryIsSym :: Query -> Bool
- queryIsAmt :: Query -> Bool
- queryIsReal :: Query -> Bool
- queryIsDepth :: Query -> Bool
- queryIsType :: Query -> Bool
- queryIsAcct :: Query -> Bool
- queryIsTag :: Query -> Bool
- queryIsDesc :: Query -> Bool
- queryIsCode :: Query -> Bool
- queryIsStatus :: Query -> Bool
- queryIsDateOrDate2 :: Query -> Bool
- queryIsDate2 :: Query -> Bool
- queryIsDate :: Query -> Bool
- queryIsNull :: Query -> Bool
- matchesQuery :: (Query -> Bool) -> Query -> Bool
- filterQueryOrNotQuery :: (Query -> Bool) -> Query -> Query
- filterQuery :: (Query -> Bool) -> Query -> Query
- simplifyQuery :: Query -> Query
- parseAccountType :: Bool -> Text -> Either String AccountType
- parseQueryTerm :: Day -> Text -> Either String (Query, [QueryOpt])
- queryprefixes :: [Text]
- words'' :: [Text] -> Text -> [Text]
- parseQueryList :: Day -> [Text] -> Either String (Query, [QueryOpt])
- parseQuery :: Day -> Text -> Either String (Query, [QueryOpt])
- generatedTransactionTag :: Query
- noteTag :: Maybe Text -> Either RegexError Query
- payeeTag :: Maybe Text -> Either RegexError Query
- data Query
- data OrdPlus
- data QueryOpt
- tests_Transaction :: TestTree
- annotateErrorWithTransaction :: Transaction -> String -> String
- transactionFile :: Transaction -> FilePath
- transactionAmounts :: Transaction -> [MixedAmount]
- transactionMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Transaction -> Transaction
- transactionMapPostings :: (Posting -> Posting) -> Transaction -> Transaction
- transactionApplyAliases :: [AccountAlias] -> Transaction -> Either RegexError Transaction
- partitionAndCheckConversionPostings :: Bool -> Map AccountName AccountType -> [IdxPosting] -> Either Text ([(IdxPosting, IdxPosting)], ([IdxPosting], [IdxPosting]))
- transactionInferCostsFromEquity :: Bool -> Map AccountName AccountType -> Transaction -> Either String Transaction
- transactionAddInferredEquityPostings :: Bool -> AccountName -> Transaction -> Transaction
- transactionToCost :: ConversionOp -> Transaction -> Transaction
- transactionApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Transaction -> Transaction
- transactionTransformPostings :: (Posting -> Posting) -> Transaction -> Transaction
- txnUntieKnot :: Transaction -> Transaction
- txnTieKnot :: Transaction -> Transaction
- transactionDateOrDate2 :: WhichDate -> Transaction -> Day
- transactionDate2 :: Transaction -> Day
- transactionsPostings :: [Transaction] -> [Posting]
- balancedVirtualPostings :: Transaction -> [Posting]
- virtualPostings :: Transaction -> [Posting]
- assignmentPostings :: Transaction -> [Posting]
- realPostings :: Transaction -> [Posting]
- hasRealPostings :: Transaction -> Bool
- showTransactionBeancount :: Transaction -> Text
- showTransactionLineFirstPart :: Transaction -> Text
- showTransactionOneLineAmounts :: Transaction -> Text
- showTransaction :: Transaction -> Text
- transactionNote :: Transaction -> Text
- transactionPayee :: Transaction -> Text
- transaction :: Day -> [Posting] -> Transaction
- nulltransaction :: Transaction
- tests_Posting :: TestTree
- commentAddTagNextLine :: Text -> Tag -> Text
- commentAddTagUnspaced :: Text -> Tag -> Text
- commentAddTag :: Text -> Tag -> Text
- commentJoin :: Text -> Text -> Text
- postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting
- postingPriceDirectivesFromCost :: Posting -> [PriceDirective]
- postingAddInferredEquityPostings :: Bool -> Text -> Posting -> [Posting]
- postingToCost :: ConversionOp -> Posting -> Maybe Posting
- postingApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Posting -> Posting
- postingAddTags :: Posting -> [Tag] -> Posting
- postingApplyAliases :: [AccountAlias] -> Posting -> Either RegexError Posting
- isEmptyPosting :: Posting -> Bool
- isPostingInDateSpan' :: WhichDate -> DateSpan -> Posting -> Bool
- isPostingInDateSpan :: DateSpan -> Posting -> Bool
- relatedPostings :: Posting -> [Posting]
- transactionAllTags :: Transaction -> [Tag]
- postingAllTags :: Posting -> [Tag]
- postingStatus :: Posting -> Status
- postingDateOrDate2 :: WhichDate -> Posting -> Day
- postingDate2 :: Posting -> Day
- postingDate :: Posting -> Day
- postingStripPrices :: Posting -> Posting
- sumPostings :: [Posting] -> MixedAmount
- accountNamesFromPostings :: [Posting] -> [AccountName]
- hasBalanceAssignment :: Posting -> Bool
- hasAmount :: Posting -> Bool
- isBalancedVirtual :: Posting -> Bool
- isVirtual :: Posting -> Bool
- isReal :: Posting -> Bool
- renderCommentLines :: Text -> [Text]
- showAccountNameBeancount :: Maybe Int -> AccountName -> Text
- postingAsLinesBeancount :: Bool -> Int -> Int -> Posting -> ([Text], Int, Int)
- postingsAsLinesBeancount :: [Posting] -> [Text]
- showAccountName :: Maybe Int -> PostingType -> AccountName -> Text
- postingAsLines :: Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int)
- postingsAsLines :: Bool -> [Posting] -> [Text]
- showPostingLines :: Posting -> [Text]
- showPosting :: Posting -> String
- originalPosting :: Posting -> Posting
- showBalanceAssertion :: BalanceAssertion -> WideBuilder
- balassertTotInc :: Amount -> Maybe BalanceAssertion
- balassertParInc :: Amount -> Maybe BalanceAssertion
- balassertTot :: Amount -> Maybe BalanceAssertion
- balassert :: Amount -> Maybe BalanceAssertion
- nullassertion :: BalanceAssertion
- nullsourcepos :: (SourcePos, SourcePos)
- vpost' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting
- post' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting
- vpost :: AccountName -> Amount -> Posting
- post :: AccountName -> Amount -> Posting
- posting :: Posting
- nullposting :: Posting
- postingStyleAmounts :: Map CommoditySymbol AmountStyle -> Posting -> Posting
- postingApplyCommodityStyles :: Map CommoditySymbol AmountStyle -> Posting -> Posting
- tests_Valuation :: TestTree
- marketPriceReverse :: MarketPrice -> MarketPrice
- mixedAmountGainAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount
- mixedAmountApplyGain :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount
- mixedAmountValueAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount
- mixedAmountApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount
- mixedAmountToCost :: Map CommoditySymbol AmountStyle -> ConversionOp -> MixedAmount -> MixedAmount
- amountPriceDirectiveFromCost :: Day -> Amount -> Maybe PriceDirective
- priceDirectiveToMarketPrice :: PriceDirective -> MarketPrice
- journalPriceOracle :: Bool -> Journal -> PriceOracle
- valuationTypeValuationCommodity :: ValuationType -> Maybe CommoditySymbol
- data ConversionOp
- data ValuationType
- type PriceOracle = (Day, CommoditySymbol, Maybe CommoditySymbol) -> Maybe (CommoditySymbol, Quantity)
- tests_Amount :: TestTree
- mixedAmountStripPrices :: MixedAmount -> MixedAmount
- mixedAmountSetPrecisionMax :: Word8 -> MixedAmount -> MixedAmount
- mixedAmountSetPrecisionMin :: Word8 -> MixedAmount -> MixedAmount
- mixedAmountSetFullPrecision :: MixedAmount -> MixedAmount
- mixedAmountSetPrecision :: AmountPrecision -> MixedAmount -> MixedAmount
- showMixedAmountLinesB :: AmountDisplayOpts -> MixedAmount -> [WideBuilder]
- showMixedAmountB :: AmountDisplayOpts -> MixedAmount -> WideBuilder
- showMixedAmountDebug :: MixedAmount -> String
- showMixedAmountElided :: Int -> Bool -> MixedAmount -> String
- showMixedAmountOneLineWithoutPrice :: Bool -> MixedAmount -> String
- showMixedAmountWithoutPrice :: Bool -> MixedAmount -> String
- showMixedAmountWithZeroCommodity :: MixedAmount -> String
- showMixedAmountOneLine :: MixedAmount -> String
- showMixedAmount :: MixedAmount -> String
- mixedAmountUnstyled :: MixedAmount -> MixedAmount
- mixedAmountSetStyles :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
- styleMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
- canonicaliseMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
- mixedAmountCost :: MixedAmount -> MixedAmount
- mapMixedAmount :: (Amount -> Amount) -> MixedAmount -> MixedAmount
- filterMixedAmountByCommodity :: CommoditySymbol -> MixedAmount -> MixedAmount
- filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount
- unifyMixedAmount :: MixedAmount -> Maybe Amount
- maCommodities :: MixedAmount -> Set CommoditySymbol
- amountsRaw :: MixedAmount -> [Amount]
- amountsPreservingZeros :: MixedAmount -> [Amount]
- amounts :: MixedAmount -> [Amount]
- maIsNonZero :: MixedAmount -> Bool
- maIsZero :: MixedAmount -> Bool
- mixedAmountIsZero :: MixedAmount -> Bool
- mixedAmountLooksZero :: MixedAmount -> Bool
- isNegativeMixedAmount :: MixedAmount -> Maybe Bool
- averageMixedAmounts :: [MixedAmount] -> MixedAmount
- multiplyMixedAmount :: Quantity -> MixedAmount -> MixedAmount
- divideMixedAmount :: Quantity -> MixedAmount -> MixedAmount
- maSum :: Foldable t => t MixedAmount -> MixedAmount
- maMinus :: MixedAmount -> MixedAmount -> MixedAmount
- maPlus :: MixedAmount -> MixedAmount -> MixedAmount
- maNegate :: MixedAmount -> MixedAmount
- maAddAmounts :: Foldable t => MixedAmount -> t Amount -> MixedAmount
- maAddAmount :: MixedAmount -> Amount -> MixedAmount
- mixedAmount :: Amount -> MixedAmount
- mixed :: Foldable t => t Amount -> MixedAmount
- isMissingMixedAmount :: MixedAmount -> Bool
- missingmixedamt :: MixedAmount
- nullmixedamt :: MixedAmount
- showAmountDebug :: Amount -> String
- showAmountWithZeroCommodity :: Amount -> String
- showAmountWithoutPrice :: Amount -> String
- cshowAmount :: Amount -> String
- showAmountB :: AmountDisplayOpts -> Amount -> WideBuilder
- showAmount :: Amount -> String
- showAmountPrice :: Amount -> WideBuilder
- amountStripPrices :: Amount -> Amount
- withDecimalPoint :: Amount -> Maybe Char -> Amount
- setAmountDecimalPoint :: Maybe Char -> Amount -> Amount
- amountUnstyled :: Amount -> Amount
- amountstyle :: AmountStyle
- amountStylesSetRounding :: Rounding -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle
- amountStyleSetRounding :: Rounding -> AmountStyle -> AmountStyle
- amountSetStyles :: Map CommoditySymbol AmountStyle -> Amount -> Amount
- styleAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount
- canonicaliseAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount
- withInternalPrecision :: Amount -> Word8 -> Amount
- setAmountInternalPrecision :: Word8 -> Amount -> Amount
- amountDisplayPrecision :: Amount -> Word8
- amountInternalPrecision :: Amount -> Word8
- defaultMaxPrecision :: Word8
- amountSetFullPrecisionOr :: Maybe Word8 -> Amount -> Amount
- amountSetFullPrecision :: Amount -> Amount
- amountSetPrecisionMax :: Word8 -> Amount -> Amount
- amountSetPrecisionMin :: Word8 -> Amount -> Amount
- amountSetPrecision :: AmountPrecision -> Amount -> Amount
- withPrecision :: Amount -> AmountPrecision -> Amount
- amountIsZero :: Amount -> Bool
- amountLooksZero :: Amount -> Bool
- isNegativeAmount :: Amount -> Bool
- invertAmount :: Amount -> Amount
- multiplyAmount :: Quantity -> Amount -> Amount
- divideAmount :: Quantity -> Amount -> Amount
- amountCost :: Amount -> Amount
- amountWithCommodity :: CommoditySymbol -> Amount -> Amount
- (@@) :: Amount -> Amount -> Amount
- at :: Amount -> Amount -> Amount
- per :: Quantity -> Amount
- gbp :: DecimalRaw Integer -> Amount
- eur :: DecimalRaw Integer -> Amount
- usd :: DecimalRaw Integer -> Amount
- hrs :: Quantity -> Amount
- num :: Quantity -> Amount
- missingamt :: Amount
- nullamt :: Amount
- csvDisplay :: AmountDisplayOpts
- oneLine :: AmountDisplayOpts
- noPrice :: AmountDisplayOpts
- noColour :: AmountDisplayOpts
- quoteCommoditySymbolIfNeeded :: Text -> Text
- isNonsimpleCommodityChar :: Char -> Bool
- showCommoditySymbol :: Text -> Text
- data AmountDisplayOpts = AmountDisplayOpts {}
- tests_StringFormat :: TestTree
- defaultStringFormatStyle :: [StringFormatComponent] -> StringFormat
- parseStringFormat :: Text -> Either String StringFormat
- defaultBalanceLineFormat :: StringFormat
- data StringFormat
- data StringFormatComponent
- data ReportItemField
- tests_AccountName :: TestTree
- beancountTopLevelAccounts :: IsString a => [a]
- accountNameToBeancount :: AccountName -> BeancountAccountName
- accountNameToAccountOnlyRegexCI :: AccountName -> Regexp
- accountNameToAccountOnlyRegex :: AccountName -> Regexp
- accountNameToAccountRegexCI :: AccountName -> Regexp
- accountNameToAccountRegex :: AccountName -> Regexp
- escapeName :: AccountName -> Text
- clipOrEllipsifyAccountName :: Maybe Int -> AccountName -> AccountName
- clipAccountName :: Maybe Int -> AccountName -> AccountName
- elideAccountName :: Int -> AccountName -> AccountName
- accountNameTreeFrom :: [AccountName] -> Tree AccountName
- subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName]
- isSubAccountNameOf :: AccountName -> AccountName -> Bool
- isAccountNamePrefixOf :: AccountName -> AccountName -> Bool
- parentAccountNames :: AccountName -> [AccountName]
- parentAccountName :: AccountName -> AccountName
- topAccountNames :: [AccountName] -> [AccountName]
- expandAccountName :: AccountName -> [AccountName]
- expandAccountNames :: [AccountName] -> [AccountName]
- accountNameDrop :: Int -> AccountName -> AccountName
- accountNameApplyAliasesMemo :: [AccountAlias] -> AccountName -> Either RegexError AccountName
- accountNameApplyAliases :: [AccountAlias] -> AccountName -> Either RegexError AccountName
- concatAccountNames :: [AccountName] -> AccountName
- joinAccountNames :: AccountName -> AccountName -> AccountName
- accountNameWithPostingType :: PostingType -> AccountName -> AccountName
- accountNameWithoutPostingType :: AccountName -> AccountName
- accountNamePostingType :: AccountName -> PostingType
- unbudgetedAccountName :: Text
- accountNameLevel :: AccountName -> Int
- accountNameType :: Map AccountName AccountType -> AccountName -> Maybe AccountType
- accountNameInferType :: AccountName -> Maybe AccountType
- expenseAccountRegex :: Regexp
- revenueAccountRegex :: Regexp
- conversionAccountRegex :: Regexp
- equityAccountRegex :: Regexp
- liabilityAccountRegex :: Regexp
- cashAccountRegex :: Regexp
- assetAccountRegex :: Regexp
- accountSummarisedName :: AccountName -> Text
- accountLeafName :: AccountName -> Text
- accountNameFromComponents :: [Text] -> AccountName
- accountNameComponents :: AccountName -> [Text]
- acctsep :: Text
- acctsepchar :: Char
- tests_Dates :: TestTree
- nulldate :: Day
- emptydatespan :: DateSpan
- nulldatespan :: DateSpan
- periodexprp :: forall (m :: Type -> Type). Day -> TextParser m (Interval, DateSpan)
- yearp :: forall (m :: Type -> Type). TextParser m Integer
- isDateSepChar :: Char -> Bool
- datesepchar :: forall (m :: Type -> Type). TextParser m Char
- datesepchars :: String
- smartdate :: forall (m :: Type -> Type). TextParser m SmartDate
- parsedateM :: String -> Maybe Day
- intervalBoundaryBefore :: Interval -> Day -> Day
- prevday :: Day -> Day
- fixSmartDate :: Day -> SmartDate -> EFDay
- fixSmartDateStrEither' :: Day -> Text -> Either HledgerParseErrors EFDay
- fixSmartDateStrEither :: Day -> Text -> Either HledgerParseErrors Text
- fixSmartDateStr :: Day -> Text -> Text
- parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan)
- parsePeriodExpr :: Day -> Text -> Either HledgerParseErrors (Interval, DateSpan)
- latestSpanContaining :: [DateSpan] -> Day -> Maybe DateSpan
- daysSpan :: [Day] -> DateSpan
- spanUnion :: DateSpan -> DateSpan -> DateSpan
- spansUnion :: [DateSpan] -> DateSpan
- spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan
- spanIntersect :: DateSpan -> DateSpan -> DateSpan
- spansIntersect :: [DateSpan] -> DateSpan
- groupByDateSpan :: Bool -> (a -> Day) -> [DateSpan] -> [a] -> [(DateSpan, [a])]
- periodContainsDate :: Period -> Day -> Bool
- spanContainsDate :: DateSpan -> Day -> Bool
- daysInSpan :: DateSpan -> Maybe Integer
- spansFromBoundaries :: Day -> [Day] -> [DateSpan]
- splitSpan :: Bool -> Interval -> DateSpan -> [DateSpan]
- spansSpan :: [DateSpan] -> DateSpan
- spanYears :: DateSpan -> [Year]
- spanEndYear :: DateSpan -> Maybe Year
- spanStartYear :: DateSpan -> Maybe Year
- spanEnd :: DateSpan -> Maybe Day
- spanStart :: DateSpan -> Maybe Day
- elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a
- getCurrentYear :: IO Integer
- getCurrentMonth :: IO Int
- getCurrentDay :: IO Day
- showDateSpanMonthAbbrev :: DateSpan -> Text
- showDateSpanDebug :: DateSpan -> String
- showDateSpan :: DateSpan -> Text
- showEFDate :: EFDay -> Text
- showDate :: Day -> Text
- posintopt :: String -> RawOpts -> Int
- intopt :: String -> RawOpts -> Int
- maybeposintopt :: String -> RawOpts -> Maybe Int
- maybeintopt :: String -> RawOpts -> Maybe Int
- listofstringopt :: String -> RawOpts -> [String]
- maybecharopt :: String -> RawOpts -> Maybe Char
- stringopt :: String -> RawOpts -> String
- maybestringopt :: String -> RawOpts -> Maybe String
- collectopts :: ((String, String) -> Maybe a) -> RawOpts -> [a]
- choiceopt :: (String -> Maybe a) -> RawOpts -> Maybe a
- toggleopt :: String -> RawOpts -> Bool
- boolopt :: String -> RawOpts -> Bool
- appendopts :: [(String, String)] -> RawOpts -> RawOpts
- unsetboolopt :: String -> RawOpts -> RawOpts
- setboolopt :: String -> RawOpts -> RawOpts
- setopt :: String -> String -> RawOpts -> RawOpts
- overRawOpts :: ([(String, String)] -> [(String, String)]) -> RawOpts -> RawOpts
- data RawOpts
- tests_Utils :: TestTree
- makeHledgerClassyLenses :: Name -> DecsQ
- numDigitsInteger :: Integer -> Int
- numDigitsInt :: Integral a => Int -> a
- multicol :: Int -> [String] -> String
- sixth6 :: (a, b, c, d, e, f) -> f
- fifth6 :: (a, b, c, d, e, f) -> e
- fourth6 :: (a, b, c, d, e, f) -> d
- third6 :: (a, b, c, d, e, f) -> c
- second6 :: (a, b, c, d, e, f) -> b
- first6 :: (a, b, c, d, e, f) -> a
- fifth5 :: (a, b, c, d, e) -> e
- fourth5 :: (a, b, c, d, e) -> d
- third5 :: (a, b, c, d, e) -> c
- second5 :: (a, b, c, d, e) -> b
- first5 :: (a, b, c, d, e) -> a
- fourth4 :: (a, b, c, d) -> d
- third4 :: (a, b, c, d) -> c
- second4 :: (a, b, c, d) -> b
- first4 :: (a, b, c, d) -> a
- third3 :: (a, b, c) -> c
- second3 :: (a, b, c) -> b
- first3 :: (a, b, c) -> a
- treeLeaves :: Tree a -> [a]
- sumStrict :: Num a => [a] -> a
- splitAtElement :: Eq a => a -> [a] -> [[a]]
- minimumStrict :: Ord a => [a] -> a
- maximumStrict :: Ord a => [a] -> a
- maximum' :: Integral a => [a] -> a
- uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
- curry4 :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e
- uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
- curry3 :: ((a, b, c) -> d) -> a -> b -> c -> d
- uncurry2 :: (a -> b -> c) -> (a, b) -> c
- curry2 :: ((a, b) -> c) -> a -> b -> c
- sequence' :: Monad f => [f a] -> f [a]
- mapM' :: Monad f => (a -> f b) -> [a] -> f [b]
- applyN :: Int -> (a -> a) -> a -> a
- stripAnsi :: String -> String
- strWidth :: String -> Int
- strWidthAnsi :: String -> Int
- takeWidth :: Int -> String -> String
- unwords' :: [String] -> String
- words' :: String -> [String]
- quoteForCommandLine :: String -> String
- singleQuoteIfNeeded :: String -> String
- quoteIfNeeded :: String -> String
- underline :: String -> String
- formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String
- elideRight :: Int -> String -> String
- elideLeft :: Int -> String -> String
- stripbrackets :: String -> String
- singleline :: String -> String
- chomp1 :: String -> String
- chomp :: String -> String
- strip1By :: (Char -> Bool) -> String -> String
- stripBy :: (Char -> Bool) -> String -> String
- strip1Char :: Char -> Char -> String -> String
- rstrip :: String -> String
- lstrip :: String -> String
- strip :: String -> String
- uppercase :: String -> String
- lowercase :: String -> String
- capitalise :: String -> String
- takeEnd :: Int -> [a] -> [a]
- eolof :: forall (m :: Type -> Type). TextParser m ()
- skipNonNewlineSpaces' :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m Bool
- skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
- skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m ()
- restofline :: forall (m :: Type -> Type). TextParser m String
- spacenonewline :: forall s (m :: Type -> Type). (Stream s, Char ~ Token s) => ParsecT HledgerParseErrorData s m Char
- isNonNewlineSpace :: Char -> Bool
- nonspace :: forall (m :: Type -> Type). TextParser m Char
- isNewline :: Char -> Bool
- showDateParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String
- parseerror :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> a
- fromparse :: (Show t, Show (Token t), Show e) => Either (ParseErrorBundle t e) a -> a
- parseWithState' :: Stream s => st -> StateT st (ParsecT e s Identity) a -> s -> Either (ParseErrorBundle s e) a
- parseWithState :: Monad m => st -> StateT st (ParsecT HledgerParseErrorData Text m) a -> Text -> m (Either HledgerParseErrors a)
- parsewithString :: Parsec e String a -> String -> Either (ParseErrorBundle String e) a
- rtp :: TextParser Identity a -> Text -> Either HledgerParseErrors a
- runTextParser :: TextParser Identity a -> Text -> Either HledgerParseErrors a
- parsewith :: Parsec e Text a -> Text -> Either (ParseErrorBundle Text e) a
- surroundedBy :: Applicative m => m openclose -> m a -> m a
- choiceInState :: forall s (m :: Type -> Type) a. [StateT s (ParsecT HledgerParseErrorData Text m) a] -> StateT s (ParsecT HledgerParseErrorData Text m) a
- choice' :: forall (m :: Type -> Type) a. [TextParser m a] -> TextParser m a
- sourcePosPairPretty :: (SourcePos, SourcePos) -> String
- dbgparse :: forall (m :: Type -> Type). Int -> String -> TextParser m ()
- traceOrLogParse :: forall (m :: Type -> Type). String -> TextParser m ()
- type SimpleStringParser a = Parsec HledgerParseErrorData String a
- type SimpleTextParser = Parsec HledgerParseErrorData Text
- type TextParser (m :: Type -> Type) a = ParsecT HledgerParseErrorData Text m a
- lbl_ :: String -> String -> String -> String
- dbg9With :: Show a => (a -> String) -> a -> a
- dbg8With :: Show a => (a -> String) -> a -> a
- dbg7With :: Show a => (a -> String) -> a -> a
- dbg6With :: Show a => (a -> String) -> a -> a
- dbg5With :: Show a => (a -> String) -> a -> a
- dbg4With :: Show a => (a -> String) -> a -> a
- dbg3With :: Show a => (a -> String) -> a -> a
- dbg2With :: Show a => (a -> String) -> a -> a
- dbg1With :: Show a => (a -> String) -> a -> a
- dbg0With :: (a -> String) -> a -> a
- dbg9IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg8IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg7IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg6IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg5IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg4IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg3IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg2IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg1IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbg0IO :: (MonadIO m, Show a) => String -> a -> m ()
- dbgExit :: Show a => String -> a -> a
- dbg9 :: Show a => String -> a -> a
- dbg8 :: Show a => String -> a -> a
- dbg7 :: Show a => String -> a -> a
- dbg6 :: Show a => String -> a -> a
- dbg5 :: Show a => String -> a -> a
- dbg4 :: Show a => String -> a -> a
- dbg3 :: Show a => String -> a -> a
- dbg2 :: Show a => String -> a -> a
- dbg1 :: Show a => String -> a -> a
- dbg0 :: Show a => String -> a -> a
- traceOrLogAtWith :: Int -> (a -> String) -> a -> a
- ptraceOrLogAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()
- ptraceOrLogAt :: Show a => Int -> String -> a -> a
- traceOrLogAt :: Int -> String -> a -> a
- traceOrLog :: String -> a -> a
- ptraceLogAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()
- ptraceLogAt :: Show a => Int -> String -> a -> a
- traceLogAtWith :: Int -> (a -> String) -> a -> a
- traceLogWith :: (a -> String) -> a -> a
- traceLogAtIO :: MonadIO m => Int -> String -> m ()
- traceLogIO :: MonadIO m => String -> m ()
- traceLogAt :: Int -> String -> a -> a
- traceLog :: String -> a -> a
- ptraceAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m ()
- ptraceAt :: Show a => Int -> String -> a -> a
- traceAtWith :: Int -> (a -> String) -> a -> a
- traceAt :: Int -> String -> a -> a
- ptrace :: Show a => a -> a
- traceWith :: (a -> String) -> a -> a
- debugLevel :: Int
- assertParseErrorE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> String -> Assertion
- assertParseEqE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> a -> Assertion
- assertParseE :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> Assertion
- assertParseStateOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (st -> b) -> b -> Assertion
- assertParseError :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> String -> Assertion
- assertParseEqOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (a -> b) -> b -> Assertion
- assertParseEq :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> a -> Assertion
- assertParse :: (HasCallStack, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> Assertion
- assertRight :: (HasCallStack, Eq a, Show a) => Either a b -> Assertion
- assertLeft :: (HasCallStack, Eq b, Show b) => Either a b -> Assertion
- getCurrentZonedTime :: IO ZonedTime
- getCurrentLocalTime :: IO LocalTime
- embedFileRelative :: FilePath -> Q Exp
- readHandlePortably :: Handle -> IO Text
- readFileOrStdinPortably :: String -> IO Text
- readFilePortably :: FilePath -> IO Text
- readFileStrictly :: FilePath -> IO Text
- sortByModTime :: [FilePath] -> IO [FilePath]
- expandGlob :: FilePath -> FilePath -> IO [FilePath]
- expandPath :: FilePath -> FilePath -> IO FilePath
- expandHomePath :: FilePath -> IO FilePath
- usageError :: String -> a
- error' :: String -> a
- terminalFgColor :: Maybe (RGB Float)
- terminalBgColor :: Maybe (RGB Float)
- terminalLightness :: Maybe Float
- terminalIsLight :: Maybe Bool
- bgColorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder
- colorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder
- bgColor :: ColorIntensity -> Color -> String -> String
- color :: ColorIntensity -> Color -> String -> String
- useColorOnStderr :: Bool
- useColorOnStdout :: Bool
- colorOption :: String
- rgb' :: Word8 -> Word8 -> Word8 -> String -> String
- brightWhite' :: String -> String
- brightCyan' :: String -> String
- brightMagenta' :: String -> String
- brightBlue' :: String -> String
- brightYellow' :: String -> String
- brightGreen' :: String -> String
- brightRed' :: String -> String
- brightBlack' :: String -> String
- white' :: String -> String
- cyan' :: String -> String
- magenta' :: String -> String
- blue' :: String -> String
- yellow' :: String -> String
- green' :: String -> String
- red' :: String -> String
- black' :: String -> String
- faint' :: String -> String
- bold' :: String -> String
- hasOutputFile :: Bool
- outputFileOption :: Maybe String
- progArgs :: [String]
- setupPager :: IO ()
- getTerminalWidth :: IO (Maybe Int)
- getTerminalHeight :: IO (Maybe Int)
- getTerminalHeightWidth :: IO (Maybe (Int, Int))
- pager :: String -> IO ()
- pprint' :: Show a => a -> IO ()
- pprint :: Show a => a -> IO ()
- pshow' :: Show a => a -> String
- pshow :: Show a => a -> String
- tests_Text :: TestTree
- readDecimal :: Text -> Integer
- unlinesB :: [Builder] -> Builder
- linesPrepend2 :: Text -> Text -> Text -> Text
- linesPrepend :: Text -> Text -> Text
- textTakeWidth :: Int -> Text -> Text
- fitText :: Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text
- textConcatBottomPadded :: [Text] -> Text
- textConcatTopPadded :: [Text] -> Text
- textUnbracket :: Text -> Text
- stripquotes :: Text -> Text
- escapeBackslash :: Text -> Text
- escapeDoubleQuotes :: Text -> Text
- textQuoteIfNeeded :: Text -> Text
- quoteIfSpaced :: Text -> Text
- formatText :: Bool -> Maybe Int -> Maybe Int -> Text -> Text
- textChomp :: Text -> Text
- wrap :: Text -> Text -> Text -> Text
- textElideRight :: Int -> Text -> Text
- textCapitalise :: Text -> Text
- wbUnpack :: WideBuilder -> String
- wbFromText :: Text -> WideBuilder
- wbToText :: WideBuilder -> Text
- data WideBuilder = WideBuilder {}
- customErrorBundlePretty :: HledgerParseErrors -> String
- data HledgerParseErrorData
- type HledgerParseErrors = ParseErrorBundle Text HledgerParseErrorData
- startOfFirstWeekInMonth :: Year -> MonthOfYear -> Day
- firstMonthOfQuarter :: Num a => a -> a
- quarterContainingMonth :: Integral a => a -> a
- yearMonthContainingWeekStarting :: Day -> (Year, MonthOfYear)
- mondayBefore :: Day -> Day
- periodShrink :: Day -> Period -> Period
- periodGrow :: Period -> Period
- periodMoveTo :: Day -> Period -> Period
- periodPreviousIn :: DateSpan -> Period -> Period
- periodNextIn :: DateSpan -> Period -> Period
- periodPrevious :: Period -> Period
- periodNext :: Period -> Period
- periodEnd :: Period -> Maybe Day
- periodStart :: Period -> Maybe Day
- showPeriodMonthAbbrev :: Period -> Text
- showPeriod :: Period -> Text
- periodTextWidth :: Period -> Int
- isStandardPeriod :: Period -> Bool
- isLastDayOfMonth :: (Eq a1, Eq a2, Num a1, Num a2) => Year -> a1 -> a2 -> Bool
- simplifyPeriod :: Period -> Period
- dateSpanAsPeriod :: DateSpan -> Period
- periodAsDateSpan :: Period -> DateSpan
- nullaccountdeclarationinfo :: AccountDeclarationInfo
- nulltagdeclarationinfo :: TagDeclarationInfo
- nullpayeedeclarationinfo :: PayeeDeclarationInfo
- nullperiodictransaction :: PeriodicTransaction
- nulltransactionmodifier :: TransactionModifier
- maCompare :: MixedAmount -> MixedAmount -> Ordering
- isDecimalMark :: Char -> Bool
- isAccountSubtypeOf :: AccountType -> AccountType -> Bool
- isIncomeStatementAccountType :: AccountType -> Bool
- isBalanceSheetAccountType :: AccountType -> Bool
- modifyEFDay :: (Day -> Day) -> EFDay -> EFDay
- fromEFDay :: EFDay -> Day
- type Month = Int
- type Quarter = Int
- type YearWeek = Int
- type MonthWeek = Int
- type YearDay = Int
- type MonthDay = Int
- type WeekDay = Int
- data SmartDate
- data SmartInterval
- data WhichDate
- data EFDay
- data DateSpan = DateSpan (Maybe EFDay) (Maybe EFDay)
- data Period
- data Interval
- type Payee = Text
- type AccountName = Text
- data AccountType
- data AccountAlias
- data Side
- type DecimalMark = Char
- type Quantity = Decimal
- data AmountPrice
- = UnitPrice !Amount
- | TotalPrice !Amount
- data AmountStyle = AmountStyle {
- ascommodityside :: !Side
- ascommodityspaced :: !Bool
- asdigitgroups :: !(Maybe DigitGroupStyle)
- asdecimalmark :: !(Maybe Char)
- asprecision :: !AmountPrecision
- asrounding :: !Rounding
- data AmountPrecision
- data Rounding
- data DigitGroupStyle = DigitGroups !Char ![Word8]
- type CommoditySymbol = Text
- data Commodity = Commodity {}
- data Amount = Amount {
- acommodity :: !CommoditySymbol
- aquantity :: !Quantity
- astyle :: !AmountStyle
- aprice :: !(Maybe AmountPrice)
- class HasAmounts a where
- styleAmounts :: Map CommoditySymbol AmountStyle -> a -> a
- data MixedAmount
- pattern MixedAmountKeyUnitPrice :: !CommoditySymbol -> !CommoditySymbol -> !Quantity -> MixedAmountKey
- pattern MixedAmountKeyNoPrice :: !CommoditySymbol -> MixedAmountKey
- pattern MixedAmountKeyTotalPrice :: !CommoditySymbol -> !CommoditySymbol -> MixedAmountKey
- data PostingType
- type TagName = Text
- type TagValue = Text
- type Tag = (TagName, TagValue)
- type DateTag = (TagName, Day)
- data Status
- data BalanceAssertion = BalanceAssertion {
- baamount :: Amount
- batotal :: Bool
- bainclusive :: Bool
- baposition :: SourcePos
- data Posting = Posting {
- pdate :: Maybe Day
- pdate2 :: Maybe Day
- pstatus :: Status
- paccount :: AccountName
- pamount :: MixedAmount
- pcomment :: Text
- ptype :: PostingType
- ptags :: [Tag]
- pbalanceassertion :: Maybe BalanceAssertion
- ptransaction :: Maybe Transaction
- poriginal :: Maybe Posting
- data Transaction = Transaction {}
- data TransactionModifier = TransactionModifier {}
- data TMPostingRule = TMPostingRule {}
- data PeriodicTransaction = PeriodicTransaction {
- ptperiodexpr :: Text
- ptinterval :: Interval
- ptspan :: DateSpan
- ptsourcepos :: (SourcePos, SourcePos)
- ptstatus :: Status
- ptcode :: Text
- ptdescription :: Text
- ptcomment :: Text
- pttags :: [Tag]
- ptpostings :: [Posting]
- data TimeclockCode
- = SetBalance
- | SetRequiredHours
- | In
- | Out
- | FinalOut
- data TimeclockEntry = TimeclockEntry {
- tlsourcepos :: SourcePos
- tlcode :: TimeclockCode
- tldatetime :: LocalTime
- tlaccount :: AccountName
- tldescription :: Text
- tlcomment :: Text
- tltags :: [Tag]
- data PriceDirective = PriceDirective {}
- data MarketPrice = MarketPrice {
- mpdate :: Day
- mpfrom :: CommoditySymbol
- mpto :: CommoditySymbol
- mprate :: Quantity
- data Journal = Journal {
- jparsedefaultyear :: Maybe Year
- jparsedefaultcommodity :: Maybe (CommoditySymbol, AmountStyle)
- jparsedecimalmark :: Maybe DecimalMark
- jparseparentaccounts :: [AccountName]
- jparsealiases :: [AccountAlias]
- jparsetimeclockentries :: [TimeclockEntry]
- jincludefilestack :: [FilePath]
- jdeclaredpayees :: [(Payee, PayeeDeclarationInfo)]
- jdeclaredtags :: [(TagName, TagDeclarationInfo)]
- jdeclaredaccounts :: [(AccountName, AccountDeclarationInfo)]
- jdeclaredaccounttags :: Map AccountName [Tag]
- jdeclaredaccounttypes :: Map AccountType [AccountName]
- jaccounttypes :: Map AccountName AccountType
- jglobalcommoditystyles :: Map CommoditySymbol AmountStyle
- jcommodities :: Map CommoditySymbol Commodity
- jinferredcommodities :: Map CommoditySymbol AmountStyle
- jpricedirectives :: [PriceDirective]
- jinferredmarketprices :: [MarketPrice]
- jtxnmodifiers :: [TransactionModifier]
- jperiodictxns :: [PeriodicTransaction]
- jtxns :: [Transaction]
- jfinalcommentlines :: Text
- jfiles :: [(FilePath, Text)]
- jlastreadtime :: POSIXTime
- type ParsedJournal = Journal
- type StorageFormat = String
- data PayeeDeclarationInfo = PayeeDeclarationInfo {
- pdicomment :: Text
- pditags :: [Tag]
- newtype TagDeclarationInfo = TagDeclarationInfo {
- tdicomment :: Text
- data AccountDeclarationInfo = AccountDeclarationInfo {
- adicomment :: Text
- aditags :: [Tag]
- adideclarationorder :: Int
- adisourcepos :: SourcePos
- data Account = Account {}
- data NormalSign
- data Ledger = Ledger {}
- regexReplaceAllBy :: Regexp -> (String -> String) -> String -> String
- regexReplaceUnmemo :: Regexp -> Replacement -> String -> Either RegexError String
- regexReplace :: Regexp -> Replacement -> String -> Either RegexError String
- regexMatchTextGroups :: Regexp -> Text -> [Text]
- regexMatchText :: Regexp -> Text -> Bool
- regexMatch :: Regexp -> String -> Bool
- toRegexCI' :: Text -> Regexp
- toRegex' :: Text -> Regexp
- toRegexCI :: Text -> Either RegexError Regexp
- toRegex :: Text -> Either RegexError Regexp
- data Regexp
- type Replacement = String
- type RegexError = String
- type Year = Integer
- data Timeout
- mkTimeout :: Integer -> Timeout
- data TestTree
- data DependencyType
- type TestName = String
- testGroup :: TestName -> [TestTree] -> TestTree
- sequentialTestGroup :: TestName -> DependencyType -> [TestTree] -> TestTree
- after_ :: DependencyType -> Expr -> TestTree -> TestTree
- after :: DependencyType -> String -> TestTree -> TestTree
- includingOptions :: [OptionDescription] -> Ingredient
- defaultMainWithIngredients :: [Ingredient] -> TestTree -> IO ()
- defaultIngredients :: [Ingredient]
- adjustOption :: IsOption v => (v -> v) -> TestTree -> TestTree
- localOption :: IsOption v => v -> TestTree -> TestTree
- askOption :: IsOption v => (v -> TestTree) -> TestTree
- withResource :: IO a -> (a -> IO ()) -> (IO a -> TestTree) -> TestTree
- runExceptT :: ExceptT e m a -> m (Either e a)
- data SourcePos = SourcePos {
- sourceName :: FilePath
- sourceLine :: !Pos
- sourceColumn :: !Pos
- mkPos :: Int -> Pos
- unPos :: Pos -> Int
- initialPos :: FilePath -> SourcePos
- sourcePosPretty :: SourcePos -> String
- foldl1Def' :: a -> (a -> a -> a) -> [a] -> a
- foldl1Def :: a -> (a -> a -> a) -> [a] -> a
- foldr1Def :: a -> (a -> a -> a) -> [a] -> a
- maximumByDef :: a -> (a -> a -> Ordering) -> [a] -> a
- minimumByDef :: a -> (a -> a -> Ordering) -> [a] -> a
- maximumDef :: Ord a => a -> [a] -> a
- minimumDef :: Ord a => a -> [a] -> a
- indexNote :: (Partial, Ix a) => String -> (a, a) -> a -> Int
- indexDef :: Ix a => Int -> (a, a) -> a -> Int
- indexMay :: Ix a => (a, a) -> a -> Maybe Int
- predSafe :: (Enum a, Eq a, Bounded a) => a -> a
- predNote :: (Partial, Enum a, Eq a, Bounded a) => String -> a -> a
- predDef :: (Enum a, Eq a, Bounded a) => a -> a -> a
- predMay :: (Enum a, Eq a, Bounded a) => a -> Maybe a
- succSafe :: (Enum a, Eq a, Bounded a) => a -> a
- succNote :: (Partial, Enum a, Eq a, Bounded a) => String -> a -> a
- succDef :: (Enum a, Eq a, Bounded a) => a -> a -> a
- succMay :: (Enum a, Eq a, Bounded a) => a -> Maybe a
- toEnumSafe :: (Enum a, Bounded a) => Int -> a
- toEnumNote :: (Partial, Enum a, Bounded a) => String -> Int -> a
- toEnumDef :: (Enum a, Bounded a) => a -> Int -> a
- toEnumMay :: (Enum a, Bounded a) => Int -> Maybe a
- findIndexJustNote :: Partial => String -> (a -> Bool) -> [a] -> Int
- findIndexJustDef :: Int -> (a -> Bool) -> [a] -> Int
- findIndexJust :: (a -> Bool) -> [a] -> Int
- elemIndexJustNote :: (Partial, Eq a) => String -> a -> [a] -> Int
- elemIndexJustDef :: Eq a => Int -> a -> [a] -> Int
- elemIndexJust :: (Partial, Eq a) => a -> [a] -> Int
- findJustNote :: Partial => String -> (a -> Bool) -> [a] -> a
- findJustDef :: a -> (a -> Bool) -> [a] -> a
- findJust :: (a -> Bool) -> [a] -> a
- lookupJustNote :: (Partial, Eq a) => String -> a -> [(a, b)] -> b
- lookupJustDef :: Eq a => b -> a -> [(a, b)] -> b
- lookupJust :: (Eq a, Partial) => a -> [(a, b)] -> b
- readNote :: (Partial, Read a) => String -> String -> a
- readDef :: Read a => a -> String -> a
- readMay :: Read a => String -> Maybe a
- readEitherSafe :: Read a => String -> Either String a
- atNote :: Partial => String -> [a] -> Int -> a
- atDef :: a -> [a] -> Int -> a
- atMay :: [a] -> Int -> Maybe a
- assertNote :: Partial => String -> Bool -> a -> a
- fromJustNote :: Partial => String -> Maybe a -> a
- fromJustDef :: a -> Maybe a -> a
- cycleNote :: Partial => String -> [a] -> [a]
- cycleDef :: [a] -> [a] -> [a]
- cycleMay :: [a] -> Maybe [a]
- scanl1Note :: Partial => String -> (a -> a -> a) -> [a] -> [a]
- scanr1Note :: Partial => String -> (a -> a -> a) -> [a] -> [a]
- scanl1Def :: [a] -> (a -> a -> a) -> [a] -> [a]
- scanr1Def :: [a] -> (a -> a -> a) -> [a] -> [a]
- scanl1May :: (a -> a -> a) -> [a] -> Maybe [a]
- scanr1May :: (a -> a -> a) -> [a] -> Maybe [a]
- foldl1Note' :: Partial => String -> (a -> a -> a) -> [a] -> a
- foldl1Note :: Partial => String -> (a -> a -> a) -> [a] -> a
- foldr1Note :: Partial => String -> (a -> a -> a) -> [a] -> a
- foldl1May' :: (a -> a -> a) -> [a] -> Maybe a
- foldl1May :: (a -> a -> a) -> [a] -> Maybe a
- foldr1May :: (a -> a -> a) -> [a] -> Maybe a
- minimumBounded :: (Ord a, Bounded a) => [a] -> a
- maximumBounded :: (Ord a, Bounded a) => [a] -> a
- minimumBound :: Ord a => a -> [a] -> a
- maximumBound :: Ord a => a -> [a] -> a
- minimumBoundBy :: a -> (a -> a -> Ordering) -> [a] -> a
- maximumBoundBy :: a -> (a -> a -> Ordering) -> [a] -> a
- maximumByNote :: Partial => String -> (a -> a -> Ordering) -> [a] -> a
- minimumByNote :: Partial => String -> (a -> a -> Ordering) -> [a] -> a
- maximumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a
- minimumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a
- maximumNote :: (Partial, Ord a) => String -> [a] -> a
- minimumNote :: (Partial, Ord a) => String -> [a] -> a
- maximumMay :: Ord a => [a] -> Maybe a
- minimumMay :: Ord a => [a] -> Maybe a
- lastNote :: Partial => String -> [a] -> a
- headNote :: Partial => String -> [a] -> a
- lastDef :: a -> [a] -> a
- headDef :: a -> [a] -> a
- lastMay :: [a] -> Maybe a
- headMay :: [a] -> Maybe a
- initSafe :: [a] -> [a]
- initNote :: Partial => String -> [a] -> [a]
- initDef :: [a] -> [a] -> [a]
- initMay :: [a] -> Maybe [a]
- tailSafe :: [a] -> [a]
- tailNote :: Partial => String -> [a] -> [a]
- tailDef :: [a] -> [a] -> [a]
- tailMay :: [a] -> Maybe [a]
- abort :: Partial => String -> a
- unpack :: Text -> String
- pack :: String -> Text
- readSTime :: ParseTime t => Bool -> TimeLocale -> String -> ReadS t
- readPTime :: ParseTime t => Bool -> TimeLocale -> String -> ReadP t
- parseTimeOrError :: ParseTime t => Bool -> TimeLocale -> String -> String -> t
- parseTimeMultipleM :: (MonadFail m, ParseTime t) => Bool -> TimeLocale -> [(String, String)] -> m t
- parseTimeM :: (MonadFail m, ParseTime t) => Bool -> TimeLocale -> String -> String -> m t
- data ZonedTime = ZonedTime {}
- zonedTimeToUTC :: ZonedTime -> UTCTime
- utcToZonedTime :: TimeZone -> UTCTime -> ZonedTime
- utcToLocalZonedTime :: UTCTime -> IO ZonedTime
- getZonedTime :: IO ZonedTime
- class FormatTime t
- formatTime :: FormatTime t => TimeLocale -> String -> t -> String
- class ParseTime t
- data TimeLocale = TimeLocale {}
- rfc822DateFormat :: String
- iso8601DateFormat :: Maybe String -> String
- defaultTimeLocale :: TimeLocale
- data LocalTime = LocalTime {}
- utcToLocalTime :: TimeZone -> UTCTime -> LocalTime
- ut1ToLocalTime :: Rational -> UniversalTime -> LocalTime
- localTimeToUTC :: TimeZone -> LocalTime -> UTCTime
- localTimeToUT1 :: Rational -> LocalTime -> UniversalTime
- diffLocalTime :: LocalTime -> LocalTime -> NominalDiffTime
- addLocalTime :: NominalDiffTime -> LocalTime -> LocalTime
- data TimeOfDay = TimeOfDay {}
- utcToLocalTimeOfDay :: TimeZone -> TimeOfDay -> (Integer, TimeOfDay)
- timeToTimeOfDay :: DiffTime -> TimeOfDay
- timeToDaysAndTimeOfDay :: NominalDiffTime -> (Integer, TimeOfDay)
- timeOfDayToTime :: TimeOfDay -> DiffTime
- timeOfDayToDayFraction :: TimeOfDay -> Rational
- sinceMidnight :: TimeOfDay -> DiffTime
- pastMidnight :: DiffTime -> TimeOfDay
- midnight :: TimeOfDay
- midday :: TimeOfDay
- makeTimeOfDayValid :: Int -> Int -> Pico -> Maybe TimeOfDay
- localToUTCTimeOfDay :: TimeZone -> TimeOfDay -> (Integer, TimeOfDay)
- daysAndTimeOfDayToTime :: Integer -> TimeOfDay -> NominalDiffTime
- dayFractionToTimeOfDay :: Rational -> TimeOfDay
- data TimeZone = TimeZone {}
- utc :: TimeZone
- timeZoneOffsetString' :: Maybe Char -> TimeZone -> String
- timeZoneOffsetString :: TimeZone -> String
- minutesToTimeZone :: Int -> TimeZone
- hoursToTimeZone :: Int -> TimeZone
- getTimeZone :: UTCTime -> IO TimeZone
- getCurrentTimeZone :: IO TimeZone
- data CalendarDiffTime = CalendarDiffTime {}
- scaleCalendarDiffTime :: Integer -> CalendarDiffTime -> CalendarDiffTime
- calendarTimeTime :: NominalDiffTime -> CalendarDiffTime
- calendarTimeDays :: CalendarDiffDays -> CalendarDiffTime
- diffUTCTime :: UTCTime -> UTCTime -> NominalDiffTime
- addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime
- getCurrentTime :: IO UTCTime
- newtype UniversalTime = ModJulianDate {}
- getTime_resolution :: DiffTime
- data NominalDiffTime
- secondsToNominalDiffTime :: Pico -> NominalDiffTime
- nominalDiffTimeToSeconds :: NominalDiffTime -> Pico
- nominalDay :: NominalDiffTime
- data DiffTime
- secondsToDiffTime :: Integer -> DiffTime
- picosecondsToDiffTime :: Integer -> DiffTime
- diffTimeToPicoseconds :: DiffTime -> Integer
- data DayOfWeek
- firstDayOfWeekOnAfter :: DayOfWeek -> Day -> Day
- dayOfWeekDiff :: DayOfWeek -> DayOfWeek -> Int
- dayOfWeek :: Day -> DayOfWeek
- toGregorian :: Day -> (Year, MonthOfYear, DayOfMonth)
- showGregorian :: Day -> String
- gregorianMonthLength :: Year -> MonthOfYear -> DayOfMonth
- fromGregorianValid :: Year -> MonthOfYear -> DayOfMonth -> Maybe Day
- fromGregorian :: Year -> MonthOfYear -> DayOfMonth -> Day
- diffGregorianDurationRollOver :: Day -> Day -> CalendarDiffDays
- diffGregorianDurationClip :: Day -> Day -> CalendarDiffDays
- addGregorianYearsRollOver :: Integer -> Day -> Day
- addGregorianYearsClip :: Integer -> Day -> Day
- addGregorianMonthsRollOver :: Integer -> Day -> Day
- addGregorianMonthsClip :: Integer -> Day -> Day
- addGregorianDurationRollOver :: CalendarDiffDays -> Day -> Day
- addGregorianDurationClip :: CalendarDiffDays -> Day -> Day
- pattern YearMonthDay :: Year -> MonthOfYear -> DayOfMonth -> Day
- isLeapYear :: Year -> Bool
- type MonthOfYear = Int
- type DayOfMonth = Int
- newtype Day = ModifiedJulianDay {}
- diffDays :: Day -> Day -> Integer
- addDays :: Integer -> Day -> Day
- data CalendarDiffDays = CalendarDiffDays {}
- scaleCalendarDiffDays :: Integer -> CalendarDiffDays -> CalendarDiffDays
- calendarYear :: CalendarDiffDays
- calendarWeek :: CalendarDiffDays
- calendarMonth :: CalendarDiffDays
- calendarDay :: CalendarDiffDays
- type Topic = String
- printHelpForTopic :: Tool -> Maybe Topic -> IO ()
- runPagerForTopic :: Tool -> Maybe Topic -> IO ()
- runManForTopic :: Tool -> Maybe Topic -> IO ()
- runInfoForTopic :: Tool -> Maybe Topic -> IO ()
- type VersionString = String
- type PackageVersion = String
- type ProgramName = String
- packageversion :: PackageVersion
- packagemajorversion :: PackageVersion
- progname :: ProgramName
- versionStringWith :: Either String GitInfo -> ProgramName -> PackageVersion -> VersionString
- data CliOpts = CliOpts {}
- type CommandDoc = String
- helpflags :: [Flag RawOpts]
- detailedversionflag :: Flag RawOpts
- inputflags :: [Flag RawOpts]
- reportflags :: [Flag RawOpts]
- flattreeflags :: Bool -> [Flag RawOpts]
- hiddenflags :: [Flag RawOpts]
- outputFormatFlag :: [String] -> Flag RawOpts
- outputFileFlag :: Flag RawOpts
- argsFlag :: FlagHelp -> Arg RawOpts
- generalflagsgroup1 :: (String, [Flag RawOpts])
- generalflagsgroup2 :: (String, [Flag RawOpts])
- generalflagsgroup3 :: (String, [Flag RawOpts])
- defMode :: Mode RawOpts
- defCommandMode :: [Name] -> Mode RawOpts
- addonCommandMode :: Name -> Mode RawOpts
- hledgerCommandMode :: CommandDoc -> [Flag RawOpts] -> [(String, [Flag RawOpts])] -> [Flag RawOpts] -> ([Arg RawOpts], Maybe (Arg RawOpts)) -> Mode RawOpts
- showModeUsage :: Mode a -> String
- topicForMode :: Mode a -> Topic
- withAliases :: String -> [String] -> String
- defcliopts :: CliOpts
- defaultWidth :: Int
- replaceNumericFlags :: [String] -> [String]
- rawOptsToCliOpts :: RawOpts -> IO CliOpts
- getHledgerCliOpts' :: Mode RawOpts -> [String] -> IO CliOpts
- getHledgerCliOpts :: Mode RawOpts -> IO CliOpts
- journalFilePathFromOpts :: CliOpts -> IO [String]
- outputFileFromOpts :: CliOpts -> IO (Maybe FilePath)
- defaultOutputFormat :: String
- outputFormats :: [String]
- outputFormatFromOpts :: CliOpts -> String
- rulesFilePathFromOpts :: CliOpts -> IO (Maybe FilePath)
- registerWidthsFromOpts :: CliOpts -> (Int, Maybe Int)
- hledgerAddons :: IO [String]
- hledgerExecutablesInPath :: IO [String]
- likelyExecutablesInPath :: IO [String]
- class HasCliOpts c where
- cliOpts :: Lens' c CliOpts
- available_width :: Lens' c Int
- command :: Lens' c String
- debug__ :: Lens' c Int
- file__ :: Lens' c [FilePath]
- inputopts :: Lens' c InputOpts
- no_new_accounts :: Lens' c Bool
- output_file :: Lens' c (Maybe FilePath)
- output_format :: Lens' c (Maybe String)
- progstarttime :: Lens' c POSIXTime
- rawopts__ :: Lens' c RawOpts
- reportspec :: Lens' c ReportSpec
- width__ :: Lens' c (Maybe String)
- ensureDebugHasArg :: (Eq (t Char), IsString (t Char), Foldable t) => [t Char] -> [t Char]
- unsupportedOutputFormatError :: String -> String
- withJournalDo :: CliOpts -> (Journal -> IO a) -> IO a
- journalTransform :: CliOpts -> Journal -> Journal
- pivotByOpts :: CliOpts -> Journal -> Journal
- anonymiseByOpts :: CliOpts -> Journal -> Journal
- writeOutput :: CliOpts -> String -> IO ()
- writeOutputLazyText :: CliOpts -> Text -> IO ()
- journalReloadIfChanged :: CliOpts -> Day -> Journal -> ExceptT String IO (Journal, Bool)
- journalReload :: CliOpts -> ExceptT String IO Journal
- journalFileIsNewer :: Journal -> FilePath -> IO Bool
- openBrowserOn :: String -> IO ExitCode
- writeFileWithBackupIfChanged :: FilePath -> Text -> IO Bool
- writeFileWithBackup :: FilePath -> String -> IO ()
- journalSimilarTransaction :: CliOpts -> Journal -> Text -> Maybe Transaction
- postingsOrTransactionsReportAsText :: Bool -> CliOpts -> (Int -> Int -> (a, [WideBuilder], [WideBuilder]) -> Builder) -> (a -> MixedAmount) -> (a -> MixedAmount) -> [a] -> Builder
- tests_Cli_Utils :: TestTree
- tagsmode :: Mode RawOpts
- tags :: CliOpts -> Journal -> IO ()
- statsmode :: Mode RawOpts
- stats :: CliOpts -> Journal -> IO ()
- registermode :: Mode RawOpts
- register :: CliOpts -> Journal -> IO ()
- postingsReportAsText :: CliOpts -> PostingsReport -> Text
- postingsReportItemAsText :: CliOpts -> Int -> Int -> (PostingsReportItem, [WideBuilder], [WideBuilder]) -> Builder
- tests_Register :: TestTree
- printmode :: Mode RawOpts
- print' :: CliOpts -> Journal -> IO ()
- transactionWithMostlyOriginalPostings :: Transaction -> Transaction
- rewritemode :: Mode RawOpts
- rewrite :: CliOpts -> Journal -> IO ()
- pricesmode :: Mode RawOpts
- prices :: CliOpts -> Journal -> IO ()
- payeesmode :: Mode RawOpts
- payees :: CliOpts -> Journal -> IO ()
- notesmode :: Mode RawOpts
- notes :: CliOpts -> Journal -> IO ()
- helpmode :: Mode RawOpts
- help' :: CliOpts -> Journal -> IO ()
- diffmode :: Mode RawOpts
- diff :: CliOpts -> Journal -> IO ()
- descriptionsmode :: Mode RawOpts
- descriptions :: CliOpts -> Journal -> IO ()
- demomode :: Mode RawOpts
- demo :: CliOpts -> Journal -> IO ()
- commoditiesmode :: Mode RawOpts
- commodities :: CliOpts -> Journal -> IO ()
- codesmode :: Mode RawOpts
- codes :: CliOpts -> Journal -> IO ()
- closemode :: Mode RawOpts
- close :: CliOpts -> Journal -> IO ()
- balancemode :: Mode RawOpts
- balance :: CliOpts -> Journal -> IO ()
- balanceReportAsCsv :: ReportOpts -> BalanceReport -> CSV
- balanceReportAsText :: ReportOpts -> BalanceReport -> Builder
- balanceReportItemAsText :: ReportOpts -> BalanceReportItem -> (Builder, [Int])
- multiBalanceReportAsCsv :: ReportOpts -> MultiBalanceReport -> CSV
- multiBalanceReportAsHtml :: ReportOpts -> MultiBalanceReport -> Html ()
- multiBalanceReportHtmlRows :: ReportOpts -> MultiBalanceReport -> (Html (), [Html ()], [Html ()])
- multiBalanceReportHtmlFootRow :: ReportOpts -> [Text] -> Html ()
- multiBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> Text
- balanceReportAsTable :: ReportOpts -> MultiBalanceReport -> Table Text Text WideBuilder
- multiBalanceRowAsCsvText :: ReportOpts -> [DateSpan] -> PeriodicReportRow a MixedAmount -> [[Text]]
- multiBalanceRowAsTableText :: ReportOpts -> PeriodicReportRow a MixedAmount -> [[WideBuilder]]
- tests_Balance :: TestTree
- data CompoundBalanceCommandSpec = CompoundBalanceCommandSpec {}
- compoundBalanceCommandMode :: CompoundBalanceCommandSpec -> Mode RawOpts
- compoundBalanceCommand :: CompoundBalanceCommandSpec -> CliOpts -> Journal -> IO ()
- incomestatementmode :: Mode RawOpts
- incomestatement :: CliOpts -> Journal -> IO ()
- cashflowmode :: Mode RawOpts
- cashflow :: CliOpts -> Journal -> IO ()
- balancesheetequitymode :: Mode RawOpts
- balancesheetequity :: CliOpts -> Journal -> IO ()
- balancesheetmode :: Mode RawOpts
- balancesheet :: CliOpts -> Journal -> IO ()
- aregistermode :: Mode RawOpts
- aregister :: CliOpts -> Journal -> IO ()
- tests_Aregister :: TestTree
- addmode :: Mode RawOpts
- add :: CliOpts -> Journal -> IO ()
- journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal
- appendToJournalFileOrStdout :: FilePath -> Text -> IO ()
- importmode :: Mode RawOpts
- importcmd :: CliOpts -> Journal -> IO ()
- activitymode :: Mode RawOpts
- barchar :: Char
- activity :: CliOpts -> Journal -> IO ()
- showHistogram :: ReportSpec -> Journal -> String
- printDayWith :: (PrintfArg t1, PrintfType t2) => (t3 -> t1) -> (DateSpan, t3) -> t2
- countBar :: Foldable t => t a -> [Char]
- accountsmode :: Mode RawOpts
- accounts :: CliOpts -> Journal -> IO ()
- builtinCommands :: [(Mode RawOpts, CliOpts -> Journal -> IO ())]
- knownCommands :: [String]
- knownAddonCommands :: [String]
- builtinCommandNames :: [String]
- findBuiltinCommand :: String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())
- printCommandsList :: String -> [String] -> IO ()
- testcmd :: CliOpts -> Journal -> IO ()
- tests_Hledger_Cli :: TestTree
- argsToCliOpts :: [String] -> [String] -> IO CliOpts
Documentation
(++) :: [a] -> [a] -> [a] infixr 5 #
Append two lists, i.e.,
[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
If the first list is not finite, the result is the first list.
filter :: (a -> Bool) -> [a] -> [a] #
\(\mathcal{O}(n)\). filter, applied to a predicate and a list, returns
the list of those elements that satisfy the predicate; i.e.,
filter p xs = [ x | x <- xs, p x]
>>>filter odd [1, 2, 3][1,3]
zip :: [a] -> [b] -> [(a, b)] #
\(\mathcal{O}(\min(m,n))\). zip takes two lists and returns a list of
corresponding pairs.
>>>zip [1, 2] ['a', 'b'][(1,'a'),(2,'b')]
If one input list is shorter than the other, excess elements of the longer list are discarded, even if one of the lists is infinite:
>>>zip [1] ['a', 'b'][(1,'a')]>>>zip [1, 2] ['a'][(1,'a')]>>>zip [] [1..][]>>>zip [1..] [][]
zip is right-lazy:
>>>zip [] undefined[]>>>zip undefined []*** Exception: Prelude.undefined ...
zip is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
print :: Show a => a -> IO () #
The print function outputs a value of any printable type to the
standard output device.
Printable types are those that are instances of class Show; print
converts values to strings for output using the show operation and
adds a newline.
For example, a program to print the first 20 integers and their powers of 2 could be written as:
main = print ([(n, 2^n) | n <- [0..19]])
The trace function outputs the trace message given as its first argument,
before returning the second argument as its result.
For example, this returns the value of f x and outputs the message to stderr.
Depending on your terminal (settings), they may or may not be mixed.
>>>let x = 123; f = show>>>trace ("calling f with x = " ++ show x) (f x)calling f with x = 123 "123"
The trace function should only be used for debugging, or for monitoring
execution. The function is not referentially transparent: its type indicates
that it is a pure function but it has the side effect of outputting the
trace message.
map :: (a -> b) -> [a] -> [b] #
\(\mathcal{O}(n)\). map f xs is the list obtained by applying f to
each element of xs, i.e.,
map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn] map f [x1, x2, ...] == [f x1, f x2, ...]
>>>map (+1) [1, 2, 3][2,3,4]
guard :: Alternative f => Bool -> f () #
Conditional failure of Alternative computations. Defined by
guard True =pure() guard False =empty
Examples
Common uses of guard include conditionally signaling an error in
an error monad and conditionally rejecting the current choice in an
Alternative-based parser.
As an example of signaling an error in the error monad Maybe,
consider a safe division function safeDiv x y that returns
Nothing when the denominator y is zero and otherwise. For example:Just (x `div`
y)
>>>safeDiv 4 0Nothing
>>>safeDiv 4 2Just 2
A definition of safeDiv using guards, but not guard:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y | y /= 0 = Just (x `div` y)
| otherwise = Nothing
A definition of safeDiv using guard and Monad do-notation:
safeDiv :: Int -> Int -> Maybe Int safeDiv x y = do guard (y /= 0) return (x `div` y)
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.
'' can be understood as the join bssdo expression
do bs <- bss bs
Examples
A common use of join is to run an IO computation returned from
an STM transaction, since STM transactions
can't perform IO directly. Recall that
atomically :: STM a -> IO a
is used to run STM transactions atomically. So, by
specializing the types of atomically and join to
atomically:: STM (IO b) -> IO (IO b)join:: IO (IO b) -> IO b
we can compose them as
join.atomically:: STM (IO b) -> IO b
class Applicative m => Monad (m :: Type -> Type) where #
The Monad class defines the basic operations over a monad,
a concept from a branch of mathematics known as category theory.
From the perspective of a Haskell programmer, however, it is best to
think of a monad as an abstract datatype of actions.
Haskell's do expressions provide a convenient syntax for writing
monadic expressions.
Instances of Monad should satisfy the following:
- Left identity
returna>>=k = k a- Right identity
m>>=return= m- Associativity
m>>=(\x -> k x>>=h) = (m>>=k)>>=h
Furthermore, the Monad and Applicative operations should relate as follows:
The above laws imply:
and that pure and (<*>) satisfy the applicative functor laws.
The instances of Monad for lists, Maybe and IO
defined in the Prelude satisfy these laws.
Minimal complete definition
Methods
(>>=) :: m a -> (a -> m b) -> m b infixl 1 #
Sequentially compose two actions, passing any value produced by the first as an argument to the second.
'as ' can be understood as the >>= bsdo expression
do a <- as bs a
(>>) :: m a -> m b -> m b infixl 1 #
Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.
'as ' can be understood as the >> bsdo expression
do as bs
Inject a value into the monadic type.
Instances
| Monad IResult | |
| Monad Parser | |
| Monad Result | |
| Monad Identity | Since: base-4.8.0.0 |
| Monad First | Since: base-4.8.0.0 |
| Monad Last | Since: base-4.8.0.0 |
| Monad Down | Since: base-4.11.0.0 |
| Monad First | Since: base-4.9.0.0 |
| Monad Last | Since: base-4.9.0.0 |
| Monad Max | Since: base-4.9.0.0 |
| Monad Min | Since: base-4.9.0.0 |
| Monad Dual | Since: base-4.8.0.0 |
| Monad Product | Since: base-4.8.0.0 |
| Monad Sum | Since: base-4.8.0.0 |
| Monad STM | Since: base-4.3.0.0 |
| Monad Par1 | Since: base-4.9.0.0 |
| Monad P | Since: base-2.1 |
| Monad ReadP | Since: base-2.1 |
| Monad ReadPrec | Since: base-2.1 |
| Monad Put | |
| Monad Seq | |
| Monad Tree | |
| Monad DNonEmpty | |
| Monad DList | |
| Monad IO | Since: base-2.1 |
| Monad Root | |
| Monad Array | |
| Monad SmallArray | |
Defined in Data.Primitive.SmallArray Methods (>>=) :: SmallArray a -> (a -> SmallArray b) -> SmallArray b # (>>) :: SmallArray a -> SmallArray b -> SmallArray b # return :: a -> SmallArray a # | |
| Monad Q | |
| Monad Capability | |
Defined in System.Console.Terminfo.Base Methods (>>=) :: Capability a -> (a -> Capability b) -> Capability b # (>>) :: Capability a -> Capability b -> Capability b # return :: a -> Capability a # | |
| Monad Vector | |
| Monad Id | |
| Monad NonEmpty | Since: base-4.9.0.0 |
| Monad Maybe | Since: base-2.1 |
| Monad Solo | Since: base-4.15 |
| Monad [] | Since: base-2.1 |
| Monad (Parser i) | |
| Monad m => Monad (WrappedMonad m) | Since: base-4.7.0.0 |
Defined in Control.Applicative Methods (>>=) :: WrappedMonad m a -> (a -> WrappedMonad m b) -> WrappedMonad m b # (>>) :: WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m b # return :: a -> WrappedMonad m a # | |
| ArrowApply a => Monad (ArrowMonad a) | Since: base-2.1 |
Defined in Control.Arrow Methods (>>=) :: ArrowMonad a a0 -> (a0 -> ArrowMonad a b) -> ArrowMonad a b # (>>) :: ArrowMonad a a0 -> ArrowMonad a b -> ArrowMonad a b # return :: a0 -> ArrowMonad a a0 # | |
| Monad (Either e) | Since: base-4.4.0.0 |
| Monad (Proxy :: Type -> Type) | Since: base-4.7.0.0 |
| Monad (U1 :: Type -> Type) | Since: base-4.9.0.0 |
| Monad (ST s) | Since: base-2.1 |
| Monad (SetM s) | |
| Functor f => Monad (Free f) | |
| Monad m => Monad (InputT m) | |
| Monad m => Monad (HtmlT m) | Basically acts like Writer. |
| Monad f => Monad (WrappedPoly f) | |
Defined in Data.MonoTraversable Methods (>>=) :: WrappedPoly f a -> (a -> WrappedPoly f b) -> WrappedPoly f b # (>>) :: WrappedPoly f a -> WrappedPoly f b -> WrappedPoly f b # return :: a -> WrappedPoly f a # | |
| Monad m => Monad (ResourceT m) | |
| Semigroup a => Monad (These a) | |
| Monad m => Monad (QuoteToQuasi m) | |
| Semigroup a => Monad (These a) | |
| Monad m => Monad (MaybeT m) | |
| Functor backend => Monad (Wizard backend) | |
| Monoid a => Monad ((,) a) | Since: base-4.9.0.0 |
| Monad m => Monad (Kleisli m a) | Since: base-4.14.0.0 |
| Monad f => Monad (Ap f) | Since: base-4.12.0.0 |
| Monad f => Monad (Alt f) | Since: base-4.8.0.0 |
| Monad f => Monad (Rec1 f) | Since: base-4.9.0.0 |
| (Applicative f, Monad f) => Monad (WhenMissing f x) | Equivalent to Since: containers-0.5.9 |
Defined in Data.IntMap.Internal Methods (>>=) :: WhenMissing f x a -> (a -> WhenMissing f x b) -> WhenMissing f x b # (>>) :: WhenMissing f x a -> WhenMissing f x b -> WhenMissing f x b # return :: a -> WhenMissing f x a # | |
| (Functor f, Monad m) => Monad (FreeT f m) | |
| Monad m => Monad (StateT s m) | |
| Monad (Tagged s) | |
| (Monad m, Error e) => Monad (ErrorT e m) | |
| Monad m => Monad (ExceptT e m) | |
| Monad m => Monad (ReaderT r m) | |
| Monad m => Monad (StateT s m) | |
| (Monoid a, Monoid b) => Monad ((,,) a b) | Since: base-4.14.0.0 |
| (Monad f, Monad g) => Monad (f :*: g) | Since: base-4.9.0.0 |
| Monad (ConduitT i o m) | |
| (Monad f, Applicative f) => Monad (WhenMatched f x y) | Equivalent to Since: containers-0.5.9 |
Defined in Data.IntMap.Internal Methods (>>=) :: WhenMatched f x y a -> (a -> WhenMatched f x y b) -> WhenMatched f x y b # (>>) :: WhenMatched f x y a -> WhenMatched f x y b -> WhenMatched f x y b # return :: a -> WhenMatched f x y a # | |
| (Applicative f, Monad f) => Monad (WhenMissing f k x) | Equivalent to Since: containers-0.5.9 |
Defined in Data.Map.Internal Methods (>>=) :: WhenMissing f k x a -> (a -> WhenMissing f k x b) -> WhenMissing f k x b # (>>) :: WhenMissing f k x a -> WhenMissing f k x b -> WhenMissing f k x b # return :: a -> WhenMissing f k x a # | |
| Stream s => Monad (ParsecT e s m) |
|
| (Monoid a, Monoid b, Monoid c) => Monad ((,,,) a b c) | Since: base-4.14.0.0 |
| Monad ((->) r) | Since: base-2.1 |
| Monad f => Monad (M1 i c f) | Since: base-4.9.0.0 |
| (Monad f, Applicative f) => Monad (WhenMatched f k x y) | Equivalent to Since: containers-0.5.9 |
Defined in Data.Map.Internal Methods (>>=) :: WhenMatched f k x y a -> (a -> WhenMatched f k x y b) -> WhenMatched f k x y b # (>>) :: WhenMatched f k x y a -> WhenMatched f k x y b -> WhenMatched f k x y b # return :: a -> WhenMatched f k x y a # | |
| Monad m => Monad (Pipe l i o u m) | |
class Functor (f :: Type -> Type) where #
A type f is a Functor if it provides a function fmap which, given any types a and b
lets you apply any function from (a -> b) to turn an f a into an f b, preserving the
structure of f. Furthermore f needs to adhere to the following:
Note, that the second law follows from the free theorem of the type fmap and
the first law, so you need only check that the former condition holds.
Minimal complete definition
Methods
fmap :: (a -> b) -> f a -> f b #
fmap is used to apply a function of type (a -> b) to a value of type f a,
where f is a functor, to produce a value of type f b.
Note that for any type constructor with more than one parameter (e.g., Either),
only the last type parameter can be modified with fmap (e.g., b in `Either a b`).
Some type constructors with two parameters or more have a instance that allows
both the last and the penultimate parameters to be mapped over.Bifunctor
Examples
Convert from a to a Maybe IntMaybe String
using show:
>>>fmap show NothingNothing>>>fmap show (Just 3)Just "3"
Convert from an to an
Either Int IntEither Int String using show:
>>>fmap show (Left 17)Left 17>>>fmap show (Right 17)Right "17"
Double each element of a list:
>>>fmap (*2) [1,2,3][2,4,6]
Apply even to the second element of a pair:
>>>fmap even (2,2)(2,True)
It may seem surprising that the function is only applied to the last element of the tuple
compared to the list example above which applies it to every element in the list.
To understand, remember that tuples are type constructors with multiple type parameters:
a tuple of 3 elements (a,b,c) can also be written (,,) a b c and its Functor instance
is defined for Functor ((,,) a b) (i.e., only the third parameter is free to be mapped over
with fmap).
It explains why fmap can be used with tuples containing values of different types as in the
following example:
>>>fmap even ("hello", 1.0, 4)("hello",1.0,True)
Instances
The Ord class is used for totally ordered datatypes.
Instances of Ord can be derived for any user-defined datatype whose
constituent types are in Ord. The declared order of the constructors in
the data declaration determines the ordering in derived Ord instances. The
Ordering datatype allows a single comparison to determine the precise
ordering of two objects.
Ord, as defined by the Haskell report, implements a total order and has the
following properties:
- Comparability
x <= y || y <= x=True- Transitivity
- if
x <= y && y <= z=True, thenx <= z=True - Reflexivity
x <= x=True- Antisymmetry
- if
x <= y && y <= x=True, thenx == y=True
The following operator interactions are expected to hold:
x >= y=y <= xx < y=x <= y && x /= yx > y=y < xx < y=compare x y == LTx > y=compare x y == GTx == y=compare x y == EQmin x y == if x <= y then x else y=Truemax x y == if x >= y then x else y=True
Note that (7.) and (8.) do not require min and max to return either of
their arguments. The result is merely required to equal one of the
arguments in terms of (==).
Minimal complete definition: either compare or <=.
Using compare can be more efficient for complex types.
Methods
compare :: a -> a -> Ordering #
(<) :: a -> a -> Bool infix 4 #
(<=) :: a -> a -> Bool infix 4 #
(>) :: a -> a -> Bool infix 4 #
Instances
class Monad m => MonadFail (m :: Type -> Type) where #
When a value is bound in do-notation, the pattern on the left
hand side of <- might not match. In this case, this class
provides a function to recover.
A Monad without a MonadFail instance may only be used in conjunction
with pattern that always match, such as newtypes, tuples, data types with
only a single data constructor, and irrefutable patterns (~pat).
Instances of MonadFail should satisfy the following law: fail s should
be a left zero for >>=,
fail s >>= f = fail s
If your Monad is also MonadPlus, a popular definition is
fail _ = mzero
Since: base-4.9.0.0
Instances
class Functor f => Applicative (f :: Type -> Type) where #
A functor with application, providing operations to
A minimal complete definition must include implementations of pure
and of either <*> or liftA2. If it defines both, then they must behave
the same as their default definitions:
(<*>) =liftA2id
liftA2f x y = f<$>x<*>y
Further, any definition must satisfy the following:
- Identity
pureid<*>v = v- Composition
pure(.)<*>u<*>v<*>w = u<*>(v<*>w)- Homomorphism
puref<*>purex =pure(f x)- Interchange
u
<*>purey =pure($y)<*>u
The other methods have the following default definitions, which may be overridden with equivalent specialized implementations:
As a consequence of these laws, the Functor instance for f will satisfy
It may be useful to note that supposing
forall x y. p (q x y) = f x . g y
it follows from the above that
liftA2p (liftA2q u v) =liftA2f u .liftA2g v
If f is also a Monad, it should satisfy
(which implies that pure and <*> satisfy the applicative functor laws).
Methods
Lift a value.
(<*>) :: 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.
Example
Used in combination with (, <$>)( can be used to build a record.<*>)
>>>data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
>>>produceFoo :: Applicative f => f Foo
>>>produceBar :: Applicative f => f Bar>>>produceBaz :: Applicative f => f Baz
>>>mkState :: Applicative f => f MyState>>>mkState = MyState <$> produceFoo <*> produceBar <*> produceBaz
liftA2 :: (a -> b -> c) -> f a -> f b -> f c #
Lift a binary function to actions.
Some functors support an implementation of liftA2 that is more
efficient than the default one. In particular, if fmap is an
expensive operation, it is likely better to use liftA2 than to
fmap over the structure and then use <*>.
This became a typeclass method in 4.10.0.0. Prior to that, it was
a function defined in terms of <*> and fmap.
Example
>>>liftA2 (,) (Just 3) (Just 5)Just (3,5)
(*>) :: f a -> f b -> f b infixl 4 #
Sequence actions, discarding the value of the first argument.
Examples
If used in conjunction with the Applicative instance for Maybe,
you can chain Maybe computations, with a possible "early return"
in case of Nothing.
>>>Just 2 *> Just 3Just 3
>>>Nothing *> Just 3Nothing
Of course a more interesting use case would be to have effectful computations instead of just returning pure values.
>>>import Data.Char>>>import Text.ParserCombinators.ReadP>>>let p = string "my name is " *> munch1 isAlpha <* eof>>>readP_to_S p "my name is Simon"[("Simon","")]
(<*) :: f a -> f b -> f a infixl 4 #
Sequence actions, discarding the value of the second argument.
Instances
| Applicative IResult | |
| Applicative Parser | |
| Applicative Result | |
| Applicative ZipList | f <$> ZipList xs1 <*> ... <*> ZipList xsN
= ZipList (zipWithN f xs1 ... xsN)where (\a b c -> stimes c [a, b]) <$> ZipList "abcd" <*> ZipList "567" <*> ZipList [1..]
= ZipList (zipWith3 (\a b c -> stimes c [a, b]) "abcd" "567" [1..])
= ZipList {getZipList = ["a5","b6b6","c7c7c7"]}Since: base-2.1 |
| Applicative Identity | Since: base-4.8.0.0 |
| Applicative First | Since: base-4.8.0.0 |
| Applicative Last | Since: base-4.8.0.0 |
| Applicative Down | Since: base-4.11.0.0 |
| Applicative First | Since: base-4.9.0.0 |
| Applicative Last | Since: base-4.9.0.0 |
| Applicative Max | Since: base-4.9.0.0 |
| Applicative Min | Since: base-4.9.0.0 |
| Applicative Dual | Since: base-4.8.0.0 |
| Applicative Product | Since: base-4.8.0.0 |
| Applicative Sum | Since: base-4.8.0.0 |
| Applicative STM | Since: base-4.8.0.0 |
| Applicative Par1 | Since: base-4.9.0.0 |
| Applicative P | Since: base-4.5.0.0 |
| Applicative ReadP | Since: base-4.6.0.0 |
| Applicative ReadPrec | Since: base-4.6.0.0 |
| Applicative Put | |
| Applicative RGB | |
| Applicative Seq | Since: containers-0.5.4 |
| Applicative Tree | |
| Applicative DNonEmpty | |
Defined in Data.DList.DNonEmpty.Internal | |
| Applicative DList | |
| Applicative IO | Since: base-2.1 |
| Applicative Root | |
| Applicative Array | |
| Applicative SmallArray | |
Defined in Data.Primitive.SmallArray Methods pure :: a -> SmallArray a # (<*>) :: SmallArray (a -> b) -> SmallArray a -> SmallArray b # liftA2 :: (a -> b -> c) -> SmallArray a -> SmallArray b -> SmallArray c # (*>) :: SmallArray a -> SmallArray b -> SmallArray b # (<*) :: SmallArray a -> SmallArray b -> SmallArray a # | |
| Applicative Q | |
| Applicative Capability | |
Defined in System.Console.Terminfo.Base Methods pure :: a -> Capability a # (<*>) :: Capability (a -> b) -> Capability a -> Capability b # liftA2 :: (a -> b -> c) -> Capability a -> Capability b -> Capability c # (*>) :: Capability a -> Capability b -> Capability b # (<*) :: Capability a -> Capability b -> Capability a # | |
| Applicative Vector | |
| Applicative Id | |
| Applicative NonEmpty | Since: base-4.9.0.0 |
| Applicative Maybe | Since: base-2.1 |
| Applicative Solo | Since: base-4.15 |
| Applicative [] | Since: base-2.1 |
| Applicative (Parser i) | |
| Monad m => Applicative (WrappedMonad m) | Since: base-2.1 |
Defined in Control.Applicative Methods pure :: a -> WrappedMonad m a # (<*>) :: WrappedMonad m (a -> b) -> WrappedMonad m a -> WrappedMonad m b # liftA2 :: (a -> b -> c) -> WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m c # (*>) :: WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m b # (<*) :: WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m a # | |
| Arrow a => Applicative (ArrowMonad a) | Since: base-4.6.0.0 |
Defined in Control.Arrow Methods pure :: a0 -> ArrowMonad a a0 # (<*>) :: ArrowMonad a (a0 -> b) -> ArrowMonad a a0 -> ArrowMonad a b # liftA2 :: (a0 -> b -> c) -> ArrowMonad a a0 -> ArrowMonad a b -> ArrowMonad a c # (*>) :: ArrowMonad a a0 -> ArrowMonad a b -> ArrowMonad a b # (<*) :: ArrowMonad a a0 -> ArrowMonad a b -> ArrowMonad a a0 # | |
| Applicative (Either e) | Since: base-3.0 |
| Applicative (StateL s) | Since: base-4.0 |
| Applicative (StateR s) | Since: base-4.0 |
| Applicative (Proxy :: Type -> Type) | Since: base-4.7.0.0 |
| Applicative (U1 :: Type -> Type) | Since: base-4.9.0.0 |
| Applicative (ST s) | Since: base-4.4.0.0 |
| Monad m => Applicative (ZipSource m) | |
Defined in Data.Conduit.Internal.Conduit | |
| Applicative (SetM s) | |
| Functor f => Applicative (Free f) | |
| Applicative m => Applicative (InputT m) | |
| Applicative m => Applicative (HtmlT m) | Based on the monad instance. |
| Applicative f => Applicative (WrappedPoly f) | |
Defined in Data.MonoTraversable Methods pure :: a -> WrappedPoly f a # (<*>) :: WrappedPoly f (a -> b) -> WrappedPoly f a -> WrappedPoly f b # liftA2 :: (a -> b -> c) -> WrappedPoly f a -> WrappedPoly f b -> WrappedPoly f c # (*>) :: WrappedPoly f a -> WrappedPoly f b -> WrappedPoly f b # (<*) :: WrappedPoly f a -> WrappedPoly f b -> WrappedPoly f a # | |
| Applicative m => Applicative (ResourceT m) | |
Defined in Control.Monad.Trans.Resource.Internal | |
| Semigroup a => Applicative (These a) | |
| Applicative m => Applicative (QuoteToQuasi m) | |
Defined in Language.Haskell.TH.Syntax.Compat Methods pure :: a -> QuoteToQuasi m a # (<*>) :: QuoteToQuasi m (a -> b) -> QuoteToQuasi m a -> QuoteToQuasi m b # liftA2 :: (a -> b -> c) -> QuoteToQuasi m a -> QuoteToQuasi m b -> QuoteToQuasi m c # (*>) :: QuoteToQuasi m a -> QuoteToQuasi m b -> QuoteToQuasi m b # (<*) :: QuoteToQuasi m a -> QuoteToQuasi m b -> QuoteToQuasi m a # | |
| Semigroup a => Applicative (These a) | |
| (Functor m, Monad m) => Applicative (MaybeT m) | |
| Functor backend => Applicative (Wizard backend) | |
Defined in System.Console.Wizard.Internal Methods pure :: a -> Wizard backend a # (<*>) :: Wizard backend (a -> b) -> Wizard backend a -> Wizard backend b # liftA2 :: (a -> b -> c) -> Wizard backend a -> Wizard backend b -> Wizard backend c # (*>) :: Wizard backend a -> Wizard backend b -> Wizard backend b # (<*) :: Wizard backend a -> Wizard backend b -> Wizard backend a # | |
| Monoid a => Applicative ((,) a) | For tuples, the ("hello ", (+15)) <*> ("world!", 2002)
("hello world!",2017)Since: base-2.1 |
| Arrow a => Applicative (WrappedArrow a b) | Since: base-2.1 |
Defined in Control.Applicative Methods pure :: a0 -> WrappedArrow a b a0 # (<*>) :: WrappedArrow a b (a0 -> b0) -> WrappedArrow a b a0 -> WrappedArrow a b b0 # liftA2 :: (a0 -> b0 -> c) -> WrappedArrow a b a0 -> WrappedArrow a b b0 -> WrappedArrow a b c # (*>) :: WrappedArrow a b a0 -> WrappedArrow a b b0 -> WrappedArrow a b b0 # (<*) :: WrappedArrow a b a0 -> WrappedArrow a b b0 -> WrappedArrow a b a0 # | |
| Applicative m => Applicative (Kleisli m a) | Since: base-4.14.0.0 |
Defined in Control.Arrow | |
| Monoid m => Applicative (Const m :: Type -> Type) | Since: base-2.0.1 |
| Applicative f => Applicative (Ap f) | Since: base-4.12.0.0 |
| Applicative f => Applicative (Alt f) | Since: base-4.8.0.0 |
| Applicative f => Applicative (Rec1 f) | Since: base-4.9.0.0 |
| Monad m => Applicative (ZipSink i m) | |
Defined in Data.Conduit.Internal.Conduit | |
| (Applicative f, Monad f) => Applicative (WhenMissing f x) | Equivalent to Since: containers-0.5.9 |
Defined in Data.IntMap.Internal Methods pure :: a -> WhenMissing f x a # (<*>) :: WhenMissing f x (a -> b) -> WhenMissing f x a -> WhenMissing f x b # liftA2 :: (a -> b -> c) -> WhenMissing f x a -> WhenMissing f x b -> WhenMissing f x c # (*>) :: WhenMissing f x a -> WhenMissing f x b -> WhenMissing f x b # (<*) :: WhenMissing f x a -> WhenMissing f x b -> WhenMissing f x a # | |
| (Functor f, Functor a, Monad a) => Applicative (FreeT f a) | |
Defined in Control.Monad.Free | |
| Applicative (Bazaar a b) | |
Defined in Lens.Micro | |
| (Functor m, Monad m) => Applicative (StateT s m) | |
| Applicative (Tagged s) | |
| (Functor m, Monad m) => Applicative (ErrorT e m) | |
Defined in Control.Monad.Trans.Error | |
| (Functor m, Monad m) => Applicative (ExceptT e m) | |
Defined in Control.Monad.Trans.Except | |
| Applicative m => Applicative (ReaderT r m) | |
Defined in Control.Monad.Trans.Reader | |
| (Functor m, Monad m) => Applicative (StateT s m) | |
Defined in Control.Monad.Trans.State.Strict | |
| (Monoid a, Monoid b) => Applicative ((,,) a b) | Since: base-4.14.0.0 |
| (Applicative f, Applicative g) => Applicative (f :*: g) | Since: base-4.9.0.0 |
| Monoid c => Applicative (K1 i c :: Type -> Type) | Since: base-4.12.0.0 |
| Applicative (ConduitT i o m) | |
Defined in Data.Conduit.Internal.Conduit Methods pure :: a -> ConduitT i o m a # (<*>) :: ConduitT i o m (a -> b) -> ConduitT i o m a -> ConduitT i o m b # liftA2 :: (a -> b -> c) -> ConduitT i o m a -> ConduitT i o m b -> ConduitT i o m c # (*>) :: ConduitT i o m a -> ConduitT i o m b -> ConduitT i o m b # (<*) :: ConduitT i o m a -> ConduitT i o m b -> ConduitT i o m a # | |
| Monad m => Applicative (ZipConduit i o m) | |
Defined in Data.Conduit.Internal.Conduit Methods pure :: a -> ZipConduit i o m a # (<*>) :: ZipConduit i o m (a -> b) -> ZipConduit i o m a -> ZipConduit i o m b # liftA2 :: (a -> b -> c) -> ZipConduit i o m a -> ZipConduit i o m b -> ZipConduit i o m c # (*>) :: ZipConduit i o m a -> ZipConduit i o m b -> ZipConduit i o m b # (<*) :: ZipConduit i o m a -> ZipConduit i o m b -> ZipConduit i o m a # | |
| (Monad f, Applicative f) => Applicative (WhenMatched f x y) | Equivalent to Since: containers-0.5.9 |
Defined in Data.IntMap.Internal Methods pure :: a -> WhenMatched f x y a # (<*>) :: WhenMatched f x y (a -> b) -> WhenMatched f x y a -> WhenMatched f x y b # liftA2 :: (a -> b -> c) -> WhenMatched f x y a -> WhenMatched f x y b -> WhenMatched f x y c # (*>) :: WhenMatched f x y a -> WhenMatched f x y b -> WhenMatched f x y b # (<*) :: WhenMatched f x y a -> WhenMatched f x y b -> WhenMatched f x y a # | |
| (Applicative f, Monad f) => Applicative (WhenMissing f k x) | Equivalent to Since: containers-0.5.9 |
Defined in Data.Map.Internal Methods pure :: a -> WhenMissing f k x a # (<*>) :: WhenMissing f k x (a -> b) -> WhenMissing f k x a -> WhenMissing f k x b # liftA2 :: (a -> b -> c) -> WhenMissing f k x a -> WhenMissing f k x b -> WhenMissing f k x c # (*>) :: WhenMissing f k x a -> WhenMissing f k x b -> WhenMissing f k x b # (<*) :: WhenMissing f k x a -> WhenMissing f k x b -> WhenMissing f k x a # | |
| Stream s => Applicative (ParsecT e s m) |
|
Defined in Text.Megaparsec.Internal Methods pure :: a -> ParsecT e s m a # (<*>) :: ParsecT e s m (a -> b) -> ParsecT e s m a -> ParsecT e s m b # liftA2 :: (a -> b -> c) -> ParsecT e s m a -> ParsecT e s m b -> ParsecT e s m c # (*>) :: ParsecT e s m a -> ParsecT e s m b -> ParsecT e s m b # (<*) :: ParsecT e s m a -> ParsecT e s m b -> ParsecT e s m a # | |
| (Monoid a, Monoid b, Monoid c) => Applicative ((,,,) a b c) | Since: base-4.14.0.0 |
Defined in GHC.Base | |
| Applicative ((->) r) | Since: base-2.1 |
| (Applicative f, Applicative g) => Applicative (Compose f g) | Since: base-4.9.0.0 |
Defined in Data.Functor.Compose | |
| (Applicative f, Applicative g) => Applicative (f :.: g) | Since: base-4.9.0.0 |
| Applicative f => Applicative (M1 i c f) | Since: base-4.9.0.0 |
| (Monad f, Applicative f) => Applicative (WhenMatched f k x y) | Equivalent to Since: containers-0.5.9 |
Defined in Data.Map.Internal Methods pure :: a -> WhenMatched f k x y a # (<*>) :: WhenMatched f k x y (a -> b) -> WhenMatched f k x y a -> WhenMatched f k x y b # liftA2 :: (a -> b -> c) -> WhenMatched f k x y a -> WhenMatched f k x y b -> WhenMatched f k x y c # (*>) :: WhenMatched f k x y a -> WhenMatched f k x y b -> WhenMatched f k x y b # (<*) :: WhenMatched f k x y a -> WhenMatched f k x y b -> WhenMatched f k x y a # | |
| Monad m => Applicative (Pipe l i o u m) | |
Defined in Data.Conduit.Internal.Pipe Methods pure :: a -> Pipe l i o u m a # (<*>) :: Pipe l i o u m (a -> b) -> Pipe l i o u m a -> Pipe l i o u m b # liftA2 :: (a -> b -> c) -> Pipe l i o u m a -> Pipe l i o u m b -> Pipe l i o u m c # (*>) :: Pipe l i o u m a -> Pipe l i o u m b -> Pipe l i o u m b # (<*) :: Pipe l i o u m a -> Pipe l i o u m b -> Pipe l i o u m a # | |
sum :: (Foldable t, Num a) => t a -> a #
The sum function computes the sum of the numbers of a structure.
Examples
Basic usage:
>>>sum []0
>>>sum [42]42
>>>sum [1..10]55
>>>sum [4.1, 2.0, 1.7]7.8
>>>sum [1..]* Hangs forever *
Since: base-4.8.0.0
product :: (Foldable t, Num a) => t a -> a #
The product function computes the product of the numbers of a
structure.
Examples
Basic usage:
>>>product []1
>>>product [42]42
>>>product [1..10]3628800
>>>product [4.1, 2.0, 1.7]13.939999999999998
>>>product [1..]* Hangs forever *
Since: base-4.8.0.0
minimum :: (Foldable t, Ord a) => t a -> a #
The least element of a non-empty structure.
This function is non-total and will raise a runtime exception if the structure happens to be empty. A structure that supports random access and maintains its elements in order should provide a specialised implementation to return the minimum in faster than linear time.
Examples
Basic usage:
>>>minimum [1..10]1
>>>minimum []*** Exception: Prelude.minimum: empty list
>>>minimum Nothing*** Exception: minimum: empty structure
WARNING: This function is partial for possibly-empty structures like lists.
Since: base-4.8.0.0
maximum :: (Foldable t, Ord a) => t a -> a #
The largest element of a non-empty structure.
This function is non-total and will raise a runtime exception if the structure happens to be empty. A structure that supports random access and maintains its elements in order should provide a specialised implementation to return the maximum in faster than linear time.
Examples
Basic usage:
>>>maximum [1..10]10
>>>maximum []*** Exception: Prelude.maximum: empty list
>>>maximum Nothing*** Exception: maximum: empty structure
WARNING: This function is partial for possibly-empty structures like lists.
Since: base-4.8.0.0
foldr1 :: Foldable t => (a -> a -> a) -> t a -> a #
A variant of foldr that has no base case,
and thus may only be applied to non-empty structures.
This function is non-total and will raise a runtime exception if the structure happens to be empty.
Examples
Basic usage:
>>>foldr1 (+) [1..4]10
>>>foldr1 (+) []Exception: Prelude.foldr1: empty list
>>>foldr1 (+) Nothing*** Exception: foldr1: empty structure
>>>foldr1 (-) [1..4]-2
>>>foldr1 (&&) [True, False, True, True]False
>>>foldr1 (||) [False, False, True, True]True
>>>foldr1 (+) [1..]* Hangs forever *
foldl1 :: Foldable t => (a -> a -> a) -> t a -> a #
A variant of foldl that has no base case,
and thus may only be applied to non-empty structures.
This function is non-total and will raise a runtime exception if the structure happens to be empty.
foldl1f =foldl1f .toList
Examples
Basic usage:
>>>foldl1 (+) [1..4]10
>>>foldl1 (+) []*** Exception: Prelude.foldl1: empty list
>>>foldl1 (+) Nothing*** Exception: foldl1: empty structure
>>>foldl1 (-) [1..4]-8
>>>foldl1 (&&) [True, False, True, True]False
>>>foldl1 (||) [False, False, True, True]True
>>>foldl1 (+) [1..]* Hangs forever *
elem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 #
Does the element occur in the structure?
Note: elem is often used in infix form.
Examples
Basic usage:
>>>3 `elem` []False
>>>3 `elem` [1,2]False
>>>3 `elem` [1,2,3,4,5]True
For infinite structures, the default implementation of elem
terminates if the sought-after value exists at a finite distance
from the left side of the structure:
>>>3 `elem` [1..]True
>>>3 `elem` ([4..] ++ [3])* Hangs forever *
Since: base-4.8.0.0
length :: Foldable t => t a -> Int #
Returns the size/length of a finite structure as an Int. The
default implementation just counts elements starting with the leftmost.
Instances for structures that can compute the element count faster
than via element-by-element counting, should provide a specialised
implementation.
Examples
Basic usage:
>>>length []0
>>>length ['a', 'b', 'c']3>>>length [1..]* Hangs forever *
Since: base-4.8.0.0
foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b #
Left-associative fold of a structure but with strict application of the operator.
This ensures that each step of the fold is forced to Weak Head Normal
Form before being applied, avoiding the collection of thunks that would
otherwise occur. This is often what you want to strictly reduce a
finite structure to a single strict result (e.g. sum).
For a general Foldable structure this should be semantically identical
to,
foldl' f z =foldl'f z .toList
Since: base-4.6.0.0
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b #
Left-associative fold of a structure, lazy in the accumulator. This is rarely what you want, but can work well for structures with efficient right-to-left sequencing and an operator that is lazy in its left argument.
In the case of lists, foldl, when applied to a binary operator, a
starting value (typically the left-identity of the operator), and a
list, reduces the list using the binary operator, from left to right:
foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
Note that to produce the outermost application of the operator the
entire input list must be traversed. Like all left-associative folds,
foldl will diverge if given an infinite list.
If you want an efficient strict left-fold, you probably want to use
foldl' instead of foldl. The reason for this is that the latter
does not force the inner results (e.g. z `f` x1 in the above
example) before applying them to the operator (e.g. to (`f` x2)).
This results in a thunk chain \(\mathcal{O}(n)\) elements long, which
then must be evaluated from the outside-in.
For a general Foldable structure this should be semantically identical
to:
foldl f z =foldlf z .toList
Examples
The first example is a strict fold, which in practice is best performed
with foldl'.
>>>foldl (+) 42 [1,2,3,4]52
Though the result below is lazy, the input is reversed before prepending it to the initial accumulator, so corecursion begins only after traversing the entire input string.
>>>foldl (\acc c -> c : acc) "abcd" "efgh""hgfeabcd"
A left fold of a structure that is infinite on the right cannot terminate, even when for any finite input the fold just returns the initial accumulator:
>>>foldl (\a _ -> a) 0 $ repeat 1* Hangs forever *
WARNING: When it comes to lists, you always want to use either foldl' or foldr instead.
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b #
Right-associative fold of a structure, lazy in the accumulator.
In the case of lists, foldr, when applied to a binary operator, a
starting value (typically the right-identity of the operator), and a
list, reduces the list using the binary operator, from right to left:
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
Note that since the head of the resulting expression is produced by an
application of the operator to the first element of the list, given an
operator lazy in its right argument, foldr can produce a terminating
expression from an unbounded list.
For a general Foldable structure this should be semantically identical
to,
foldr f z =foldrf z .toList
Examples
Basic usage:
>>>foldr (||) False [False, True, False]True
>>>foldr (||) False []False
>>>foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd']"foodcba"
Infinite structures
⚠️ Applying foldr to infinite structures usually doesn't terminate.
It may still terminate under one of the following conditions:
- the folding function is short-circuiting
- the folding function is lazy on its second argument
Short-circuiting
( short-circuits on ||)True values, so the following terminates
because there is a True value finitely far from the left side:
>>>foldr (||) False (True : repeat False)True
But the following doesn't terminate:
>>>foldr (||) False (repeat False ++ [True])* Hangs forever *
Laziness in the second argument
Applying foldr to infinite structures terminates when the operator is
lazy in its second argument (the initial accumulator is never used in
this case, and so could be left undefined, but [] is more clear):
>>>take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
null :: Foldable t => t a -> Bool #
Test whether the structure is empty. The default implementation is Left-associative and lazy in both the initial element and the accumulator. Thus optimised for structures where the first element can be accessed in constant time. Structures where this is not the case should have a non-default implementation.
Examples
Basic usage:
>>>null []True
>>>null [1]False
null is expected to terminate even for infinite structures.
The default implementation terminates provided the structure
is bounded on the left (there is a leftmost element).
>>>null [1..]False
Since: base-4.8.0.0
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 collect the results. For
a version that ignores the results see mapM_.
Examples
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a) #
Evaluate each monadic action in the structure from left to
right, and collect the results. For a version that ignores the
results see sequence_.
Examples
Basic usage:
The first two examples are instances where the input and
and output of sequence are isomorphic.
>>>sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
>>>sequence $ [Right 1,Right 2,Right 3,Right 4]Right [1,2,3,4]
The following examples demonstrate short circuit behavior
for sequence.
>>>sequence $ Left [1,2,3,4]Left [1,2,3,4]
>>>sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]Left 0
The character type Char is an enumeration whose values represent
Unicode (or equivalently ISO/IEC 10646) code points (i.e. characters, see
http://www.unicode.org/ for details). This set extends the ISO 8859-1
(Latin-1) character set (the first 256 characters), which is itself an extension
of the ASCII character set (the first 128 characters). A character literal in
Haskell has type Char.
To convert a Char to or from the corresponding Int value defined
by Unicode, use toEnum and fromEnum from the
Enum class respectively (or equivalently ord and
chr).
Instances
The Maybe type encapsulates an optional value. A value of type
either contains a value of type Maybe aa (represented as ),
or it is empty (represented as Just aNothing). Using Maybe is a good way to
deal with errors or exceptional cases without resorting to drastic
measures such as error.
The Maybe type is also a monad. It is a simple kind of error
monad, where all errors are represented by Nothing. A richer
error monad can be built using the Either type.
Instances
| FromJSON1 Maybe | |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON1 Maybe | |
Defined in Data.Aeson.Types.ToJSON Methods liftToJSON :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> Maybe a -> Value # liftToJSONList :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> [Maybe a] -> Value # liftToEncoding :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> Maybe a -> Encoding # liftToEncodingList :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> [Maybe a] -> Encoding # liftOmitField :: (a -> Bool) -> Maybe a -> Bool # | |
| MonadFail Maybe | Since: base-4.9.0.0 |
Defined in Control.Monad.Fail | |
| Foldable Maybe | Since: base-2.1 |
Defined in Data.Foldable Methods fold :: Monoid m => Maybe m -> m # foldMap :: Monoid m => (a -> m) -> Maybe a -> m # foldMap' :: Monoid m => (a -> m) -> Maybe a -> m # foldr :: (a -> b -> b) -> b -> Maybe a -> b # foldr' :: (a -> b -> b) -> b -> Maybe a -> b # foldl :: (b -> a -> b) -> b -> Maybe a -> b # foldl' :: (b -> a -> b) -> b -> Maybe a -> b # foldr1 :: (a -> a -> a) -> Maybe a -> a # foldl1 :: (a -> a -> a) -> Maybe a -> a # elem :: Eq a => a -> Maybe a -> Bool # maximum :: Ord a => Maybe a -> a # minimum :: Ord a => Maybe a -> a # | |
| Eq1 Maybe | Since: base-4.9.0.0 |
| Ord1 Maybe | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
| Read1 Maybe | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
| Show1 Maybe | Since: base-4.9.0.0 |
| Traversable Maybe | Since: base-2.1 |
| Alternative Maybe | Since: base-2.1 |
| Applicative Maybe | Since: base-2.1 |
| Functor Maybe | Since: base-2.1 |
| Monad Maybe | Since: base-2.1 |
| MonadPlus Maybe | Since: base-2.1 |
| MonadThrow Maybe | |
Defined in Control.Monad.Catch | |
| Hashable1 Maybe | |
Defined in Data.Hashable.Class | |
| Generic1 Maybe | |
| Reportable Maybe e | |
Defined in Hledger.Reports.ReportOptions | |
| Lift a => Lift (Maybe a :: Type) | |
| FromJSON a => FromJSON (Maybe a) | |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON a => ToJSON (Maybe a) | |
| Data a => Data (Maybe a) | Since: base-4.0.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Maybe a -> c (Maybe a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Maybe a) # toConstr :: Maybe a -> Constr # dataTypeOf :: Maybe a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Maybe a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Maybe a)) # gmapT :: (forall b. Data b => b -> b) -> Maybe a -> Maybe a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Maybe a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Maybe a -> r # gmapQ :: (forall d. Data d => d -> u) -> Maybe a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Maybe a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Maybe a -> m (Maybe a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Maybe a -> m (Maybe a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Maybe a -> m (Maybe a) # | |
| Semigroup a => Monoid (Maybe a) | Lift a semigroup into Since 4.11.0: constraint on inner Since: base-2.1 |
| Semigroup a => Semigroup (Maybe a) | Since: base-4.9.0.0 |
| Generic (Maybe a) | |
| SingKind a => SingKind (Maybe a) | Since: base-4.9.0.0 |
Defined in GHC.Generics Associated Types type DemoteRep (Maybe a) | |
| Read a => Read (Maybe a) | Since: base-2.1 |
| Show a => Show (Maybe a) | Since: base-2.1 |
| Default (Maybe a) | |
Defined in System.Console.CmdArgs.Default | |
| Default (Maybe a) | |
Defined in Data.Default.Class | |
| Eq a => Eq (Maybe a) | Since: base-2.1 |
| Ord a => Ord (Maybe a) | Since: base-2.1 |
| Hashable a => Hashable (Maybe a) | |
Defined in Data.Hashable.Class | |
| HasAmounts a => HasAmounts (Maybe a) | |
Defined in Hledger.Data.Types Methods styleAmounts :: Map CommoditySymbol AmountStyle -> Maybe a -> Maybe a # | |
| MonoFoldable (Maybe a) | |
Defined in Data.MonoTraversable Methods ofoldMap :: Monoid m => (Element (Maybe a) -> m) -> Maybe a -> m # ofoldr :: (Element (Maybe a) -> b -> b) -> b -> Maybe a -> b # ofoldl' :: (a0 -> Element (Maybe a) -> a0) -> a0 -> Maybe a -> a0 # otoList :: Maybe a -> [Element (Maybe a)] # oall :: (Element (Maybe a) -> Bool) -> Maybe a -> Bool # oany :: (Element (Maybe a) -> Bool) -> Maybe a -> Bool # olength64 :: Maybe a -> Int64 # ocompareLength :: Integral i => Maybe a -> i -> Ordering # otraverse_ :: Applicative f => (Element (Maybe a) -> f b) -> Maybe a -> f () # ofor_ :: Applicative f => Maybe a -> (Element (Maybe a) -> f b) -> f () # omapM_ :: Applicative m => (Element (Maybe a) -> m ()) -> Maybe a -> m () # oforM_ :: Applicative m => Maybe a -> (Element (Maybe a) -> m ()) -> m () # ofoldlM :: Monad m => (a0 -> Element (Maybe a) -> m a0) -> a0 -> Maybe a -> m a0 # ofoldMap1Ex :: Semigroup m => (Element (Maybe a) -> m) -> Maybe a -> m # ofoldr1Ex :: (Element (Maybe a) -> Element (Maybe a) -> Element (Maybe a)) -> Maybe a -> Element (Maybe a) # ofoldl1Ex' :: (Element (Maybe a) -> Element (Maybe a) -> Element (Maybe a)) -> Maybe a -> Element (Maybe a) # headEx :: Maybe a -> Element (Maybe a) # lastEx :: Maybe a -> Element (Maybe a) # unsafeHead :: Maybe a -> Element (Maybe a) # unsafeLast :: Maybe a -> Element (Maybe a) # maximumByEx :: (Element (Maybe a) -> Element (Maybe a) -> Ordering) -> Maybe a -> Element (Maybe a) # minimumByEx :: (Element (Maybe a) -> Element (Maybe a) -> Ordering) -> Maybe a -> Element (Maybe a) # | |
| MonoFunctor (Maybe a) | |
| MonoPointed (Maybe a) | |
| MonoTraversable (Maybe a) | |
| Pretty a => Pretty (Maybe a) | Ignore
|
Defined in Prettyprinter.Internal | |
| SingI ('Nothing :: Maybe a) | Since: base-4.9.0.0 |
Defined in GHC.Generics | |
| Each (Maybe a) (Maybe b) a b | |
| SingI a2 => SingI ('Just a2 :: Maybe a1) | Since: base-4.9.0.0 |
Defined in GHC.Generics | |
| type Rep1 Maybe | Since: base-4.6.0.0 |
| type DemoteRep (Maybe a) | |
Defined in GHC.Generics | |
| type Rep (Maybe a) | Since: base-4.6.0.0 |
Defined in GHC.Generics | |
| data Sing (b :: Maybe a) | |
| type Element (Maybe a) | |
Defined in Data.MonoTraversable | |
Instances
| FromJSON Ordering | |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON Ordering | |
| Data Ordering | Since: base-4.0.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Ordering -> c Ordering # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Ordering # toConstr :: Ordering -> Constr # dataTypeOf :: Ordering -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Ordering) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Ordering) # gmapT :: (forall b. Data b => b -> b) -> Ordering -> Ordering # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Ordering -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Ordering -> r # gmapQ :: (forall d. Data d => d -> u) -> Ordering -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Ordering -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Ordering -> m Ordering # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Ordering -> m Ordering # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Ordering -> m Ordering # | |
| Monoid Ordering | Since: base-2.1 |
| Semigroup Ordering | Since: base-4.9.0.0 |
| Bounded Ordering | Since: base-2.1 |
| Enum Ordering | Since: base-2.1 |
| Generic Ordering | |
| Ix Ordering | Since: base-2.1 |
Defined in GHC.Ix Methods range :: (Ordering, Ordering) -> [Ordering] # index :: (Ordering, Ordering) -> Ordering -> Int # unsafeIndex :: (Ordering, Ordering) -> Ordering -> Int # inRange :: (Ordering, Ordering) -> Ordering -> Bool # rangeSize :: (Ordering, Ordering) -> Int # unsafeRangeSize :: (Ordering, Ordering) -> Int # | |
| Read Ordering | Since: base-2.1 |
| Show Ordering | Since: base-2.1 |
| Default Ordering | |
Defined in Data.Default.Class | |
| Eq Ordering | |
| Ord Ordering | |
Defined in GHC.Classes | |
| Hashable Ordering | |
Defined in Data.Hashable.Class | |
| type Rep Ordering | Since: base-4.6.0.0 |
A value of type is a computation which, when performed,
does some I/O before returning a value of type IO aa.
There is really only one way to "perform" an I/O action: bind it to
Main.main in your program. When your program is run, the I/O will
be performed. It isn't possible to perform I/O from an arbitrary
function, unless that function is itself in the IO monad and called
at some point, directly or indirectly, from Main.main.
IO is a monad, so IO actions can be combined using either the do-notation
or the >> and >>= operations from the Monad
class.
Instances
The Either type represents values with two possibilities: a value of
type is either Either a b or Left a.Right b
The Either type is sometimes used to represent a value which is
either correct or an error; by convention, the Left constructor is
used to hold an error value and the Right constructor is used to
hold a correct value (mnemonic: "right" also means "correct").
Examples
The type is the type of values which can be either
a Either String IntString or an Int. The Left constructor can be used only on
Strings, and the Right constructor can be used only on Ints:
>>>let s = Left "foo" :: Either String Int>>>sLeft "foo">>>let n = Right 3 :: Either String Int>>>nRight 3>>>:type ss :: Either String Int>>>:type nn :: 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) sLeft "foo">>>fmap (*2) nRight 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)>>>:}
>>>parseMultipleRight 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)>>>:}
>>>parseMultipleLeft "parse error"
Instances
| FromJSON2 Either | |
Defined in Data.Aeson.Types.FromJSON Methods liftParseJSON2 :: Maybe a -> (Value -> Parser a) -> (Value -> Parser [a]) -> Maybe b -> (Value -> Parser b) -> (Value -> Parser [b]) -> Value -> Parser (Either a b) # liftParseJSONList2 :: Maybe a -> (Value -> Parser a) -> (Value -> Parser [a]) -> Maybe b -> (Value -> Parser b) -> (Value -> Parser [b]) -> Value -> Parser [Either a b] # liftOmittedField2 :: Maybe a -> Maybe b -> Maybe (Either a b) # | |
| ToJSON2 Either | |
Defined in Data.Aeson.Types.ToJSON Methods liftToJSON2 :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> (b -> Bool) -> (b -> Value) -> ([b] -> Value) -> Either a b -> Value # liftToJSONList2 :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> (b -> Bool) -> (b -> Value) -> ([b] -> Value) -> [Either a b] -> Value # liftToEncoding2 :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> (b -> Bool) -> (b -> Encoding) -> ([b] -> Encoding) -> Either a b -> Encoding # liftToEncodingList2 :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> (b -> Bool) -> (b -> Encoding) -> ([b] -> Encoding) -> [Either a b] -> Encoding # liftOmitField2 :: (a -> Bool) -> (b -> Bool) -> Either a b -> Bool # | |
| Bifunctor Either | Since: base-4.8.0.0 |
| Eq2 Either | Since: base-4.9.0.0 |
| Ord2 Either | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
| Read2 Either | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes Methods liftReadsPrec2 :: (Int -> ReadS a) -> ReadS [a] -> (Int -> ReadS b) -> ReadS [b] -> Int -> ReadS (Either a b) # liftReadList2 :: (Int -> ReadS a) -> ReadS [a] -> (Int -> ReadS b) -> ReadS [b] -> ReadS [Either a b] # liftReadPrec2 :: ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec (Either a b) # liftReadListPrec2 :: ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec [Either a b] # | |
| Show2 Either | Since: base-4.9.0.0 |
| Hashable2 Either | |
Defined in Data.Hashable.Class | |
| Generic1 (Either a :: Type -> Type) | |
| (Lift a, Lift b) => Lift (Either a b :: Type) | |
| FromJSON a => FromJSON1 (Either a) | |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON a => ToJSON1 (Either a) | |
Defined in Data.Aeson.Types.ToJSON Methods liftToJSON :: (a0 -> Bool) -> (a0 -> Value) -> ([a0] -> Value) -> Either a a0 -> Value # liftToJSONList :: (a0 -> Bool) -> (a0 -> Value) -> ([a0] -> Value) -> [Either a a0] -> Value # liftToEncoding :: (a0 -> Bool) -> (a0 -> Encoding) -> ([a0] -> Encoding) -> Either a a0 -> Encoding # liftToEncodingList :: (a0 -> Bool) -> (a0 -> Encoding) -> ([a0] -> Encoding) -> [Either a a0] -> Encoding # liftOmitField :: (a0 -> Bool) -> Either a a0 -> Bool # | |
| Foldable (Either a) | Since: base-4.7.0.0 |
Defined in Data.Foldable Methods fold :: Monoid m => Either a m -> m # foldMap :: Monoid m => (a0 -> m) -> Either a a0 -> m # foldMap' :: Monoid m => (a0 -> m) -> Either a a0 -> m # foldr :: (a0 -> b -> b) -> b -> Either a a0 -> b # foldr' :: (a0 -> b -> b) -> b -> Either a a0 -> b # foldl :: (b -> a0 -> b) -> b -> Either a a0 -> b # foldl' :: (b -> a0 -> b) -> b -> Either a a0 -> b # foldr1 :: (a0 -> a0 -> a0) -> Either a a0 -> a0 # foldl1 :: (a0 -> a0 -> a0) -> Either a a0 -> a0 # toList :: Either a a0 -> [a0] # length :: Either a a0 -> Int # elem :: Eq a0 => a0 -> Either a a0 -> Bool # maximum :: Ord a0 => Either a a0 -> a0 # minimum :: Ord a0 => Either a a0 -> a0 # | |
| Eq a => Eq1 (Either a) | Since: base-4.9.0.0 |
| Ord a => Ord1 (Either a) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
| Read a => Read1 (Either a) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes Methods liftReadsPrec :: (Int -> ReadS a0) -> ReadS [a0] -> Int -> ReadS (Either a a0) # liftReadList :: (Int -> ReadS a0) -> ReadS [a0] -> ReadS [Either a a0] # liftReadPrec :: ReadPrec a0 -> ReadPrec [a0] -> ReadPrec (Either a a0) # liftReadListPrec :: ReadPrec a0 -> ReadPrec [a0] -> ReadPrec [Either a a0] # | |
| Show a => Show1 (Either a) | Since: base-4.9.0.0 |
| Traversable (Either a) | Since: base-4.7.0.0 |
Defined in Data.Traversable | |
| Applicative (Either e) | Since: base-3.0 |
| Functor (Either a) | Since: base-3.0 |
| Monad (Either e) | Since: base-4.4.0.0 |
| e ~ SomeException => MonadCatch (Either e) | Since: exceptions-0.8.3 |
| e ~ SomeException => MonadMask (Either e) | Since: exceptions-0.8.3 |
Defined in Control.Monad.Catch | |
| e ~ SomeException => MonadThrow (Either e) | |
Defined in Control.Monad.Catch | |
| Hashable a => Hashable1 (Either a) | |
Defined in Data.Hashable.Class | |
| e ~ a => Reportable (Either a) e | |
Defined in Hledger.Reports.ReportOptions | |
| (FromJSON a, FromJSON b) => FromJSON (Either a b) | |
Defined in Data.Aeson.Types.FromJSON | |
| (ToJSON a, ToJSON b) => ToJSON (Either a b) | |
| (Data a, Data b) => Data (Either a b) | Since: base-4.0.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b0. Data d => c (d -> b0) -> d -> c b0) -> (forall g. g -> c g) -> Either a b -> c (Either a b) # gunfold :: (forall b0 r. Data b0 => c (b0 -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Either a b) # toConstr :: Either a b -> Constr # dataTypeOf :: Either a b -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Either a b)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Either a b)) # gmapT :: (forall b0. Data b0 => b0 -> b0) -> Either a b -> Either a b # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Either a b -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Either a b -> r # gmapQ :: (forall d. Data d => d -> u) -> Either a b -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Either a b -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Either a b -> m (Either a b) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Either a b -> m (Either a b) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Either a b -> m (Either a b) # | |
| Semigroup (Either a b) | Since: base-4.9.0.0 |
| Generic (Either a b) | |
| (Read a, Read b) => Read (Either a b) | Since: base-3.0 |
| (Show a, Show b) => Show (Either a b) | Since: base-3.0 |
| (Eq a, Eq b) => Eq (Either a b) | Since: base-2.1 |
| (Ord a, Ord b) => Ord (Either a b) | Since: base-2.1 |
| (Hashable a, Hashable b) => Hashable (Either a b) | |
Defined in Data.Hashable.Class | |
| MonoFoldable (Either a b) | |
Defined in Data.MonoTraversable Methods ofoldMap :: Monoid m => (Element (Either a b) -> m) -> Either a b -> m # ofoldr :: (Element (Either a b) -> b0 -> b0) -> b0 -> Either a b -> b0 # ofoldl' :: (a0 -> Element (Either a b) -> a0) -> a0 -> Either a b -> a0 # otoList :: Either a b -> [Element (Either a b)] # oall :: (Element (Either a b) -> Bool) -> Either a b -> Bool # oany :: (Element (Either a b) -> Bool) -> Either a b -> Bool # olength :: Either a b -> Int # olength64 :: Either a b -> Int64 # ocompareLength :: Integral i => Either a b -> i -> Ordering # otraverse_ :: Applicative f => (Element (Either a b) -> f b0) -> Either a b -> f () # ofor_ :: Applicative f => Either a b -> (Element (Either a b) -> f b0) -> f () # omapM_ :: Applicative m => (Element (Either a b) -> m ()) -> Either a b -> m () # oforM_ :: Applicative m => Either a b -> (Element (Either a b) -> m ()) -> m () # ofoldlM :: Monad m => (a0 -> Element (Either a b) -> m a0) -> a0 -> Either a b -> m a0 # ofoldMap1Ex :: Semigroup m => (Element (Either a b) -> m) -> Either a b -> m # ofoldr1Ex :: (Element (Either a b) -> Element (Either a b) -> Element (Either a b)) -> Either a b -> Element (Either a b) # ofoldl1Ex' :: (Element (Either a b) -> Element (Either a b) -> Element (Either a b)) -> Either a b -> Element (Either a b) # headEx :: Either a b -> Element (Either a b) # lastEx :: Either a b -> Element (Either a b) # unsafeHead :: Either a b -> Element (Either a b) # unsafeLast :: Either a b -> Element (Either a b) # maximumByEx :: (Element (Either a b) -> Element (Either a b) -> Ordering) -> Either a b -> Element (Either a b) # minimumByEx :: (Element (Either a b) -> Element (Either a b) -> Ordering) -> Either a b -> Element (Either a b) # | |
| MonoFunctor (Either a b) | |
| MonoPointed (Either a b) | |
| MonoTraversable (Either a b) | |
| (a ~ a', b ~ b') => Each (Either a a') (Either b b') a b | Since: microlens-0.4.11 |
| type Rep1 (Either a :: Type -> Type) | Since: base-4.6.0.0 |
Defined in GHC.Generics type Rep1 (Either a :: Type -> Type) = D1 ('MetaData "Either" "Data.Either" "base" 'False) (C1 ('MetaCons "Left" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 a)) :+: C1 ('MetaCons "Right" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) Par1)) | |
| type Rep (Either a b) | Since: base-4.6.0.0 |
Defined in GHC.Generics type Rep (Either a b) = D1 ('MetaData "Either" "Data.Either" "base" 'False) (C1 ('MetaCons "Left" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 a)) :+: C1 ('MetaCons "Right" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 b))) | |
| type Element (Either a b) | |
Defined in Data.MonoTraversable | |
getCurrentDirectory :: IO FilePath #
Obtain the current working directory as an absolute path.
In a multithreaded program, the current working directory is a global state
shared among all threads of the process. Therefore, when performing
filesystem operations from multiple threads, it is highly recommended to
use absolute rather than relative paths (see: makeAbsolute).
Note that getCurrentDirectory is not guaranteed to return the same path
received by setCurrentDirectory. On POSIX systems, the path returned will
always be fully dereferenced (not contain any symbolic links). For more
information, refer to the documentation of
getcwd.
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]isDoesNotExistErrorThere is no path referring to the working directory.[EPERM, ENOENT, ESTALE...]isPermissionErrorThe process has insufficient privileges to perform the operation.[EACCES]isFullErrorInsufficient resources are available to perform the operation.UnsupportedOperationThe operating system has no notion of current working directory.
File and directory names are values of type String, whose precise
meaning is operating system dependent. Files can be opened, yielding a
handle which can then be used to operate on the contents of that file.
span :: (a -> Bool) -> [a] -> ([a], [a]) #
span, applied to a predicate p and a list xs, returns a tuple where
first element is longest prefix (possibly empty) of xs of elements that
satisfy p and second element is the remainder of the list:
>>>span (< 3) [1,2,3,4,1,2,3,4]([1,2],[3,4,1,2,3,4])>>>span (< 9) [1,2,3]([1,2,3],[])>>>span (< 0) [1,2,3]([],[1,2,3])
(<$>) :: Functor f => (a -> b) -> f a -> f b infixl 4 #
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.
Examples
Convert from a to a Maybe Int using Maybe
Stringshow:
>>>show <$> NothingNothing>>>show <$> Just 3Just "3"
Convert from an to an
Either Int IntEither IntString using show:
>>>show <$> Left 17Left 17>>>show <$> Right 17Right "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)
Convert a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged.
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.
Constructors
| UTCTime | |
Fields
| |
Instances
| FromJSON UTCTime | |
Defined in Data.Aeson.Types.FromJSON | |
| FromJSONKey UTCTime | |
Defined in Data.Aeson.Types.FromJSON Methods | |
| ToJSON UTCTime | |
| ToJSONKey UTCTime | |
Defined in Data.Aeson.Types.ToJSON | |
| Data UTCTime | |
Defined in Data.Time.Clock.Internal.UTCTime Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> UTCTime -> c UTCTime # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c UTCTime # toConstr :: UTCTime -> Constr # dataTypeOf :: UTCTime -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c UTCTime) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c UTCTime) # gmapT :: (forall b. Data b => b -> b) -> UTCTime -> UTCTime # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> UTCTime -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> UTCTime -> r # gmapQ :: (forall d. Data d => d -> u) -> UTCTime -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> UTCTime -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> UTCTime -> m UTCTime # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> UTCTime -> m UTCTime # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> UTCTime -> m UTCTime # | |
| NFData UTCTime | |
Defined in Data.Time.Clock.Internal.UTCTime | |
| Eq UTCTime | |
| Ord UTCTime | |
Defined in Data.Time.Clock.Internal.UTCTime | |
A space efficient, packed, unboxed Unicode text type.
Instances
liftM2 :: Monad m => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r #
Promote a function to a monad, scanning the monadic arguments from left to right. For example,
liftM2 (+) [0,1] [0,2] = [0,2,1,3] liftM2 (+) (Just 1) Nothing = Nothing
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.
class Applicative f => Alternative (f :: Type -> Type) where #
A monoid on applicative functors.
If defined, some and many should be the least solutions
of the equations:
Methods
The identity of <|>
(<|>) :: f a -> f a -> f a infixl 3 #
An associative binary operation
One or more.
Zero or more.
Instances
($>) :: Functor f => f a -> b -> f b infixl 4 #
Flipped version of <$.
Examples
Replace the contents of a with a constant
Maybe IntString:
>>>Nothing $> "foo"Nothing>>>Just 90210 $> "foo"Just "foo"
Replace the contents of an
with a constant Either Int IntString, resulting in an :Either
Int String
>>>Left 8675309 $> "foo"Left 8675309>>>Right 8675309 $> "foo"Right "foo"
Replace each element of a list with a constant String:
>>>[1,2,3] $> "foo"["foo","foo","foo"]
Replace the second element of a pair with a constant String:
>>>(1,2) $> "foo"(1,"foo")
Since: base-4.7.0.0
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
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]
fromMaybe :: a -> Maybe a -> a #
The fromMaybe function takes a default value and a Maybe
value. If the Maybe is Nothing, it returns the default value;
otherwise, it returns the value contained in the Maybe.
Examples
Basic usage:
>>>fromMaybe "" (Just "Hello, World!")"Hello, World!"
>>>fromMaybe "" Nothing""
Read an integer from a string using readMaybe. If we fail to
parse an integer, we want to return 0 by default:
>>>import Text.Read ( readMaybe )>>>fromMaybe 0 (readMaybe "5")5>>>fromMaybe 0 (readMaybe "")0
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]
The Const functor.
Instances
| Generic1 (Const a :: k -> Type) | |
| Unbox a => Vector Vector (Const a b) | |
Defined in Data.Vector.Unboxed.Base Methods basicUnsafeFreeze :: Mutable Vector s (Const a b) -> ST s (Vector (Const a b)) # basicUnsafeThaw :: Vector (Const a b) -> ST s (Mutable Vector s (Const a b)) # basicLength :: Vector (Const a b) -> Int # basicUnsafeSlice :: Int -> Int -> Vector (Const a b) -> Vector (Const a b) # basicUnsafeIndexM :: Vector (Const a b) -> Int -> Box (Const a b) # basicUnsafeCopy :: Mutable Vector s (Const a b) -> Vector (Const a b) -> ST s () # | |
| Unbox a => MVector MVector (Const a b) | |
Defined in Data.Vector.Unboxed.Base Methods basicLength :: MVector s (Const a b) -> Int # basicUnsafeSlice :: Int -> Int -> MVector s (Const a b) -> MVector s (Const a b) # basicOverlaps :: MVector s (Const a b) -> MVector s (Const a b) -> Bool # basicUnsafeNew :: Int -> ST s (MVector s (Const a b)) # basicInitialize :: MVector s (Const a b) -> ST s () # basicUnsafeReplicate :: Int -> Const a b -> ST s (MVector s (Const a b)) # basicUnsafeRead :: MVector s (Const a b) -> Int -> ST s (Const a b) # basicUnsafeWrite :: MVector s (Const a b) -> Int -> Const a b -> ST s () # basicClear :: MVector s (Const a b) -> ST s () # basicSet :: MVector s (Const a b) -> Const a b -> ST s () # basicUnsafeCopy :: MVector s (Const a b) -> MVector s (Const a b) -> ST s () # basicUnsafeMove :: MVector s (Const a b) -> MVector s (Const a b) -> ST s () # basicUnsafeGrow :: MVector s (Const a b) -> Int -> ST s (MVector s (Const a b)) # | |
| FromJSON2 (Const :: Type -> Type -> Type) | |
Defined in Data.Aeson.Types.FromJSON Methods liftParseJSON2 :: Maybe a -> (Value -> Parser a) -> (Value -> Parser [a]) -> Maybe b -> (Value -> Parser b) -> (Value -> Parser [b]) -> Value -> Parser (Const a b) # liftParseJSONList2 :: Maybe a -> (Value -> Parser a) -> (Value -> Parser [a]) -> Maybe b -> (Value -> Parser b) -> (Value -> Parser [b]) -> Value -> Parser [Const a b] # liftOmittedField2 :: Maybe a -> Maybe b -> Maybe (Const a b) # | |
| ToJSON2 (Const :: Type -> TYPE LiftedRep -> Type) | |
Defined in Data.Aeson.Types.ToJSON Methods liftToJSON2 :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> (b -> Bool) -> (b -> Value) -> ([b] -> Value) -> Const a b -> Value # liftToJSONList2 :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> (b -> Bool) -> (b -> Value) -> ([b] -> Value) -> [Const a b] -> Value # liftToEncoding2 :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> (b -> Bool) -> (b -> Encoding) -> ([b] -> Encoding) -> Const a b -> Encoding # liftToEncodingList2 :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> (b -> Bool) -> (b -> Encoding) -> ([b] -> Encoding) -> [Const a b] -> Encoding # liftOmitField2 :: (a -> Bool) -> (b -> Bool) -> Const a b -> Bool # | |
| Bifunctor (Const :: Type -> Type -> Type) | Since: base-4.8.0.0 |
| Eq2 (Const :: Type -> Type -> Type) | Since: base-4.9.0.0 |
| Ord2 (Const :: Type -> Type -> Type) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
| Read2 (Const :: Type -> Type -> Type) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes Methods liftReadsPrec2 :: (Int -> ReadS a) -> ReadS [a] -> (Int -> ReadS b) -> ReadS [b] -> Int -> ReadS (Const a b) # liftReadList2 :: (Int -> ReadS a) -> ReadS [a] -> (Int -> ReadS b) -> ReadS [b] -> ReadS [Const a b] # liftReadPrec2 :: ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec (Const a b) # liftReadListPrec2 :: ReadPrec a -> ReadPrec [a] -> ReadPrec b -> ReadPrec [b] -> ReadPrec [Const a b] # | |
| Show2 (Const :: Type -> TYPE LiftedRep -> Type) | Since: base-4.9.0.0 |
| Hashable2 (Const :: Type -> Type -> Type) | |
Defined in Data.Hashable.Class | |
| FromJSON a => FromJSON1 (Const a :: Type -> Type) | |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON a => ToJSON1 (Const a :: TYPE LiftedRep -> Type) | |
Defined in Data.Aeson.Types.ToJSON Methods liftToJSON :: (a0 -> Bool) -> (a0 -> Value) -> ([a0] -> Value) -> Const a a0 -> Value # liftToJSONList :: (a0 -> Bool) -> (a0 -> Value) -> ([a0] -> Value) -> [Const a a0] -> Value # liftToEncoding :: (a0 -> Bool) -> (a0 -> Encoding) -> ([a0] -> Encoding) -> Const a a0 -> Encoding # liftToEncodingList :: (a0 -> Bool) -> (a0 -> Encoding) -> ([a0] -> Encoding) -> [Const a a0] -> Encoding # liftOmitField :: (a0 -> Bool) -> Const a a0 -> Bool # | |
| Foldable (Const m :: TYPE LiftedRep -> Type) | Since: base-4.7.0.0 |
Defined in Data.Functor.Const Methods fold :: Monoid m0 => Const m m0 -> m0 # foldMap :: Monoid m0 => (a -> m0) -> Const m a -> m0 # foldMap' :: Monoid m0 => (a -> m0) -> Const m a -> m0 # foldr :: (a -> b -> b) -> b -> Const m a -> b # foldr' :: (a -> b -> b) -> b -> Const m a -> b # foldl :: (b -> a -> b) -> b -> Const m a -> b # foldl' :: (b -> a -> b) -> b -> Const m a -> b # foldr1 :: (a -> a -> a) -> Const m a -> a # foldl1 :: (a -> a -> a) -> Const m a -> a # elem :: Eq a => a -> Const m a -> Bool # maximum :: Ord a => Const m a -> a # minimum :: Ord a => Const m a -> a # | |
| Eq a => Eq1 (Const a :: Type -> Type) | Since: base-4.9.0.0 |
| Ord a => Ord1 (Const a :: Type -> Type) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes | |
| Read a => Read1 (Const a :: Type -> Type) | Since: base-4.9.0.0 |
Defined in Data.Functor.Classes Methods liftReadsPrec :: (Int -> ReadS a0) -> ReadS [a0] -> Int -> ReadS (Const a a0) # liftReadList :: (Int -> ReadS a0) -> ReadS [a0] -> ReadS [Const a a0] # liftReadPrec :: ReadPrec a0 -> ReadPrec [a0] -> ReadPrec (Const a a0) # liftReadListPrec :: ReadPrec a0 -> ReadPrec [a0] -> ReadPrec [Const a a0] # | |
| Show a => Show1 (Const a :: TYPE LiftedRep -> Type) | Since: base-4.9.0.0 |
| Traversable (Const m :: Type -> Type) | Since: base-4.7.0.0 |
| Monoid m => Applicative (Const m :: Type -> Type) | Since: base-2.0.1 |
| Functor (Const m :: Type -> Type) | Since: base-2.1 |
| Hashable a => Hashable1 (Const a :: Type -> Type) | |
Defined in Data.Hashable.Class | |
| Reportable (Const r :: Type -> Type) e | |
Defined in Hledger.Reports.ReportOptions | |
| FromJSON a => FromJSON (Const a b) | |
Defined in Data.Aeson.Types.FromJSON | |
| (FromJSON a, FromJSONKey a) => FromJSONKey (Const a b) | |
Defined in Data.Aeson.Types.FromJSON Methods fromJSONKey :: FromJSONKeyFunction (Const a b) # fromJSONKeyList :: FromJSONKeyFunction [Const a b] # | |
| ToJSON a => ToJSON (Const a b) | |
| (ToJSON a, ToJSONKey a) => ToJSONKey (Const a b) | |
Defined in Data.Aeson.Types.ToJSON | |
| (Typeable k, Data a, Typeable b) => Data (Const a b) | Since: base-4.10.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b0. Data d => c (d -> b0) -> d -> c b0) -> (forall g. g -> c g) -> Const a b -> c (Const a b) # gunfold :: (forall b0 r. Data b0 => c (b0 -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Const a b) # toConstr :: Const a b -> Constr # dataTypeOf :: Const a b -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Const a b)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Const a b)) # gmapT :: (forall b0. Data b0 => b0 -> b0) -> Const a b -> Const a b # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Const a b -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Const a b -> r # gmapQ :: (forall d. Data d => d -> u) -> Const a b -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Const a b -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Const a b -> m (Const a b) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Const a b -> m (Const a b) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Const a b -> m (Const a b) # | |
| IsString a => IsString (Const a b) | Since: base-4.9.0.0 |
Defined in Data.String Methods fromString :: String -> Const a b # | |
| Storable a => Storable (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const | |
| Monoid a => Monoid (Const a b) | Since: base-4.9.0.0 |
| Semigroup a => Semigroup (Const a b) | Since: base-4.9.0.0 |
| Bits a => Bits (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods (.&.) :: Const a b -> Const a b -> Const a b # (.|.) :: Const a b -> Const a b -> Const a b # xor :: Const a b -> Const a b -> Const a b # complement :: Const a b -> Const a b # shift :: Const a b -> Int -> Const a b # rotate :: Const a b -> Int -> Const a b # setBit :: Const a b -> Int -> Const a b # clearBit :: Const a b -> Int -> Const a b # complementBit :: Const a b -> Int -> Const a b # testBit :: Const a b -> Int -> Bool # bitSizeMaybe :: Const a b -> Maybe Int # isSigned :: Const a b -> Bool # shiftL :: Const a b -> Int -> Const a b # unsafeShiftL :: Const a b -> Int -> Const a b # shiftR :: Const a b -> Int -> Const a b # unsafeShiftR :: Const a b -> Int -> Const a b # rotateL :: Const a b -> Int -> Const a b # | |
| FiniteBits a => FiniteBits (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods finiteBitSize :: Const a b -> Int # countLeadingZeros :: Const a b -> Int # countTrailingZeros :: Const a b -> Int # | |
| Bounded a => Bounded (Const a b) | Since: base-4.9.0.0 |
| Enum a => Enum (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods succ :: Const a b -> Const a b # pred :: Const a b -> Const a b # fromEnum :: Const a b -> Int # enumFrom :: Const a b -> [Const a b] # enumFromThen :: Const a b -> Const a b -> [Const a b] # enumFromTo :: Const a b -> Const a b -> [Const a b] # enumFromThenTo :: Const a b -> Const a b -> Const a b -> [Const a b] # | |
| Floating a => Floating (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods exp :: Const a b -> Const a b # log :: Const a b -> Const a b # sqrt :: Const a b -> Const a b # (**) :: Const a b -> Const a b -> Const a b # logBase :: Const a b -> Const a b -> Const a b # sin :: Const a b -> Const a b # cos :: Const a b -> Const a b # tan :: Const a b -> Const a b # asin :: Const a b -> Const a b # acos :: Const a b -> Const a b # atan :: Const a b -> Const a b # sinh :: Const a b -> Const a b # cosh :: Const a b -> Const a b # tanh :: Const a b -> Const a b # asinh :: Const a b -> Const a b # acosh :: Const a b -> Const a b # atanh :: Const a b -> Const a b # log1p :: Const a b -> Const a b # expm1 :: Const a b -> Const a b # | |
| RealFloat a => RealFloat (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods floatRadix :: Const a b -> Integer # floatDigits :: Const a b -> Int # floatRange :: Const a b -> (Int, Int) # decodeFloat :: Const a b -> (Integer, Int) # encodeFloat :: Integer -> Int -> Const a b # exponent :: Const a b -> Int # significand :: Const a b -> Const a b # scaleFloat :: Int -> Const a b -> Const a b # isInfinite :: Const a b -> Bool # isDenormalized :: Const a b -> Bool # isNegativeZero :: Const a b -> Bool # | |
| Generic (Const a b) | |
| Ix a => Ix (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods range :: (Const a b, Const a b) -> [Const a b] # index :: (Const a b, Const a b) -> Const a b -> Int # unsafeIndex :: (Const a b, Const a b) -> Const a b -> Int # inRange :: (Const a b, Const a b) -> Const a b -> Bool # rangeSize :: (Const a b, Const a b) -> Int # unsafeRangeSize :: (Const a b, Const a b) -> Int # | |
| Num a => Num (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const | |
| Read a => Read (Const a b) | This instance would be equivalent to the derived instances of the
Since: base-4.8.0.0 |
| Fractional a => Fractional (Const a b) | Since: base-4.9.0.0 |
| Integral a => Integral (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods quot :: Const a b -> Const a b -> Const a b # rem :: Const a b -> Const a b -> Const a b # div :: Const a b -> Const a b -> Const a b # mod :: Const a b -> Const a b -> Const a b # quotRem :: Const a b -> Const a b -> (Const a b, Const a b) # divMod :: Const a b -> Const a b -> (Const a b, Const a b) # | |
| Real a => Real (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const Methods toRational :: Const a b -> Rational # | |
| RealFrac a => RealFrac (Const a b) | Since: base-4.9.0.0 |
| Show a => Show (Const a b) | This instance would be equivalent to the derived instances of the
Since: base-4.8.0.0 |
| Eq a => Eq (Const a b) | Since: base-4.9.0.0 |
| Ord a => Ord (Const a b) | Since: base-4.9.0.0 |
| Hashable a => Hashable (Const a b) | |
Defined in Data.Hashable.Class | |
| MonoFoldable (Const m a) | |
Defined in Data.MonoTraversable Methods ofoldMap :: Monoid m0 => (Element (Const m a) -> m0) -> Const m a -> m0 # ofoldr :: (Element (Const m a) -> b -> b) -> b -> Const m a -> b # ofoldl' :: (a0 -> Element (Const m a) -> a0) -> a0 -> Const m a -> a0 # otoList :: Const m a -> [Element (Const m a)] # oall :: (Element (Const m a) -> Bool) -> Const m a -> Bool # oany :: (Element (Const m a) -> Bool) -> Const m a -> Bool # olength64 :: Const m a -> Int64 # ocompareLength :: Integral i => Const m a -> i -> Ordering # otraverse_ :: Applicative f => (Element (Const m a) -> f b) -> Const m a -> f () # ofor_ :: Applicative f => Const m a -> (Element (Const m a) -> f b) -> f () # omapM_ :: Applicative m0 => (Element (Const m a) -> m0 ()) -> Const m a -> m0 () # oforM_ :: Applicative m0 => Const m a -> (Element (Const m a) -> m0 ()) -> m0 () # ofoldlM :: Monad m0 => (a0 -> Element (Const m a) -> m0 a0) -> a0 -> Const m a -> m0 a0 # ofoldMap1Ex :: Semigroup m0 => (Element (Const m a) -> m0) -> Const m a -> m0 # ofoldr1Ex :: (Element (Const m a) -> Element (Const m a) -> Element (Const m a)) -> Const m a -> Element (Const m a) # ofoldl1Ex' :: (Element (Const m a) -> Element (Const m a) -> Element (Const m a)) -> Const m a -> Element (Const m a) # headEx :: Const m a -> Element (Const m a) # lastEx :: Const m a -> Element (Const m a) # unsafeHead :: Const m a -> Element (Const m a) # unsafeLast :: Const m a -> Element (Const m a) # maximumByEx :: (Element (Const m a) -> Element (Const m a) -> Ordering) -> Const m a -> Element (Const m a) # minimumByEx :: (Element (Const m a) -> Element (Const m a) -> Ordering) -> Const m a -> Element (Const m a) # | |
| MonoFunctor (Const m a) | |
| Monoid m => MonoPointed (Const m a) | |
| MonoTraversable (Const m a) | |
| Pretty a => Pretty (Const a b) | |
Defined in Prettyprinter.Internal | |
| Prim a => Prim (Const a b) | Since: primitive-0.6.5.0 |
Defined in Data.Primitive.Types Methods sizeOfType# :: Proxy (Const a b) -> Int# # sizeOf# :: Const a b -> Int# # alignmentOfType# :: Proxy (Const a b) -> Int# # alignment# :: Const a b -> Int# # indexByteArray# :: ByteArray# -> Int# -> Const a b # readByteArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Const a b #) # writeByteArray# :: MutableByteArray# s -> Int# -> Const a b -> State# s -> State# s # setByteArray# :: MutableByteArray# s -> Int# -> Int# -> Const a b -> State# s -> State# s # indexOffAddr# :: Addr# -> Int# -> Const a b # readOffAddr# :: Addr# -> Int# -> State# s -> (# State# s, Const a b #) # writeOffAddr# :: Addr# -> Int# -> Const a b -> State# s -> State# s # setOffAddr# :: Addr# -> Int# -> Int# -> Const a b -> State# s -> State# s # | |
| Unbox a => Unbox (Const a b) | |
Defined in Data.Vector.Unboxed.Base | |
| type Rep1 (Const a :: k -> Type) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const | |
| newtype MVector s (Const a b) | |
Defined in Data.Vector.Unboxed.Base | |
| type Rep (Const a b) | Since: base-4.9.0.0 |
Defined in Data.Functor.Const | |
| type Element (Const m a) | |
Defined in Data.MonoTraversable | |
| newtype Vector (Const a b) | |
Defined in Data.Vector.Unboxed.Base | |
unless :: Applicative f => Bool -> f () -> f () #
The reverse of when.
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.
Instances
forkOnWithUnmask :: Int -> ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId #
Like forkIOWithUnmask, but the child thread is pinned to the
given CPU, as with forkOn.
Since: base-4.4.0.0
forkIOWithUnmask :: ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId #
Like forkIO, but the child thread is passed a function that can
be used to unmask asynchronous exceptions. This function is
typically used in the following way
... mask_ $ forkIOWithUnmask $ \unmask ->
catch (unmask ...) handlerso that the exception handler in the child thread is established with asynchronous exceptions masked, meanwhile the main body of the child thread is executed in the unmasked state.
Note that the unmask function passed to the child thread should only be used in that thread; the behaviour is undefined if it is invoked in a different thread.
Since: base-4.4.0.0
forkOn :: Int -> IO () -> IO ThreadId #
Like forkIO, but lets you specify on which capability the thread
should run. Unlike a forkIO thread, a thread created by forkOn
will stay on the same capability for its entire lifetime (forkIO
threads can migrate between capabilities according to the scheduling
policy). forkOn is useful for overriding the scheduling policy when
you know in advance how best to distribute the threads.
The Int argument specifies a capability number (see
getNumCapabilities). Typically capabilities correspond to physical
processors, but the exact behaviour is implementation-dependent. The
value passed to forkOn is interpreted modulo the total number of
capabilities as returned by getNumCapabilities.
GHC note: the number of capabilities is specified by the +RTS -N
option when the program is started. Capabilities can be fixed to
actual processor cores with +RTS -qa if the underlying operating
system supports that, although in practice this is usually unnecessary
(and may actually degrade performance in some cases - experimentation
is recommended).
Since: base-4.4.0.0
forkOS :: 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).
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.
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.
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.
Instances
| Show ThreadId | Since: base-4.2.0.0 |
| Eq ThreadId | Since: base-4.2.0.0 |
| Ord ThreadId | Since: base-4.2.0.0 |
Defined in GHC.Conc.Sync | |
| Hashable ThreadId | |
Defined in Data.Hashable.Class | |
Returns True for any Unicode space character, and the control
characters \t, \n, \r, \f, \v.
Selects alphabetic Unicode characters (lower-case, upper-case and
title-case letters, plus letters of caseless scripts and modifiers letters).
This function is equivalent to isLetter.
class (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where #
Monads that also support choice and failure.
Minimal complete definition
Nothing
Methods
The identity of mplus. It should also satisfy the equations
mzero >>= f = mzero v >> mzero = mzero
The default definition is
mzero = empty
An associative operation. The default definition is
mplus = (<|>)
Instances
| MonadPlus IResult | |
| MonadPlus Parser | |
| MonadPlus Result | |
| MonadPlus STM | Since: base-4.3.0.0 |
| MonadPlus P | Since: base-2.1 |
Defined in Text.ParserCombinators.ReadP | |
| MonadPlus ReadP | Since: base-2.1 |
| MonadPlus ReadPrec | Since: base-2.1 |
| MonadPlus Seq | |
| MonadPlus DList | |
| MonadPlus IO | Since: base-4.9.0.0 |
| MonadPlus Root | |
| MonadPlus Array | |
| MonadPlus SmallArray | |
Defined in Data.Primitive.SmallArray | |
| MonadPlus Capability | |
Defined in System.Console.Terminfo.Base | |
| MonadPlus Vector | |
| MonadPlus Maybe | Since: base-2.1 |
| MonadPlus [] | Since: base-2.1 |
| MonadPlus (Parser i) | |
| (ArrowApply a, ArrowPlus a) => MonadPlus (ArrowMonad a) | Since: base-4.6.0.0 |
Defined in Control.Arrow | |
| MonadPlus (Proxy :: Type -> Type) | Since: base-4.9.0.0 |
| MonadPlus (U1 :: Type -> Type) | Since: base-4.9.0.0 |
| MonadPlus m => MonadPlus (ResourceT m) | Since 1.1.5 |
| Monad m => MonadPlus (MaybeT m) | |
| Functor backend => MonadPlus (Wizard backend) | |
| MonadPlus m => MonadPlus (Kleisli m a) | Since: base-4.14.0.0 |
| MonadPlus f => MonadPlus (Ap f) | Since: base-4.12.0.0 |
| MonadPlus f => MonadPlus (Alt f) | Since: base-4.8.0.0 |
| MonadPlus f => MonadPlus (Rec1 f) | Since: base-4.9.0.0 |
| (Functor f, Monad m, MonadPlus m) => MonadPlus (FreeT f m) | |
| (Monad m, Error e) => MonadPlus (ErrorT e m) | |
| (Monad m, Monoid e) => MonadPlus (ExceptT e m) | |
| MonadPlus m => MonadPlus (ReaderT r m) | |
| MonadPlus m => MonadPlus (StateT s m) | |
| (MonadPlus f, MonadPlus g) => MonadPlus (f :*: g) | Since: base-4.9.0.0 |
| (Ord e, Stream s) => MonadPlus (ParsecT e s m) |
Note: strictly speaking, this instance is unlawful. The right identity law does not hold, e.g. in general this is not true: v >> mzero = mero However the following holds: try v >> mzero = mzero |
| MonadPlus f => MonadPlus (M1 i c f) | Since: base-4.9.0.0 |
threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) #
Returns an STM action that can be used to wait until data can be written to a file descriptor. The second returned value is an IO action that can be used to deregister interest in the file descriptor.
Since: base-4.7.0.0
threadWaitWrite :: Fd -> IO () #
Block the current thread until data can be written to the given file descriptor (GHC only).
This will throw an IOError if the file descriptor was closed
while this thread was blocked. To safely close a file descriptor
that has been used with threadWaitWrite, use
closeFdWith.
threadWaitReadSTM :: Fd -> IO (STM (), IO ()) #
Returns an STM action that can be used to wait for data to read from a file descriptor. The second returned value is an IO action that can be used to deregister interest in the file descriptor.
Since: base-4.7.0.0
threadWaitRead :: Fd -> IO () #
Block the current thread until data is available to read on the given file descriptor (GHC only).
This will throw an IOError if the file descriptor was closed
while this thread was blocked. To safely close a file descriptor
that has been used with threadWaitRead, use
closeFdWith.
runInUnboundThread :: IO a -> IO a #
Run the IO computation passed as the first argument. If the calling thread
is bound, an unbound thread is created temporarily using forkIO.
runInBoundThread doesn't finish until the IO computation finishes.
Use this function only in the rare case that you have actually observed a
performance loss due to the use of bound threads. A program that
doesn't need its main thread to be bound and makes heavy use of concurrency
(e.g. a web server), might want to wrap its main action in
runInUnboundThread.
Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread.
runInBoundThread :: IO a -> IO a #
Run the IO computation passed as the first argument. If the calling thread
is not bound, a bound thread is created temporarily. runInBoundThread
doesn't finish until the IO computation finishes.
You can wrap a series of foreign function calls that rely on thread-local state
with runInBoundThread so that you can use them without knowing whether the
current thread is bound.
rtsSupportsBoundThreads :: Bool #
True if bound threads are supported.
If rtsSupportsBoundThreads is False, isCurrentThreadBound
will always return False and both forkOS and runInBoundThread will
fail.
isCurrentThreadBound :: IO Bool #
Returns True if the calling thread is bound, that is, if it is
safe to use foreign libraries that rely on thread-local state from the
calling thread.
forkOSWithUnmask :: ((forall a. IO a -> IO a) -> IO ()) -> IO ThreadId #
Like forkIOWithUnmask, but the child thread is a bound thread,
as with forkOS.
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId #
Fork a thread and call the supplied function when the thread is about to terminate, with an exception or a returned value. The function is called with asynchronous exceptions masked.
forkFinally action and_then =
mask $ \restore ->
forkIO $ try (restore action) >>= and_thenThis function is useful for informing the parent when a child terminates, for example.
Since: base-4.6.0.0
Chan is an abstract type representing an unbounded FIFO channel.
writeList2Chan :: Chan a -> [a] -> IO () #
Write an entire list of items to a Chan.
Read the next value from the Chan. Blocks when the channel is empty. Since
the read end of a channel is an MVar, this operation inherits fairness
guarantees of MVars (e.g. threads blocked in this operation are woken up in
FIFO order).
Throws BlockedIndefinitelyOnMVar when the channel is
empty and no other thread holds a reference to the channel.
getChanContents :: Chan a -> IO [a] #
Return a lazy list representing the contents of the supplied
Chan, much like hGetContents.
dupChan :: Chan a -> IO (Chan a) #
Duplicate a Chan: the duplicate channel begins empty, but data written to
either channel from then on will be available from both. Hence this creates
a kind of broadcast channel, where data written by anyone is seen by
everyone else.
(Note that a duplicated channel is not equal to its original.
So: fmap (c /=) $ dupChan c returns True for all c.)
signalQSem :: QSem -> IO () #
Signal that a unit of the QSem is available
Build a new QSem with a supplied initial quantity.
The initial quantity must be at least 0.
Build a new QSemN with a supplied initial quantity.
The initial quantity must be at least 0.
withProgName :: String -> IO a -> IO a #
withProgName name act - while executing action act,
have getProgName return name.
unsetEnv name removes the specified environment variable from the
environment of the current process.
Throws IOException if name is the empty string or
contains an equals sign.
Since: base-4.7.0.0
setEnv :: String -> String -> IO () #
setEnv name value sets the specified environment variable to value.
Early versions of this function operated under the mistaken belief that setting an environment variable to the empty string on Windows removes that environment variable from the environment. For the sake of compatibility, it adopted that behavior on POSIX. In particular
setEnv name ""
has the same effect as
unsetEnv name
If you'd like to be able to set environment variables to blank strings,
use setEnv.
Throws IOException if name is the empty string or
contains an equals sign.
Since: base-4.7.0.0
lookupEnv :: String -> IO (Maybe String) #
Return the value of the environment variable var, or Nothing if
there is no such value.
For POSIX users, this is equivalent to getEnv.
Since: base-4.6.0.0
getProgName :: IO String #
Computation getProgName returns the name of the program as it was
invoked.
However, this is hard-to-impossible to implement on some non-Unix
OSes, so instead, for maximum portability, we just return the leafname
of the program as invoked. Even then there are some differences
between platforms: on Windows, for example, a program invoked as foo
is probably really FOO.EXE, and that is what getProgName will return.
getEnvironment :: IO [(String, String)] #
getEnvironment retrieves the entire environment as a
list of (key,value) pairs.
If an environment entry does not contain an '=' character,
the key is the whole entry and the value is the empty string.
getEnv :: String -> IO String #
Computation getEnv var returns the value
of the environment variable var. For the inverse, the
setEnv function can be used.
This computation may fail with:
isDoesNotExistErrorif the environment variable does not exist.
Computation getArgs returns a list of the program's command
line arguments (not including the program name).
getExecutablePath :: IO FilePath #
Returns the absolute pathname of the current executable.
Note that for scripts and interactive sessions, this is the path to the interpreter (e.g. ghci.)
Since base 4.11.0.0, getExecutablePath resolves symlinks on Windows.
If an executable is launched through a symlink, getExecutablePath
returns the absolute path of the original executable.
Since: base-4.6.0.0
exitWith :: ExitCode -> IO a #
Computation exitWith code throws ExitCode code.
Normally this terminates the program, returning code to the
program's caller.
On program termination, the standard Handles stdout and
stderr are flushed automatically; any other buffered Handles
need to be flushed manually, otherwise the buffered data will be
discarded.
A program that fails in any other way is treated as if it had
called exitFailure.
A program that terminates successfully without calling exitWith
explicitly is treated as if it had called exitWith ExitSuccess.
As an ExitCode is not an IOException, exitWith bypasses
the error handling in the IO monad and cannot be intercepted by
catch from the Prelude. However it is a SomeException, and can
be caught using the functions of Control.Exception. This means
that cleanup computations added with bracket
(from Control.Exception) are also executed properly on exitWith.
Note: in GHC, exitWith should be called from the main program
thread in order to exit the process. When called from another
thread, exitWith will throw an ExitException as normal, but the
exception will not cause the process itself to exit.
exitSuccess :: IO a #
The computation exitSuccess is equivalent to
exitWith ExitSuccess, It terminates the program
successfully.
exitFailure :: IO a #
The computation exitFailure is equivalent to
exitWith (ExitFailure exitfail),
where exitfail is implementation-dependent.
Write given error message to stderr and terminate with exitFailure.
Since: base-4.8.0.0
class PrintfType t #
The PrintfType class provides the variable argument magic for
printf. Its implementation is intentionally not visible from
this module. If you attempt to pass an argument of a type which
is not an instance of this class to printf or hPrintf, then
the compiler will report it as a missing instance of PrintfArg.
Minimal complete definition
spr
Instances
| a ~ () => PrintfType (IO a) | Since: base-4.7.0.0 |
Defined in Text.Printf | |
| IsChar c => PrintfType [c] | Since: base-2.1 |
Defined in Text.Printf | |
| (PrintfArg a, PrintfType r) => PrintfType (a -> r) | Since: base-2.1 |
Defined in Text.Printf | |
Typeclass of printf-formattable values. The formatArg method
takes a value and a field format descriptor and either fails due
to a bad descriptor or produces a ShowS as the result. The
default parseFormat expects no modifiers: this is the normal
case. Minimal instance: formatArg.
Minimal complete definition
Methods
formatArg :: a -> FieldFormatter #
Since: base-4.7.0.0
parseFormat :: a -> ModifierParser #
Since: base-4.7.0.0
Instances
| PrintfArg Int16 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Int32 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Int64 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Int8 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Word16 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Word32 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Word64 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Word8 | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg ShortText | Since: text-short-0.1.2 |
Defined in Data.Text.Short.Internal | |
| PrintfArg Integer | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Natural | Since: base-4.8.0.0 |
Defined in Text.Printf | |
| PrintfArg Char | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Double | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Float | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Int | Since: base-2.1 |
Defined in Text.Printf | |
| PrintfArg Word | Since: base-2.1 |
Defined in Text.Printf | |
| IsChar c => PrintfArg [c] | Since: base-2.1 |
Defined in Text.Printf | |
type ModifierParser = String -> FormatParse #
Type of a function that will parse modifier characters from the format string.
Since: base-4.7.0.0
class HPrintfType t #
The HPrintfType class provides the variable argument magic for
hPrintf. Its implementation is intentionally not visible from
this module.
Minimal complete definition
hspr
Instances
| a ~ () => HPrintfType (IO a) | Since: base-4.7.0.0 |
Defined in Text.Printf | |
| (PrintfArg a, HPrintfType r) => HPrintfType (a -> r) | Since: base-2.1 |
Defined in Text.Printf | |
data FormatSign #
How to handle the sign of a numeric field. These are
mutually exclusive, with SignPlus taking precedence.
Since: base-4.7.0.0
data FormatParse #
The "format parser" walks over argument-type-specific modifier characters to find the primary format character. This is the type of its result.
Since: base-4.7.0.0
Constructors
| FormatParse | |
data FormatAdjustment #
Whether to left-adjust or zero-pad a field. These are
mutually exclusive, with LeftAdjust taking precedence.
Since: base-4.7.0.0
Constructors
| LeftAdjust | |
| ZeroPad |
type FieldFormatter = FieldFormat -> ShowS #
This is the type of a field formatter reified over its argument.
Since: base-4.7.0.0
data FieldFormat #
Description of field formatting for formatArg. See UNIX printf(3)
for a description of how field formatting works.
Since: base-4.7.0.0
Constructors
| FieldFormat | |
Fields
| |
vFmt :: Char -> FieldFormat -> FieldFormat #
Substitute a 'v' format character with the given
default format character in the FieldFormat. A
convenience for user-implemented types, which should
support "%v".
Since: base-4.7.0.0
printf :: PrintfType r => String -> r #
Format a variable number of arguments with the C-style formatting string.
>>>printf "%s, %d, %.4f" "hello" 123 pihello, 123, 3.1416
The return value is either String or ( (which
should be IO a)(, but Haskell's type system
makes this hard).IO ())
The format string consists of ordinary characters and
conversion specifications, which specify how to format
one of the arguments to printf in the output string. A
format specification is introduced by the % character;
this character can be self-escaped into the format string
using %%. A format specification ends with a
format character that provides the primary information about
how to format the value. The rest of the conversion
specification is optional. In order, one may have flag
characters, a width specifier, a precision specifier, and
type-specific modifier characters.
Unlike C printf(3), the formatting of this printf
is driven by the argument type; formatting is type specific. The
types formatted by printf "out of the box" are:
printf is also extensible to support other types: see below.
A conversion specification begins with the
character %, followed by zero or more of the following flags:
- left adjust (default is right adjust) + always use a sign (+ or -) for signed conversions space leading space for positive numbers in signed conversions 0 pad with zeros rather than spaces # use an \"alternate form\": see below
When both flags are given, - overrides 0 and + overrides space.
A negative width specifier in a * conversion is treated as
positive but implies the left adjust flag.
The "alternate form" for unsigned radix conversions is
as in C printf(3):
%o prefix with a leading 0 if needed %x prefix with a leading 0x if nonzero %X prefix with a leading 0X if nonzero %b prefix with a leading 0b if nonzero %[eEfFgG] ensure that the number contains a decimal point
Any flags are followed optionally by a field width:
num field width * as num, but taken from argument list
The field width is a minimum, not a maximum: it will be expanded as needed to avoid mutilating a value.
Any field width is followed optionally by a precision:
.num precision . same as .0 .* as num, but taken from argument list
Negative precision is taken as 0. The meaning of the precision depends on the conversion type.
Integral minimum number of digits to show RealFloat number of digits after the decimal point String maximum number of characters
The precision for Integral types is accomplished by zero-padding. If both precision and zero-pad are given for an Integral field, the zero-pad is ignored.
Any precision is followed optionally for Integral types by a width modifier; the only use of this modifier being to set the implicit size of the operand for conversion of a negative operand to unsigned:
hh Int8 h Int16 l Int32 ll Int64 L Int64
The specification ends with a format character:
c character Integral d decimal Integral o octal Integral x hexadecimal Integral X hexadecimal Integral b binary Integral u unsigned decimal Integral f floating point RealFloat F floating point RealFloat g general format float RealFloat G general format float RealFloat e exponent format float RealFloat E exponent format float RealFloat s string String v default format any type
The "%v" specifier is provided for all built-in types, and should be provided for user-defined type formatters as well. It picks a "best" representation for the given type. For the built-in types the "%v" specifier is converted as follows:
c Char u other unsigned Integral d other signed Integral g RealFloat s String
Mismatch between the argument types and the format string, as well as any other syntactic or semantic errors in the format string, will cause an exception to be thrown at runtime.
Note that the formatting for RealFloat types is
currently a bit different from that of C printf(3),
conforming instead to showEFloat,
showFFloat and showGFloat (and their
alternate versions showFFloatAlt and
showGFloatAlt). This is hard to fix: the fixed
versions would format in a backward-incompatible way.
In any case the Haskell behavior is generally more
sensible than the C behavior. A brief summary of some
key differences:
- Haskell
printfnever uses the default "6-digit" precision used by C printf. - Haskell
printftreats the "precision" specifier as indicating the number of digits after the decimal point. - Haskell
printfprints the exponent of e-format numbers without a gratuitous plus sign, and with the minimum possible number of digits. - Haskell
printfwill place a zero after a decimal point when possible.
Raises an error with a printf-specific prefix on the
message string.
Since: base-4.7.0.0
hPrintf :: HPrintfType r => Handle -> String -> r #
formatRealFloat :: RealFloat a => a -> FieldFormatter #
Formatter for RealFloat values.
Since: base-4.7.0.0
formatInteger :: Integer -> FieldFormatter #
Formatter for Integer values.
Since: base-4.7.0.0
formatInt :: (Integral a, Bounded a) => a -> FieldFormatter #
Formatter for Int values.
Since: base-4.7.0.0
formatChar :: Char -> FieldFormatter #
Formatter for Char values.
Since: base-4.7.0.0
errorShortFormat :: a #
Calls perror to indicate that the format string ended
early.
Since: base-4.7.0.0
errorMissingArgument :: a #
Calls perror to indicate that there is a missing
argument in the argument list.
Since: base-4.7.0.0
errorBadFormat :: Char -> a #
Calls perror to indicate an unknown format letter for
a given type.
Since: base-4.7.0.0
errorBadArgument :: a #
Calls perror to indicate that there is a type
error or similar in the given argument.
Since: base-4.7.0.0
zipWithM_ :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m () #
zipWithM :: Applicative m => (a -> b -> m c) -> [a] -> [b] -> m [c] #
replicateM_ :: Applicative m => Int -> m a -> m () #
replicateM :: Applicative m => Int -> m a -> m [a] #
performs the action replicateM n actact n times,
and then returns the list of results:
Examples
>>>import Control.Monad.State>>>runState (replicateM 3 $ state $ \s -> (s, s + 1)) 1([1,2,3],4)
mapAndUnzipM :: Applicative m => (a -> m (b, c)) -> [a] -> m ([b], [c]) #
The mapAndUnzipM function maps its first argument over a list, returning
the result as a pair of lists. This function is mainly used with complicated
data structures or a state monad.
forever :: Applicative f => f a -> f b #
Repeat an action indefinitely.
Examples
A common use of forever is to process input from network sockets,
Handles, and channels
(e.g. MVar and
Chan).
For example, here is how we might implement an echo
server, using
forever both to listen for client connections on a network socket
and to echo client input on client connection handles:
echoServer :: Socket -> IO () echoServer socket =forever$ do client <- accept socketforkFinally(echo client) (\_ -> hClose client) where echo :: Handle -> IO () echo client =forever$ hGetLine client >>= hPutStrLn client
Note that "forever" isn't necessarily non-terminating.
If the action is in a and short-circuits after some number of iterations.
then MonadPlus actually returns forevermzero, effectively short-circuiting its caller.
foldM_ :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m () #
Like foldM, but discards the result.
foldM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b #
The foldM function is analogous to foldl, except that its result is
encapsulated in a monad. Note that foldM works from left-to-right over
the list arguments. This could be an issue where ( and the `folded
function' are not commutative.>>)
foldM f a1 [x1, x2, ..., xm] == do a2 <- f a1 x1 a3 <- f a2 x2 ... f am xm
If right-to-left evaluation is required, the input list should be reversed.
filterM :: Applicative m => (a -> m Bool) -> [a] -> m [a] #
This generalizes the list-based filter function.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c infixr 1 #
Left-to-right composition of Kleisli arrows.
'(bs ' can be understood as the >=> cs) ado expression
do b <- bs a cs b
traceShowId :: Show a => a -> a #
Like traceShow but returns the shown value instead of a third value.
>>>traceShowId (1+2+3, "hello" ++ "world")(6,"helloworld") (6,"helloworld")
Since: base-4.7.0.0
The traceIO function outputs the trace message from the IO monad.
This sequences the output with respect to other IO actions.
Since: base-4.5.0.0
isSubsequenceOf :: Eq a => [a] -> [a] -> Bool #
The isSubsequenceOf function takes two lists and returns True if all
the elements of the first list occur, in order, in the second. The
elements do not have to occur consecutively.
is equivalent to isSubsequenceOf x y.elem x (subsequences y)
Examples
>>>isSubsequenceOf "GHC" "The Glorious Haskell Compiler"True>>>isSubsequenceOf ['a','d'..'z'] ['a'..'z']True>>>isSubsequenceOf [1..10] [10,9..0]False
Since: base-4.8.0.0
mapAccumR :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b) #
The mapAccumR function behaves like a combination of fmap
and foldr; it applies a function to each element of a structure,
passing an accumulating parameter from right to left, and returning
a final value of this accumulator together with the new structure.
Examples
Basic usage:
>>>mapAccumR (\a b -> (a + b, a)) 0 [1..10](55,[54,52,49,45,40,34,27,19,10,0])
>>>mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]("054321",["05432","0543","054","05","0"])
mapAccumL :: Traversable t => (s -> a -> (s, b)) -> s -> t a -> (s, t b) #
The mapAccumL function behaves like a combination of fmap
and foldl; it applies a function to each element of a structure,
passing an accumulating parameter from left to right, and returning
a final value of this accumulator together with the new structure.
Examples
Basic usage:
>>>mapAccumL (\a b -> (a + b, a)) 0 [1..10](55,[0,1,3,6,10,15,21,28,36,45])
>>>mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]("012345",["0","01","012","0123","01234"])
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) #
Lists, but with an Applicative functor based on zipping.
Constructors
| ZipList | |
Fields
| |
Instances
| Foldable ZipList | Since: base-4.9.0.0 |
Defined in Control.Applicative Methods fold :: Monoid m => ZipList m -> m # foldMap :: Monoid m => (a -> m) -> ZipList a -> m # foldMap' :: Monoid m => (a -> m) -> ZipList a -> m # foldr :: (a -> b -> b) -> b -> ZipList a -> b # foldr' :: (a -> b -> b) -> b -> ZipList a -> b # foldl :: (b -> a -> b) -> b -> ZipList a -> b # foldl' :: (b -> a -> b) -> b -> ZipList a -> b # foldr1 :: (a -> a -> a) -> ZipList a -> a # foldl1 :: (a -> a -> a) -> ZipList a -> a # elem :: Eq a => a -> ZipList a -> Bool # maximum :: Ord a => ZipList a -> a # minimum :: Ord a => ZipList a -> a # | |
| Traversable ZipList | Since: base-4.9.0.0 |
| Alternative ZipList | Since: base-4.11.0.0 |
| Applicative ZipList | f <$> ZipList xs1 <*> ... <*> ZipList xsN
= ZipList (zipWithN f xs1 ... xsN)where (\a b c -> stimes c [a, b]) <$> ZipList "abcd" <*> ZipList "567" <*> ZipList [1..]
= ZipList (zipWith3 (\a b c -> stimes c [a, b]) "abcd" "567" [1..])
= ZipList {getZipList = ["a5","b6b6","c7c7c7"]}Since: base-2.1 |
| Functor ZipList | Since: base-2.1 |
| Generic1 ZipList | |
| Data a => Data (ZipList a) | Since: base-4.14.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> ZipList a -> c (ZipList a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (ZipList a) # toConstr :: ZipList a -> Constr # dataTypeOf :: ZipList a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (ZipList a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (ZipList a)) # gmapT :: (forall b. Data b => b -> b) -> ZipList a -> ZipList a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> ZipList a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> ZipList a -> r # gmapQ :: (forall d. Data d => d -> u) -> ZipList a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> ZipList a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> ZipList a -> m (ZipList a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> ZipList a -> m (ZipList a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> ZipList a -> m (ZipList a) # | |
| IsList (ZipList a) | Since: base-4.15.0.0 |
| Generic (ZipList a) | |
| Read a => Read (ZipList a) | Since: base-4.7.0.0 |
| Show a => Show (ZipList a) | Since: base-4.7.0.0 |
| Eq a => Eq (ZipList a) | Since: base-4.7.0.0 |
| Ord a => Ord (ZipList a) | Since: base-4.7.0.0 |
| MonoFunctor (ZipList a) | |
| MonoPointed (ZipList a) | |
| type Rep1 ZipList | Since: base-4.7.0.0 |
Defined in Control.Applicative | |
| type Item (ZipList a) | |
| type Rep (ZipList a) | Since: base-4.7.0.0 |
Defined in Control.Applicative | |
| type Element (ZipList a) | |
Defined in Data.MonoTraversable | |
newtype WrappedMonad (m :: Type -> Type) a #
Constructors
| WrapMonad | |
Fields
| |
Instances
| Generic1 (WrappedMonad m :: Type -> Type) | |
Defined in Control.Applicative Associated Types type Rep1 (WrappedMonad m) :: k -> Type # Methods from1 :: forall (a :: k). WrappedMonad m a -> Rep1 (WrappedMonad m) a # to1 :: forall (a :: k). Rep1 (WrappedMonad m) a -> WrappedMonad m a # | |
| MonadPlus m => Alternative (WrappedMonad m) | Since: base-2.1 |
Defined in Control.Applicative Methods empty :: WrappedMonad m a # (<|>) :: WrappedMonad m a -> WrappedMonad m a -> WrappedMonad m a # some :: WrappedMonad m a -> WrappedMonad m [a] # many :: WrappedMonad m a -> WrappedMonad m [a] # | |
| Monad m => Applicative (WrappedMonad m) | Since: base-2.1 |
Defined in Control.Applicative Methods pure :: a -> WrappedMonad m a # (<*>) :: WrappedMonad m (a -> b) -> WrappedMonad m a -> WrappedMonad m b # liftA2 :: (a -> b -> c) -> WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m c # (*>) :: WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m b # (<*) :: WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m a # | |
| Monad m => Functor (WrappedMonad m) | Since: base-2.1 |
Defined in Control.Applicative Methods fmap :: (a -> b) -> WrappedMonad m a -> WrappedMonad m b # (<$) :: a -> WrappedMonad m b -> WrappedMonad m a # | |
| Monad m => Monad (WrappedMonad m) | Since: base-4.7.0.0 |
Defined in Control.Applicative Methods (>>=) :: WrappedMonad m a -> (a -> WrappedMonad m b) -> WrappedMonad m b # (>>) :: WrappedMonad m a -> WrappedMonad m b -> WrappedMonad m b # return :: a -> WrappedMonad m a # | |
| (Typeable m, Typeable a, Data (m a)) => Data (WrappedMonad m a) | Since: base-4.14.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> WrappedMonad m a -> c (WrappedMonad m a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (WrappedMonad m a) # toConstr :: WrappedMonad m a -> Constr # dataTypeOf :: WrappedMonad m a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (WrappedMonad m a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (WrappedMonad m a)) # gmapT :: (forall b. Data b => b -> b) -> WrappedMonad m a -> WrappedMonad m a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> WrappedMonad m a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> WrappedMonad m a -> r # gmapQ :: (forall d. Data d => d -> u) -> WrappedMonad m a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> WrappedMonad m a -> u # gmapM :: Monad m0 => (forall d. Data d => d -> m0 d) -> WrappedMonad m a -> m0 (WrappedMonad m a) # gmapMp :: MonadPlus m0 => (forall d. Data d => d -> m0 d) -> WrappedMonad m a -> m0 (WrappedMonad m a) # gmapMo :: MonadPlus m0 => (forall d. Data d => d -> m0 d) -> WrappedMonad m a -> m0 (WrappedMonad m a) # | |
| Generic (WrappedMonad m a) | |
Defined in Control.Applicative Associated Types type Rep (WrappedMonad m a) :: Type -> Type # Methods from :: WrappedMonad m a -> Rep (WrappedMonad m a) x # to :: Rep (WrappedMonad m a) x -> WrappedMonad m a # | |
| Monad m => MonoFunctor (WrappedMonad m a) | |
Defined in Data.MonoTraversable Methods omap :: (Element (WrappedMonad m a) -> Element (WrappedMonad m a)) -> WrappedMonad m a -> WrappedMonad m a # | |
| Monad m => MonoPointed (WrappedMonad m a) | |
Defined in Data.MonoTraversable Methods opoint :: Element (WrappedMonad m a) -> WrappedMonad m a # | |
| type Rep1 (WrappedMonad m :: Type -> Type) | Since: base-4.7.0.0 |
Defined in Control.Applicative type Rep1 (WrappedMonad m :: Type -> Type) = D1 ('MetaData "WrappedMonad" "Control.Applicative" "base" 'True) (C1 ('MetaCons "WrapMonad" 'PrefixI 'True) (S1 ('MetaSel ('Just "unwrapMonad") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec1 m))) | |
| type Rep (WrappedMonad m a) | Since: base-4.7.0.0 |
Defined in Control.Applicative type Rep (WrappedMonad m a) = D1 ('MetaData "WrappedMonad" "Control.Applicative" "base" 'True) (C1 ('MetaCons "WrapMonad" 'PrefixI 'True) (S1 ('MetaSel ('Just "unwrapMonad") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (m a)))) | |
| type Element (WrappedMonad m a) | |
Defined in Data.MonoTraversable | |
newtype WrappedArrow (a :: Type -> Type -> Type) b c #
Constructors
| WrapArrow | |
Fields
| |
Instances
| Generic1 (WrappedArrow a b :: Type -> Type) | |
Defined in Control.Applicative Associated Types type Rep1 (WrappedArrow a b) :: k -> Type # Methods from1 :: forall (a0 :: k). WrappedArrow a b a0 -> Rep1 (WrappedArrow a b) a0 # to1 :: forall (a0 :: k). Rep1 (WrappedArrow a b) a0 -> WrappedArrow a b a0 # | |
| (ArrowZero a, ArrowPlus a) => Alternative (WrappedArrow a b) | Since: base-2.1 |
Defined in Control.Applicative Methods empty :: WrappedArrow a b a0 # (<|>) :: WrappedArrow a b a0 -> WrappedArrow a b a0 -> WrappedArrow a b a0 # some :: WrappedArrow a b a0 -> WrappedArrow a b [a0] # many :: WrappedArrow a b a0 -> WrappedArrow a b [a0] # | |
| Arrow a => Applicative (WrappedArrow a b) | Since: base-2.1 |
Defined in Control.Applicative Methods pure :: a0 -> WrappedArrow a b a0 # (<*>) :: WrappedArrow a b (a0 -> b0) -> WrappedArrow a b a0 -> WrappedArrow a b b0 # liftA2 :: (a0 -> b0 -> c) -> WrappedArrow a b a0 -> WrappedArrow a b b0 -> WrappedArrow a b c # (*>) :: WrappedArrow a b a0 -> WrappedArrow a b b0 -> WrappedArrow a b b0 # (<*) :: WrappedArrow a b a0 -> WrappedArrow a b b0 -> WrappedArrow a b a0 # | |
| Arrow a => Functor (WrappedArrow a b) | Since: base-2.1 |
Defined in Control.Applicative Methods fmap :: (a0 -> b0) -> WrappedArrow a b a0 -> WrappedArrow a b b0 # (<$) :: a0 -> WrappedArrow a b b0 -> WrappedArrow a b a0 # | |
| (Typeable a, Typeable b, Typeable c, Data (a b c)) => Data (WrappedArrow a b c) | Since: base-4.14.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b0. Data d => c0 (d -> b0) -> d -> c0 b0) -> (forall g. g -> c0 g) -> WrappedArrow a b c -> c0 (WrappedArrow a b c) # gunfold :: (forall b0 r. Data b0 => c0 (b0 -> r) -> c0 r) -> (forall r. r -> c0 r) -> Constr -> c0 (WrappedArrow a b c) # toConstr :: WrappedArrow a b c -> Constr # dataTypeOf :: WrappedArrow a b c -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c0 (t d)) -> Maybe (c0 (WrappedArrow a b c)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c0 (t d e)) -> Maybe (c0 (WrappedArrow a b c)) # gmapT :: (forall b0. Data b0 => b0 -> b0) -> WrappedArrow a b c -> WrappedArrow a b c # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> WrappedArrow a b c -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> WrappedArrow a b c -> r # gmapQ :: (forall d. Data d => d -> u) -> WrappedArrow a b c -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> WrappedArrow a b c -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> WrappedArrow a b c -> m (WrappedArrow a b c) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> WrappedArrow a b c -> m (WrappedArrow a b c) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> WrappedArrow a b c -> m (WrappedArrow a b c) # | |
| Generic (WrappedArrow a b c) | |
Defined in Control.Applicative Associated Types type Rep (WrappedArrow a b c) :: Type -> Type # Methods from :: WrappedArrow a b c -> Rep (WrappedArrow a b c) x # to :: Rep (WrappedArrow a b c) x -> WrappedArrow a b c # | |
| Arrow a => MonoFunctor (WrappedArrow a b c) | |
Defined in Data.MonoTraversable Methods omap :: (Element (WrappedArrow a b c) -> Element (WrappedArrow a b c)) -> WrappedArrow a b c -> WrappedArrow a b c # | |
| Arrow a => MonoPointed (WrappedArrow a b c) | |
Defined in Data.MonoTraversable Methods opoint :: Element (WrappedArrow a b c) -> WrappedArrow a b c # | |
| type Rep1 (WrappedArrow a b :: Type -> Type) | Since: base-4.7.0.0 |
Defined in Control.Applicative type Rep1 (WrappedArrow a b :: Type -> Type) = D1 ('MetaData "WrappedArrow" "Control.Applicative" "base" 'True) (C1 ('MetaCons "WrapArrow" 'PrefixI 'True) (S1 ('MetaSel ('Just "unwrapArrow") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec1 (a b)))) | |
| type Rep (WrappedArrow a b c) | Since: base-4.7.0.0 |
Defined in Control.Applicative type Rep (WrappedArrow a b c) = D1 ('MetaData "WrappedArrow" "Control.Applicative" "base" 'True) (C1 ('MetaCons "WrapArrow" 'PrefixI 'True) (S1 ('MetaSel ('Just "unwrapArrow") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (a b c)))) | |
| type Element (WrappedArrow a b c) | |
Defined in Data.MonoTraversable | |
optional :: Alternative f => f a -> f (Maybe a) #
One or none.
It is useful for modelling any computation that is allowed to fail.
Examples
Using the Alternative instance of Control.Monad.Except, the following functions:
>>>import Control.Monad.Except
>>>canFail = throwError "it failed" :: Except String Int>>>final = return 42 :: Except String Int
Can be combined by allowing the first function to fail:
>>>runExcept $ canFail *> finalLeft "it failed">>>runExcept $ optional canFail *> finalRight 42
writeFile :: FilePath -> String -> IO () #
The computation writeFile file str function writes the string str,
to the file file.
readFile' :: FilePath -> IO String #
The readFile' function reads a file and
returns the contents of the file as a string.
The file is fully read before being returned, as with getContents'.
Since: base-4.15.0.0
readFile :: FilePath -> IO String #
The readFile function reads a file and
returns the contents of the file as a string.
The file is read lazily, on demand, as with getContents.
openTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) #
Like openTempFile, but uses the default file permissions
Arguments
| :: FilePath | Directory in which to create the file |
| -> String | File name template. If the template is "foo.ext" then the created file will be "fooXXX.ext" where XXX is some random number. Note that this should not contain any path separator characters. |
| -> IO (FilePath, Handle) |
The function creates a temporary file in ReadWrite mode. The created file isn't deleted automatically, so you need to delete it manually.
The file is created with permissions such that only the current user can read/write it.
With some exceptions (see below), the file will be created securely
in the sense that an attacker should not be able to cause
openTempFile to overwrite another file on the filesystem using your
credentials, by putting symbolic links (on Unix) in the place where
the temporary file is to be created. On Unix the O_CREAT and
O_EXCL flags are used to prevent this attack, but note that
O_EXCL is sometimes not supported on NFS filesystems, so if you
rely on this behaviour it is best to use local filesystems only.
openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) #
Like openBinaryTempFile, but uses the default file permissions
openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) #
Like openTempFile, but opens the file in binary mode. See openBinaryFile for more comments.
localeEncoding :: TextEncoding #
The Unicode encoding of the current locale
This is the initial locale encoding: if it has been subsequently changed by
setLocaleEncoding this value will not reflect that change.
interact :: (String -> String) -> IO () #
The interact function takes a function of type String->String
as its argument. The entire input from the standard input device is
passed to this function as its argument, and the resulting string is
output on the standard output device.
Computation hReady hdl indicates whether at least one item is
available for input from handle hdl.
This operation may fail with:
isEOFErrorif the end of file has been reached.
hPrint :: Show a => Handle -> a -> IO () #
Computation hPrint hdl t writes the string representation of t
given by the shows function to the file or channel managed by hdl
and appends a newline.
This operation may fail with:
isFullErrorif the device is full; orisPermissionErrorif another system resource limit would be exceeded.
getContents' :: IO String #
The getContents' operation returns all user input as a single string,
which is fully read before being returned
(same as hGetContents' stdin).
Since: base-4.15.0.0
getContents :: IO String #
The getContents operation returns all user input as a single string,
which is read lazily as it is needed
(same as hGetContents stdin).
fixIO :: (a -> IO a) -> IO a #
The implementation of mfix for IO. If the function
passed to fixIO inspects its argument, the resulting action will throw
FixIOException.
appendFile :: FilePath -> String -> IO () #
The computation appendFile file str function appends the string str,
to the file file.
Note that writeFile and appendFile write a literal string
to a file. To write a value of any printable type, as with print,
use the show function to convert the value to a string first.
main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
data HandlePosn #
Instances
| Show HandlePosn | Since: base-4.1.0.0 |
Defined in GHC.IO.Handle Methods showsPrec :: Int -> HandlePosn -> ShowS # show :: HandlePosn -> String # showList :: [HandlePosn] -> ShowS # | |
| Eq HandlePosn | Since: base-4.1.0.0 |
Defined in GHC.IO.Handle | |
hTell :: Handle -> IO Integer #
Computation hTell hdl returns the current position of the
handle hdl, as the number of bytes from the beginning of
the file. The value returned may be subsequently passed to
hSeek to reposition the handle to the current position.
This operation may fail with:
isIllegalOperationErrorif the Handle is not seekable.
hSetPosn :: HandlePosn -> IO () #
If a call to hGetPosn hdl returns a position p,
then computation hSetPosn p sets the position of hdl
to the position it held at the time of the call to hGetPosn.
This operation may fail with:
isPermissionErrorif a system resource limit would be exceeded.
hSetNewlineMode :: Handle -> NewlineMode -> IO () #
Set the NewlineMode on the specified Handle. All buffered
data is flushed first.
hSetFileSize :: Handle -> Integer -> IO () #
hSetFileSize hdl size truncates the physical file with handle hdl to size bytes.
hSetEncoding :: Handle -> TextEncoding -> IO () #
The action hSetEncoding hdl encoding changes the text encoding
for the handle hdl to encoding. The default encoding when a Handle is
created is localeEncoding, namely the default encoding for the
current locale.
To create a Handle with no encoding at all, use openBinaryFile. To
stop further encoding or decoding on an existing Handle, use
hSetBinaryMode.
hSetEncoding may need to flush buffered data in order to change
the encoding.
hSetBuffering :: Handle -> BufferMode -> IO () #
Computation hSetBuffering hdl mode sets the mode of buffering for
handle hdl on subsequent reads and writes.
If the buffer mode is changed from BlockBuffering or
LineBuffering to NoBuffering, then
- if
hdlis writable, the buffer is flushed as forhFlush; - if
hdlis not writable, the contents of the buffer is discarded.
This operation may fail with:
isPermissionErrorif the handle has already been used for reading or writing and the implementation does not allow the buffering mode to be changed.
hSetBinaryMode :: Handle -> Bool -> IO () #
Select binary mode (True) or text mode (False) on a open handle.
(See also openBinaryFile.)
This has the same effect as calling hSetEncoding with char8, together
with hSetNewlineMode with noNewlineTranslation.
hSeek :: Handle -> SeekMode -> Integer -> IO () #
Computation hSeek hdl mode i sets the position of handle
hdl depending on mode.
The offset i is given in terms of 8-bit bytes.
If hdl is block- or line-buffered, then seeking to a position which is not
in the current buffer will first cause any items in the output buffer to be
written to the device, and then cause the input buffer to be discarded.
Some handles may not be seekable (see hIsSeekable), or only support a
subset of the possible positioning operations (for instance, it may only
be possible to seek to the end of a tape, or to a positive offset from
the beginning or current position).
It is not possible to set a negative I/O position, or for
a physical file, an I/O position beyond the current end-of-file.
This operation may fail with:
isIllegalOperationErrorif the Handle is not seekable, or does not support the requested seek mode.isPermissionErrorif a system resource limit would be exceeded.
hLookAhead :: Handle -> IO Char #
Computation hLookAhead returns the next character from the handle
without removing it from the input buffer, blocking until a character
is available.
This operation may fail with:
isEOFErrorif the end of file has been reached.
hIsWritable :: Handle -> IO Bool #
hIsTerminalDevice :: Handle -> IO Bool #
Is the handle connected to a terminal?
hIsSeekable :: Handle -> IO Bool #
hIsReadable :: Handle -> IO Bool #
For a readable handle hdl, hIsEOF hdl returns
True if no further input can be taken from hdl or for a
physical file, if the current I/O position is equal to the length of
the file. Otherwise, it returns False.
NOTE: hIsEOF may block, because it has to attempt to read from
the stream to determine whether there is any more data to be read.
hGetPosn :: Handle -> IO HandlePosn #
Computation hGetPosn hdl returns the current I/O position of
hdl as a value of the abstract type HandlePosn.
hGetEncoding :: Handle -> IO (Maybe TextEncoding) #
Return the current TextEncoding for the specified Handle, or
Nothing if the Handle is in binary mode.
Note that the TextEncoding remembers nothing about the state of
the encoder/decoder in use on this Handle. For example, if the
encoding in use is UTF-16, then using hGetEncoding and
hSetEncoding to save and restore the encoding may result in an
extra byte-order-mark being written to the file.
hGetBuffering :: Handle -> IO BufferMode #
Computation hGetBuffering hdl returns the current buffering mode
for hdl.
hFileSize :: Handle -> IO Integer #
For a handle hdl which attached to a physical file,
hFileSize hdl returns the size of that file in 8-bit bytes.
Computation hClose hdl makes handle hdl closed. Before the
computation finishes, if hdl is writable its buffer is flushed as
for hFlush.
Performing hClose on a handle that has already been closed has no effect;
doing so is not an error. All other operations on a closed handle will fail.
If hClose fails for any reason, any further operations (apart from
hClose) on the handle will still fail as if hdl had been successfully
closed.
hClose is an interruptible operation in the sense described in
Control.Exception. If hClose is interrupted by an asynchronous
exception in the process of flushing its buffers, then the I/O device
(e.g., file) will be closed anyway.
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.
withMVarMasked :: MVar a -> (a -> IO b) -> IO b #
Like withMVar, but the IO action in the second argument is executed
with asynchronous exceptions masked.
Since: base-4.7.0.0
withMVar :: MVar a -> (a -> IO b) -> IO b #
withMVar is an exception-safe wrapper for operating on the contents
of an MVar. This operation is exception-safe: it will replace the
original contents of the MVar if an exception is raised (see
Control.Exception). However, it is only atomic if there are no
other producers for this MVar.
modifyMVar_ :: MVar a -> (a -> IO a) -> IO () #
An exception-safe wrapper for modifying the contents of an MVar.
Like withMVar, modifyMVar will replace the original contents of
the MVar if an exception is raised during the operation. This
function is only atomic if there are no other producers for this
MVar.
modifyMVarMasked_ :: MVar a -> (a -> IO a) -> IO () #
Like modifyMVar_, but the IO action in the second argument is executed with
asynchronous exceptions masked.
Since: base-4.6.0.0
modifyMVarMasked :: MVar a -> (a -> IO (a, b)) -> IO b #
Like modifyMVar, but the IO action in the second argument is executed with
asynchronous exceptions masked.
Since: base-4.6.0.0
modifyMVar :: MVar a -> (a -> IO (a, b)) -> IO b #
A slight variation on modifyMVar_ that allows a value to be
returned (b) in addition to the modified value of the MVar.
addMVarFinalizer :: MVar a -> IO () -> IO () #
hWaitForInput :: Handle -> Int -> IO Bool #
Computation hWaitForInput hdl t
waits until input is available on handle hdl.
It returns True as soon as input is available on hdl,
or False if no input is available within t milliseconds. Note that
hWaitForInput waits until one or more full characters are available,
which means that it needs to do decoding, and hence may fail
with a decoding error.
If t is less than zero, then hWaitForInput waits indefinitely.
This operation may fail with:
isEOFErrorif the end of file has been reached.- a decoding error, if the input begins with an invalid byte sequence in this Handle's encoding.
NOTE for GHC users: unless you use the -threaded flag,
hWaitForInput hdl t where t >= 0 will block all other Haskell
threads for the duration of the call. It behaves like a
safe foreign call in this respect.
hPutStr :: Handle -> String -> IO () #
Computation hPutStr hdl s writes the string
s to the file or channel managed by hdl.
This operation may fail with:
isFullErrorif the device is full; orisPermissionErrorif another system resource limit would be exceeded.
hPutChar :: Handle -> Char -> IO () #
Computation hPutChar hdl ch writes the character ch to the
file or channel managed by hdl. Characters may be buffered if
buffering is enabled for hdl.
This operation may fail with:
isFullErrorif the device is full; orisPermissionErrorif another system resource limit would be exceeded.
hPutBuf :: Handle -> Ptr a -> Int -> IO () #
hPutBuf hdl buf count writes count 8-bit bytes from the
buffer buf to the handle hdl. It returns ().
hPutBuf ignores any text encoding that applies to the Handle,
writing the bytes directly to the underlying file or device.
hPutBuf ignores the prevailing TextEncoding and
NewlineMode on the Handle, and writes bytes directly.
This operation may fail with:
ResourceVanishedif the handle is a pipe or socket, and the reading end is closed. (If this is a POSIX system, and the program has not asked to ignore SIGPIPE, then a SIGPIPE may be delivered instead, whose default action is to terminate the program).
hGetLine :: Handle -> IO String #
Computation hGetLine hdl reads a line from the file or
channel managed by hdl.
This operation may fail with:
isEOFErrorif the end of file is encountered when reading the first character of the line.
If hGetLine encounters end-of-file at any other point while reading
in a line, it is treated as a line terminator and the (partial)
line is returned.
hGetContents' :: Handle -> IO String #
The hGetContents' operation reads all input on the given handle
before returning it as a String and closing the handle.
Since: base-4.15.0.0
hGetContents :: Handle -> IO String #
Computation hGetContents hdl returns the list of characters
corresponding to the unread portion of the channel or file managed
by hdl, which is put into an intermediate state, semi-closed.
In this state, hdl is effectively closed,
but items are read from hdl on demand and accumulated in a special
list returned by hGetContents hdl.
Any operation that fails because a handle is closed,
also fails if a handle is semi-closed. The only exception is
hClose. A semi-closed handle becomes closed:
- if
hCloseis applied to it; - if an I/O error occurs when reading an item from the handle;
- or once the entire contents of the handle has been read.
Once a semi-closed handle becomes closed, the contents of the associated list becomes fixed. The contents of this final list is only partially specified: it will contain at least all the items of the stream that were evaluated prior to the handle becoming closed.
Any I/O errors encountered while a handle is semi-closed are simply discarded.
This operation may fail with:
isEOFErrorif the end of file has been reached.
hGetChar :: Handle -> IO Char #
Computation hGetChar hdl reads a character from the file or
channel managed by hdl, blocking until a character is available.
This operation may fail with:
isEOFErrorif the end of file has been reached.
hGetBufSome :: Handle -> Ptr a -> Int -> IO Int #
hGetBufSome hdl buf count reads data from the handle hdl
into the buffer buf. If there is any data available to read,
then hGetBufSome returns it immediately; it only blocks if there
is no data to be read.
It returns the number of bytes actually read. This may be zero if
EOF was reached before any data was read (or if count is zero).
hGetBufSome never raises an EOF exception, instead it returns a value
smaller than count.
If the handle is a pipe or socket, and the writing end
is closed, hGetBufSome will behave as if EOF was reached.
hGetBufSome ignores the prevailing TextEncoding and
NewlineMode on the Handle, and reads bytes directly.
hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int #
hGetBufNonBlocking hdl buf count reads data from the handle hdl
into the buffer buf until either EOF is reached, or
count 8-bit bytes have been read, or there is no more data available
to read immediately.
hGetBufNonBlocking is identical to hGetBuf, except that it will
never block waiting for data to become available, instead it returns
only whatever data is available. To wait for data to arrive before
calling hGetBufNonBlocking, use hWaitForInput.
If the handle is a pipe or socket, and the writing end
is closed, hGetBufNonBlocking will behave as if EOF was reached.
hGetBufNonBlocking ignores the prevailing TextEncoding and
NewlineMode on the Handle, and reads bytes directly.
NOTE: on Windows, this function does not work correctly; it
behaves identically to hGetBuf.
hGetBuf :: Handle -> Ptr a -> Int -> IO Int #
hGetBuf hdl buf count reads data from the handle hdl
into the buffer buf until either EOF is reached or
count 8-bit bytes have been read.
It returns the number of bytes actually read. This may be zero if
EOF was reached before any data was read (or if count is zero).
hGetBuf never raises an EOF exception, instead it returns a value
smaller than count.
If the handle is a pipe or socket, and the writing end
is closed, hGetBuf will behave as if EOF was reached.
hGetBuf ignores the prevailing TextEncoding and NewlineMode
on the Handle, and reads bytes directly.
The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte
sequence 0xEF 0xBB 0xBF). This encoding behaves like utf8,
except that on input, the BOM sequence is ignored at the beginning
of the stream, and on output, the BOM sequence is prepended.
The byte-order-mark is strictly unnecessary in UTF-8, but is sometimes used to identify the encoding of a file.
utf8 :: TextEncoding #
The UTF-8 Unicode encoding
utf32le :: TextEncoding #
The UTF-32 Unicode encoding (little-endian)
utf32be :: TextEncoding #
The UTF-32 Unicode encoding (big-endian)
utf32 :: TextEncoding #
The UTF-32 Unicode encoding (a byte-order-mark should be used to indicate endianness).
utf16le :: TextEncoding #
The UTF-16 Unicode encoding (little-endian)
utf16be :: TextEncoding #
The UTF-16 Unicode encoding (big-endian)
utf16 :: TextEncoding #
The UTF-16 Unicode encoding (a byte-order-mark should be used to indicate endianness).
mkTextEncoding :: String -> IO TextEncoding #
Look up the named Unicode encoding. May fail with
isDoesNotExistErrorif the encoding is unknown
The set of known encodings is system-dependent, but includes at least:
UTF-8
UTF-16,UTF-16BE,UTF-16LEUTF-32,UTF-32BE,UTF-32LE
There is additional notation (borrowed from GNU iconv) for specifying how illegal characters are handled:
- a suffix of
//IGNORE, e.g.UTF-8//IGNORE, will cause all illegal sequences on input to be ignored, and on output will drop all code points that have no representation in the target encoding. - a suffix of
//TRANSLITwill choose a replacement character for illegal sequences or code points. - a suffix of
//ROUNDTRIPwill use a PEP383-style escape mechanism to represent any invalid bytes in the input as Unicode codepoints (specifically, as lone surrogates, which are normally invalid in UTF-32). Upon output, these special codepoints are detected and turned back into the corresponding original byte.
In theory, this mechanism allows arbitrary data to be roundtripped via
a String with no loss of data. In practice, there are two limitations
to be aware of:
- This only stands a chance of working for an encoding which is an ASCII superset, as for security reasons we refuse to escape any bytes smaller than 128. Many encodings of interest are ASCII supersets (in particular, you can assume that the locale encoding is an ASCII superset) but many (such as UTF-16) are not.
- If the underlying encoding is not itself roundtrippable, this mechanism can fail. Roundtrippable encodings are those which have an injective mapping into Unicode. Almost all encodings meet this criteria, but some do not. Notably, Shift-JIS (CP932) and Big5 contain several different encodings of the same Unicode codepoint.
On Windows, you can access supported code pages with the prefix
CP; for example, "CP1250".
latin1 :: TextEncoding #
char8 :: TextEncoding #
An encoding in which Unicode code points are translated to bytes by taking the code point modulo 256. When decoding, bytes are translated directly into the equivalent code point.
This encoding never fails in either direction. However, encoding discards information, so encode followed by decode is not the identity.
Since: base-4.4.0.0
userErrorType :: IOErrorType #
I/O error that is programmer-defined.
tryIOError :: IO a -> IO (Either IOError a) #
The construct tryIOError comp exposes IO errors which occur within a
computation, and which are not fully handled.
Non-I/O exceptions are not caught by this variant; to catch all
exceptions, use try from Control.Exception.
Since: base-4.4.0.0
resourceVanishedErrorType :: IOErrorType #
I/O error where the operation failed because the resource vanished. This happens when, for example, attempting to write to a closed socket or attempting to write to a named pipe that was deleted.
Since: base-4.14.0.0
permissionErrorType :: IOErrorType #
I/O error where the operation failed because the user does not have sufficient operating system privilege to perform that operation.
modifyIOError :: (IOError -> IOError) -> IO a -> IO a #
Catch any IOException that occurs in the computation and throw a
modified version.
mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError #
Construct an IOException of the given type where the second argument
describes the error location and the third and fourth argument
contain the file handle and file path of the file involved in the
error if applicable.
isUserErrorType :: IOErrorType -> Bool #
I/O error that is programmer-defined.
isUserError :: IOError -> Bool #
A programmer-defined error value constructed using userError.
isResourceVanishedErrorType :: IOErrorType -> Bool #
I/O error where the operation failed because the resource vanished.
See resourceVanishedErrorType.
Since: base-4.14.0.0
isResourceVanishedError :: IOError -> Bool #
An error indicating that the operation failed because the
resource vanished. See resourceVanishedErrorType.
Since: base-4.14.0.0
isPermissionErrorType :: IOErrorType -> Bool #
I/O error where the operation failed because the user does not have sufficient operating system privilege to perform that operation.
isPermissionError :: IOError -> Bool #
An error indicating that an IO operation failed because
the user does not have sufficient operating system privilege
to perform that operation.
isIllegalOperationErrorType :: IOErrorType -> Bool #
I/O error where the operation is not possible.
isIllegalOperation :: IOError -> Bool #
An error indicating that an IO operation failed because
the operation was not possible.
Any computation which returns an IO result may fail with
isIllegalOperation. In some cases, an implementation will not be
able to distinguish between the possible error causes. In this case
it should fail with isIllegalOperation.
isFullErrorType :: IOErrorType -> Bool #
I/O error where the operation failed because the device is full.
isFullError :: IOError -> Bool #
An error indicating that an IO operation failed because
the device is full.
isEOFErrorType :: IOErrorType -> Bool #
I/O error where the operation failed because the end of file has been reached.
isEOFError :: IOError -> Bool #
An error indicating that an IO operation failed because
the end of file has been reached.
isDoesNotExistErrorType :: IOErrorType -> Bool #
I/O error where the operation failed because one of its arguments does not exist.
isDoesNotExistError :: IOError -> Bool #
An error indicating that an IO operation failed because
one of its arguments does not exist.
isAlreadyInUseErrorType :: IOErrorType -> Bool #
I/O error where the operation failed because one of its arguments is a single-use resource, which is already being used.
isAlreadyInUseError :: IOError -> Bool #
An error indicating that an IO operation failed because
one of its arguments is a single-use resource, which is already
being used (for example, opening the same file twice for writing
might give this error).
isAlreadyExistsErrorType :: IOErrorType -> Bool #
I/O error where the operation failed because one of its arguments already exists.
isAlreadyExistsError :: IOError -> Bool #
An error indicating that an IO operation failed because
one of its arguments already exists.
ioeSetLocation :: IOError -> String -> IOError #
ioeSetHandle :: IOError -> Handle -> IOError #
ioeSetFileName :: IOError -> FilePath -> IOError #
ioeSetErrorType :: IOError -> IOErrorType -> IOError #
ioeSetErrorString :: IOError -> String -> IOError #
ioeGetLocation :: IOError -> String #
ioeGetHandle :: IOError -> Maybe Handle #
ioeGetFileName :: IOError -> Maybe FilePath #
ioeGetErrorType :: IOError -> IOErrorType #
ioeGetErrorString :: IOError -> String #
illegalOperationErrorType :: IOErrorType #
I/O error where the operation is not possible.
fullErrorType :: IOErrorType #
I/O error where the operation failed because the device is full.
I/O error where the operation failed because the end of file has been reached.
doesNotExistErrorType :: IOErrorType #
I/O error where the operation failed because one of its arguments does not exist.
catchIOError :: IO a -> (IOError -> IO a) -> IO a #
The catchIOError function establishes a handler that receives any
IOException raised in the action protected by catchIOError.
An IOException is caught by
the most recent handler established by one of the exception handling
functions. These handlers are
not selective: all IOExceptions are caught. Exception propagation
must be explicitly provided in a handler by re-raising any unwanted
exceptions. For example, in
f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e)
the function f returns [] when an end-of-file exception
(cf. isEOFError) occurs in g; otherwise, the
exception is propagated to the next outer handler.
When an exception propagates outside the main program, the Haskell
system prints the associated IOException value and exits the program.
Non-I/O exceptions are not caught by this variant; to catch all
exceptions, use catch from Control.Exception.
Since: base-4.4.0.0
annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError #
Adds a location description and maybe a file path and file handle
to an IOException. If any of the file handle or file path is not given
the corresponding value in the IOException remains unaltered.
alreadyInUseErrorType :: IOErrorType #
I/O error where the operation failed because one of its arguments is a single-use resource, which is already being used.
alreadyExistsErrorType :: IOErrorType #
I/O error where the operation failed because one of its arguments already exists.
The yield action allows (forces, in a co-operative multitasking
implementation) a context-switch to any other currently runnable
threads (if any), and is occasionally useful when implementing
concurrency abstractions.
throwTo :: Exception e => ThreadId -> e -> IO () #
throwTo raises an arbitrary exception in the target thread (GHC only).
Exception delivery synchronizes between the source and target thread:
throwTo does not return until the exception has been raised in the
target thread. The calling thread can thus be certain that the target
thread has received the exception. Exception delivery is also atomic
with respect to other exceptions. Atomicity is a useful property to have
when dealing with race conditions: e.g. if there are two threads that
can kill each other, it is guaranteed that only one of the threads
will get to kill the other.
Whatever work the target thread was doing when the exception was raised is not lost: the computation is suspended until required by another thread.
If the target thread is currently making a foreign call, then the
exception will not be raised (and hence throwTo will not return)
until the call has completed. This is the case regardless of whether
the call is inside a mask or not. However, in GHC a foreign call
can be annotated as interruptible, in which case a throwTo will
cause the RTS to attempt to cause the call to return; see the GHC
documentation for more details.
Important note: the behaviour of throwTo differs from that described in
the paper "Asynchronous exceptions in Haskell"
(http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm).
In the paper, throwTo is non-blocking; but the library implementation adopts
a more synchronous design in which throwTo does not return until the exception
is received by the target thread. The trade-off is discussed in Section 9 of the paper.
Like any blocking operation, throwTo is therefore interruptible (see Section 5.3 of
the paper). Unlike other interruptible operations, however, throwTo
is always interruptible, even if it does not actually block.
There is no guarantee that the exception will be delivered promptly,
although the runtime will endeavour to ensure that arbitrary
delays don't occur. In GHC, an exception can only be raised when a
thread reaches a safe point, where a safe point is where memory
allocation occurs. Some loops do not perform any memory allocation
inside the loop and therefore cannot be interrupted by a throwTo.
If the target of throwTo is the calling thread, then the behaviour
is the same as throwIO, except that the exception
is thrown as an asynchronous exception. This means that if there is
an enclosing pure computation, which would be the case if the current
IO operation is inside unsafePerformIO or unsafeInterleaveIO, that
computation is not permanently replaced by the exception, but is
suspended as if it had received an asynchronous exception.
Note that if throwTo is called with the current thread as the
target, the exception will be thrown even if the thread is currently
inside mask or uninterruptibleMask.
threadCapability :: ThreadId -> IO (Int, Bool) #
Returns the number of the capability on which the thread is currently
running, and a boolean indicating whether the thread is locked to
that capability or not. A thread is locked to a capability if it
was created with forkOn.
Since: base-4.4.0.0
setNumCapabilities :: Int -> IO () #
Set the number of Haskell threads that can run truly simultaneously
(on separate physical processors) at any given time. The number
passed to forkOn is interpreted modulo this value. The initial
value is given by the +RTS -N runtime flag.
This is also the number of threads that will participate in parallel garbage collection. It is strongly recommended that the number of capabilities is not set larger than the number of physical processor cores, and it may often be beneficial to leave one or more cores free to avoid contention with other processes in the machine.
Since: base-4.5.0.0
myThreadId :: IO ThreadId #
Returns the ThreadId of the calling thread (GHC only).
mkWeakThreadId :: ThreadId -> IO (Weak ThreadId) #
Make a weak pointer to a ThreadId. It can be important to do
this if you want to hold a reference to a ThreadId while still
allowing the thread to receive the BlockedIndefinitely family of
exceptions (e.g. BlockedIndefinitelyOnMVar). Holding a normal
ThreadId reference will prevent the delivery of
BlockedIndefinitely exceptions because the reference could be
used as the target of throwTo at any time, which would unblock
the thread.
Holding a Weak ThreadId, on the other hand, will not prevent the
thread from receiving BlockedIndefinitely exceptions. It is
still possible to throw an exception to a Weak ThreadId, but the
caller must use deRefWeak first to determine whether the thread
still exists.
Since: base-4.6.0.0
killThread :: ThreadId -> IO () #
killThread raises the ThreadKilled exception in the given
thread (GHC only).
killThread tid = throwTo tid ThreadKilled
getNumCapabilities :: IO Int #
Returns the number of Haskell threads that can run truly
simultaneously (on separate physical processors) at any given time. To change
this value, use setNumCapabilities.
Since: base-4.4.0.0
data IOErrorType #
An abstract type that contains a value for each variant of IOException.
Instances
| Show IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception Methods showsPrec :: Int -> IOErrorType -> ShowS # show :: IOErrorType -> String # showList :: [IOErrorType] -> ShowS # | |
| Eq IOErrorType | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception | |
Defines the exit codes that a program can return.
Constructors
| ExitSuccess | indicates successful termination; |
| ExitFailure Int | indicates program failure with an exit code. The exact interpretation of the code is operating-system dependent. In particular, some values may be prohibited (e.g. 0 on a POSIX-compliant system). |
Instances
| Exception ExitCode | Since: base-4.1.0.0 |
Defined in GHC.IO.Exception Methods toException :: ExitCode -> SomeException # fromException :: SomeException -> Maybe ExitCode # displayException :: ExitCode -> String # | |
| Generic ExitCode | |
| Read ExitCode | |
| Show ExitCode | |
| Eq ExitCode | |
| Ord ExitCode | |
Defined in GHC.IO.Exception | |
| type Rep ExitCode | |
Defined in GHC.IO.Exception type Rep ExitCode = D1 ('MetaData "ExitCode" "GHC.IO.Exception" "base" 'False) (C1 ('MetaCons "ExitSuccess" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "ExitFailure" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int))) | |
The action hFlush hdl causes any items buffered for output
in handle hdl to be sent immediately to the operating system.
This operation may fail with:
isFullErrorif the device is full;isPermissionErrorif a system resource limit would be exceeded. It is unspecified whether the characters in the buffer are discarded or retained under these circumstances.
data NewlineMode #
Specifies the translation, if any, of newline characters between
internal Strings and the external file or stream. Haskell Strings
are assumed to represent newlines with the '\n' character; the
newline mode specifies how to translate '\n' on output, and what to
translate into '\n' on input.
Constructors
| NewlineMode | |
Instances
| Read NewlineMode | Since: base-4.3.0.0 |
Defined in GHC.IO.Handle.Types Methods readsPrec :: Int -> ReadS NewlineMode # readList :: ReadS [NewlineMode] # readPrec :: ReadPrec NewlineMode # readListPrec :: ReadPrec [NewlineMode] # | |
| Show NewlineMode | Since: base-4.3.0.0 |
Defined in GHC.IO.Handle.Types Methods showsPrec :: Int -> NewlineMode -> ShowS # show :: NewlineMode -> String # showList :: [NewlineMode] -> ShowS # | |
| Eq NewlineMode | Since: base-4.2.0.0 |
Defined in GHC.IO.Handle.Types | |
| Ord NewlineMode | Since: base-4.3.0.0 |
Defined in GHC.IO.Handle.Types Methods compare :: NewlineMode -> NewlineMode -> Ordering # (<) :: NewlineMode -> NewlineMode -> Bool # (<=) :: NewlineMode -> NewlineMode -> Bool # (>) :: NewlineMode -> NewlineMode -> Bool # (>=) :: NewlineMode -> NewlineMode -> Bool # max :: NewlineMode -> NewlineMode -> NewlineMode # min :: NewlineMode -> NewlineMode -> NewlineMode # | |
The representation of a newline in the external file or stream.
data BufferMode #
Three kinds of buffering are supported: line-buffering, block-buffering or no-buffering. These modes have the following effects. For output, items are written out, or flushed, from the internal buffer according to the buffer mode:
- line-buffering: the entire output buffer is flushed
whenever a newline is output, the buffer overflows,
a
hFlushis issued, or the handle is closed. - block-buffering: the entire buffer is written out whenever it
overflows, a
hFlushis issued, or the handle is closed. - no-buffering: output is written immediately, and never stored in the buffer.
An implementation is free to flush the buffer more frequently, but not less frequently, than specified above. The output buffer is emptied as soon as it has been written out.
Similarly, input occurs according to the buffer mode for the handle:
- line-buffering: when the buffer for the handle is not empty, the next item is obtained from the buffer; otherwise, when the buffer is empty, characters up to and including the next newline character are read into the buffer. No characters are available until the newline character is available or the buffer is full.
- block-buffering: when the buffer for the handle becomes empty, the next block of data is read into the buffer.
- no-buffering: the next input item is read and returned.
The
hLookAheadoperation implies that even a no-buffered handle may require a one-character buffer.
The default buffering mode when a handle is opened is implementation-dependent and may depend on the file system object which is attached to that handle. For most implementations, physical files will normally be block-buffered and terminals will normally be line-buffered.
Constructors
| NoBuffering | buffering is disabled if possible. |
| LineBuffering | line-buffering should be enabled if possible. |
| BlockBuffering (Maybe Int) | block-buffering should be enabled if possible.
The size of the buffer is |
Instances
| Read BufferMode | Since: base-4.2.0.0 |
Defined in GHC.IO.Handle.Types Methods readsPrec :: Int -> ReadS BufferMode # readList :: ReadS [BufferMode] # readPrec :: ReadPrec BufferMode # readListPrec :: ReadPrec [BufferMode] # | |
| Show BufferMode | Since: base-4.2.0.0 |
Defined in GHC.IO.Handle.Types Methods showsPrec :: Int -> BufferMode -> ShowS # show :: BufferMode -> String # showList :: [BufferMode] -> ShowS # | |
| Eq BufferMode | Since: base-4.2.0.0 |
Defined in GHC.IO.Handle.Types | |
| Ord BufferMode | Since: base-4.2.0.0 |
Defined in GHC.IO.Handle.Types Methods compare :: BufferMode -> BufferMode -> Ordering # (<) :: BufferMode -> BufferMode -> Bool # (<=) :: BufferMode -> BufferMode -> Bool # (>) :: BufferMode -> BufferMode -> Bool # (>=) :: BufferMode -> BufferMode -> Bool # max :: BufferMode -> BufferMode -> BufferMode # min :: BufferMode -> BufferMode -> BufferMode # | |
universalNewlineMode :: NewlineMode #
Map '\r\n' into '\n' on input, and '\n' to the native newline
representation on output. This mode can be used on any platform, and
works with text files using any newline convention. The downside is
that readFile >>= writeFile might yield a different file.
universalNewlineMode = NewlineMode { inputNL = CRLF,
outputNL = nativeNewline }noNewlineTranslation :: NewlineMode #
Do no newline translation at all.
noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }nativeNewlineMode :: NewlineMode #
Use the native newline representation on both input and output
nativeNewlineMode = NewlineMode { inputNL = nativeNewline
outputNL = nativeNewline }A mode that determines the effect of hSeek hdl mode i.
Constructors
| AbsoluteSeek | the position of |
| RelativeSeek | the position of |
| SeekFromEnd | the position of |
Instances
| Enum SeekMode | Since: base-4.2.0.0 |
| Ix SeekMode | Since: base-4.2.0.0 |
Defined in GHC.IO.Device Methods range :: (SeekMode, SeekMode) -> [SeekMode] # index :: (SeekMode, SeekMode) -> SeekMode -> Int # unsafeIndex :: (SeekMode, SeekMode) -> SeekMode -> Int # inRange :: (SeekMode, SeekMode) -> SeekMode -> Bool # rangeSize :: (SeekMode, SeekMode) -> Int # unsafeRangeSize :: (SeekMode, SeekMode) -> Int # | |
| Read SeekMode | Since: base-4.2.0.0 |
| Show SeekMode | Since: base-4.2.0.0 |
| Eq SeekMode | Since: base-4.2.0.0 |
| Ord SeekMode | Since: base-4.2.0.0 |
Defined in GHC.IO.Device | |
data TextEncoding #
A TextEncoding is a specification of a conversion scheme
between sequences of bytes and sequences of Unicode characters.
For example, UTF-8 is an encoding of Unicode characters into a sequence
of bytes. The TextEncoding for UTF-8 is utf8.
Instances
| Show TextEncoding | Since: base-4.3.0.0 |
Defined in GHC.IO.Encoding.Types Methods showsPrec :: Int -> TextEncoding -> ShowS # show :: TextEncoding -> String # showList :: [TextEncoding] -> ShowS # | |
type IOError = IOException #
The Haskell 2010 type for exceptions in the IO monad.
Any I/O operation may raise an IOException instead of returning a result.
For a more general type of exception, including also those that arise
in pure code, see Exception.
In Haskell 2010, this is an opaque type.
userError :: String -> IOError #
Construct an IOException value with a string describing the error.
The fail method of the IO instance of the Monad class raises a
userError, thus:
instance Monad IO where ... fail s = ioError (userError s)
sequence_ :: (Foldable t, Monad m) => t (m a) -> m () #
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.
sequence_ is just like sequenceA_, but specialised to monadic
actions.
or :: Foldable t => t Bool -> Bool #
or returns the disjunction of a container of Bools. For the
result to be False, the container must be finite; True, however,
results from a True value finitely far from the left end.
Examples
Basic usage:
>>>or []False
>>>or [True]True
>>>or [False]False
>>>or [True, True, False]True
>>>or (True : repeat False) -- Infinite list [True,False,False,False,...True
>>>or (repeat False)* Hangs forever *
notElem :: (Foldable t, Eq a) => a -> t a -> Bool infix 4 #
notElem is the negation of elem.
Examples
Basic usage:
>>>3 `notElem` []True
>>>3 `notElem` [1,2]True
>>>3 `notElem` [1,2,3,4,5]False
For infinite structures, notElem terminates if the value exists at a
finite distance from the left side of the structure:
>>>3 `notElem` [1..]False
>>>3 `notElem` ([4..] ++ [3])* Hangs forever *
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a #
The least element of a non-empty structure with respect to the given comparison function.
Examples
Basic usage:
>>>minimumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"!"
WARNING: This function is partial for possibly-empty structures like lists.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a #
The largest element of a non-empty structure with respect to the given comparison function.
Examples
Basic usage:
>>>maximumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"Longest"
WARNING: This function is partial for possibly-empty structures like lists.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b] #
Map a function over all the elements of a container and concatenate the resulting lists.
Examples
Basic usage:
>>>concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
>>>concatMap (take 3) (Just [1..])[1,2,3]
concat :: Foldable t => t [a] -> [a] #
The concatenation of all the elements of a container of lists.
Examples
Basic usage:
>>>concat (Just [1, 2, 3])[1,2,3]
>>>concat (Left 42)[]
>>>concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
asum :: (Foldable t, Alternative f) => t (f a) -> f a #
The sum of a collection of actions, generalizing concat.
asum is just like msum, but generalised to Alternative.
Examples
Basic usage:
>>>asum [Just "Hello", Nothing, Just "World"]Just "Hello"
any :: Foldable t => (a -> Bool) -> t a -> Bool #
Determines whether any element of the structure satisfies the predicate.
Examples
Basic usage:
>>>any (> 3) []False
>>>any (> 3) [1,2]False
>>>any (> 3) [1,2,3,4,5]True
>>>any (> 3) [1..]True
>>>any (> 3) [0, -1..]* Hangs forever *
and :: Foldable t => t Bool -> Bool #
and returns the conjunction of a container of Bools. For the
result to be True, the container must be finite; False, however,
results from a False value finitely far from the left end.
Examples
Basic usage:
>>>and []True
>>>and [True]True
>>>and [False]False
>>>and [True, True, False]False
>>>and (False : repeat True) -- Infinite list [False,True,True,True,...False
>>>and (repeat True)* Hangs forever *
all :: Foldable t => (a -> Bool) -> t a -> Bool #
Determines whether all elements of the structure satisfy the predicate.
Examples
Basic usage:
>>>all (> 3) []True
>>>all (> 3) [1,2]False
>>>all (> 3) [1,2,3,4,5]False
>>>all (> 3) [1..]False
>>>all (> 3) [4..]* Hangs forever *
zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h] #
words breaks a string up into a list of words, which were delimited
by white space.
>>>words "Lorem ipsum\ndolor"["Lorem","ipsum","dolor"]
union :: Eq a => [a] -> [a] -> [a] #
The union function returns the list union of the two lists.
For example,
>>>"dog" `union` "cow""dogcw"
Duplicates, and elements of the first list, are removed from the
the second list, but if the first list contains duplicates, so will
the result.
It is a special case of unionBy, which allows the programmer to supply
their own equality test.
unfoldr :: (b -> Maybe (a, b)) -> b -> [a] #
The unfoldr function is a `dual' to foldr: while foldr
reduces a list to a summary value, unfoldr builds a list from
a seed value. The function takes the element and returns Nothing
if it is done producing the list or returns Just (a,b), in which
case, a is a prepended to the list and b is used as the next
element in a recursive call. For example,
iterate f == unfoldr (\x -> Just (x, f x))
In some cases, unfoldr can undo a foldr operation:
unfoldr f' (foldr f z xs) == xs
if the following holds:
f' (f x y) = Just (x,y) f' z = Nothing
A simple use of unfoldr:
>>>unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10[10,9,8,7,6,5,4,3,2,1]
The transpose function transposes the rows and columns of its argument.
For example,
>>>transpose [[1,2,3],[4,5,6]][[1,4],[2,5],[3,6]]
If some of the rows are shorter than the following rows, their elements are skipped:
>>>transpose [[10,11],[20],[],[30,31,32]][[10,20,30],[11,31],[32]]
subsequences :: [a] -> [[a]] #
The subsequences function returns the list of all subsequences of the argument.
>>>subsequences "abc"["","a","b","ab","c","ac","bc","abc"]
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a] #
\(\mathcal{O}(\min(m,n))\). The stripPrefix function drops the given
prefix from a list. It returns Nothing if the list did not start with the
prefix given, or Just the list after the prefix, if it does.
>>>stripPrefix "foo" "foobar"Just "bar"
>>>stripPrefix "foo" "foo"Just ""
>>>stripPrefix "foo" "barfoo"Nothing
>>>stripPrefix "foo" "barfoobaz"Nothing
sortOn :: Ord b => (a -> b) -> [a] -> [a] #
Sort a list by comparing the results of a key function applied to each
element. sortOn f is equivalent to sortBy (comparing f), but has the
performance advantage of only evaluating f once for each element in the
input list. This is called the decorate-sort-undecorate paradigm, or
Schwartzian transform.
Elements are arranged from lowest to highest, keeping duplicates in the order they appeared in the input.
>>>sortOn fst [(2, "world"), (4, "!"), (1, "Hello")][(1,"Hello"),(2,"world"),(4,"!")]
Since: base-4.8.0.0
permutations :: [a] -> [[a]] #
The permutations function returns the list of all permutations of the argument.
>>>permutations "abc"["abc","bac","cba","bca","cab","acb"]
partition :: (a -> Bool) -> [a] -> ([a], [a]) #
The partition function takes a predicate and a list, and returns
the pair of lists of elements which do and do not satisfy the
predicate, respectively; i.e.,
partition p xs == (filter p xs, filter (not . p) xs)
>>>partition (`elem` "aeiou") "Hello World!"("eoo","Hll Wrld!")
\(\mathcal{O}(n^2)\). The nub function removes duplicate elements from a
list. In particular, it keeps only the first occurrence of each element. (The
name nub means `essence'.) It is a special case of nubBy, which allows
the programmer to supply their own equality test.
>>>nub [1,2,3,4,3,2,1,2,4,3,5][1,2,3,4,5]
lines breaks a string up into a list of strings at newline
characters. The resulting strings do not contain newlines.
Note that after splitting the string at newline characters, the last part of the string is considered a line even if it doesn't end with a newline. For example,
>>>lines ""[]
>>>lines "\n"[""]
>>>lines "one"["one"]
>>>lines "one\n"["one"]
>>>lines "one\n\n"["one",""]
>>>lines "one\ntwo"["one","two"]
>>>lines "one\ntwo\n"["one","two"]
Thus contains at least as many elements as newlines in lines ss.
isSuffixOf :: Eq a => [a] -> [a] -> Bool #
The isSuffixOf function takes two lists and returns True iff
the first list is a suffix of the second. The second list must be
finite.
>>>"ld!" `isSuffixOf` "Hello World!"True
>>>"World" `isSuffixOf` "Hello World!"False
isPrefixOf :: Eq a => [a] -> [a] -> Bool #
\(\mathcal{O}(\min(m,n))\). The isPrefixOf function takes two lists and
returns True iff the first list is a prefix of the second.
>>>"Hello" `isPrefixOf` "Hello World!"True
>>>"Hello" `isPrefixOf` "Wello Horld!"False
intersperse :: a -> [a] -> [a] #
\(\mathcal{O}(n)\). The intersperse function takes an element and a list
and `intersperses' that element between the elements of the list. For
example,
>>>intersperse ',' "abcde""a,b,c,d,e"
intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] #
The intersectBy function is the non-overloaded version of intersect.
intersect :: Eq a => [a] -> [a] -> [a] #
The intersect function takes the list intersection of two lists.
For example,
>>>[1,2,3,4] `intersect` [2,4,6,8][2,4]
If the first list contains duplicates, so will the result.
>>>[1,2,2,3,4] `intersect` [6,4,4,2][2,2,4]
It is a special case of intersectBy, which allows the programmer to
supply their own equality test. If the element is found in both the first
and the second list, the element from the first list will be used.
intercalate :: [a] -> [[a]] -> [a] #
intercalate xs xss is equivalent to (.
It inserts the list concat (intersperse xs xss))xs in between the lists in xss and concatenates the
result.
>>>intercalate ", " ["Lorem", "ipsum", "dolor"]"Lorem, ipsum, dolor"
insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a] #
\(\mathcal{O}(n)\). The non-overloaded version of insert.
insert :: Ord a => a -> [a] -> [a] #
\(\mathcal{O}(n)\). The insert function takes an element and a list and
inserts the element into the list at the first position where it is less than
or equal to the next element. In particular, if the list is sorted before the
call, the result will also be sorted. It is a special case of insertBy,
which allows the programmer to supply their own comparison function.
>>>insert 4 [1,2,3,5,6,7][1,2,3,4,5,6,7]
group :: Eq a => [a] -> [[a]] #
The group function takes a list and returns a list of lists such
that the concatenation of the result is equal to the argument. Moreover,
each sublist in the result contains only equal elements. For example,
>>>group "Mississippi"["M","i","ss","i","ss","i","pp","i"]
It is a special case of groupBy, which allows the programmer to supply
their own equality test.
genericTake :: Integral i => i -> [a] -> [a] #
The genericTake function is an overloaded version of take, which
accepts any Integral value as the number of elements to take.
genericSplitAt :: Integral i => i -> [a] -> ([a], [a]) #
The genericSplitAt function is an overloaded version of splitAt, which
accepts any Integral value as the position at which to split.
genericReplicate :: Integral i => i -> a -> [a] #
The genericReplicate function is an overloaded version of replicate,
which accepts any Integral value as the number of repetitions to make.
genericLength :: Num i => [a] -> i #
\(\mathcal{O}(n)\). The genericLength function is an overloaded version
of length. In particular, instead of returning an Int, it returns any
type which is an instance of Num. It is, however, less efficient than
length.
>>>genericLength [1, 2, 3] :: Int3>>>genericLength [1, 2, 3] :: Float3.0
genericIndex :: Integral i => [a] -> i -> a #
The genericIndex function is an overloaded version of !!, which
accepts any Integral value as the index.
genericDrop :: Integral i => i -> [a] -> [a] #
The genericDrop function is an overloaded version of drop, which
accepts any Integral value as the number of elements to drop.
findIndices :: (a -> Bool) -> [a] -> [Int] #
The findIndices function extends findIndex, by returning the
indices of all elements satisfying the predicate, in ascending order.
>>>findIndices (`elem` "aeiou") "Hello World!"[1,4,7]
elemIndices :: Eq a => a -> [a] -> [Int] #
The elemIndices function extends elemIndex, by returning the
indices of all elements equal to the query element, in ascending order.
>>>elemIndices 'o' "Hello World"[4,7]
dropWhileEnd :: (a -> Bool) -> [a] -> [a] #
The dropWhileEnd function drops the largest suffix of a list
in which the given predicate holds for all elements. For example:
>>>dropWhileEnd isSpace "foo\n""foo"
>>>dropWhileEnd isSpace "foo bar""foo bar"
dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefinedSince: base-4.5.0.0
deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] #
The deleteFirstsBy function takes a predicate and two lists and
returns the first list with the first occurrence of each element of
the second list removed.
(\\) :: Eq a => [a] -> [a] -> [a] infix 5 #
The \\ function is list difference (non-associative).
In the result of xs \\ ys, the first occurrence of each element of
ys in turn (if any) has been removed from xs. Thus
(xs ++ ys) \\ xs == ys.
>>>"Hello World!" \\ "ell W""Hoorld!"
It is a special case of deleteFirstsBy, which allows the programmer
to supply their own equality test.
The Down type allows you to reverse sort order conveniently. A value of type
contains a value of type Down aa (represented as ).Down a
If a has an instance associated with it then comparing two
values thus wrapped will give you the opposite of their normal sort order.
This is particularly useful when sorting in generalised list comprehensions,
as in: Ordthen sortWith by .Down x
>>>compare True FalseGT
>>>compare (Down True) (Down False)LT
If a has a instance then the wrapped instance also respects
the reversed ordering by exchanging the values of Bounded and
minBound.maxBound
>>>minBound :: Int-9223372036854775808
>>>minBound :: Down IntDown 9223372036854775807
All other instances of behave as they do for Down aa.
Since: base-4.6.0.0
Instances
| FromJSON1 Down | Since: aeson-2.2.0.0 |
| ToJSON1 Down | Since: aeson-2.2.0.0 |
Defined in Data.Aeson.Types.ToJSON Methods liftToJSON :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> Down a -> Value # liftToJSONList :: (a -> Bool) -> (a -> Value) -> ([a] -> Value) -> [Down a] -> Value # liftToEncoding :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> Down a -> Encoding # liftToEncodingList :: (a -> Bool) -> (a -> Encoding) -> ([a] -> Encoding) -> [Down a] -> Encoding # liftOmitField :: (a -> Bool) -> Down a -> Bool # | |
| Foldable Down | Since: base-4.12.0.0 |
Defined in Data.Foldable Methods fold :: Monoid m => Down m -> m # foldMap :: Monoid m => (a -> m) -> Down a -> m # foldMap' :: Monoid m => (a -> m) -> Down a -> m # foldr :: (a -> b -> b) -> b -> Down a -> b # foldr' :: (a -> b -> b) -> b -> Down a -> b # foldl :: (b -> a -> b) -> b -> Down a -> b # foldl' :: (b -> a -> b) -> b -> Down a -> b # foldr1 :: (a -> a -> a) -> Down a -> a # foldl1 :: (a -> a -> a) -> Down a -> a # elem :: Eq a => a -> Down a -> Bool # maximum :: Ord a => Down a -> a # | |
| Eq1 Down | Since: base-4.12.0.0 |
| Ord1 Down | Since: base-4.12.0.0 |
Defined in Data.Functor.Classes | |
| Read1 Down | Since: base-4.12.0.0 |
Defined in Data.Functor.Classes | |
| Show1 Down | Since: base-4.12.0.0 |
| Traversable Down | Since: base-4.12.0.0 |
| Applicative Down | Since: base-4.11.0.0 |
| Functor Down | Since: base-4.11.0.0 |
| Monad Down | Since: base-4.11.0.0 |
| Generic1 Down | |
| Unbox a => Vector Vector (Down a) | |
Defined in Data.Vector.Unboxed.Base Methods basicUnsafeFreeze :: Mutable Vector s (Down a) -> ST s (Vector (Down a)) # basicUnsafeThaw :: Vector (Down a) -> ST s (Mutable Vector s (Down a)) # basicLength :: Vector (Down a) -> Int # basicUnsafeSlice :: Int -> Int -> Vector (Down a) -> Vector (Down a) # basicUnsafeIndexM :: Vector (Down a) -> Int -> Box (Down a) # basicUnsafeCopy :: Mutable Vector s (Down a) -> Vector (Down a) -> ST s () # | |
| Unbox a => MVector MVector (Down a) | |
Defined in Data.Vector.Unboxed.Base Methods basicLength :: MVector s (Down a) -> Int # basicUnsafeSlice :: Int -> Int -> MVector s (Down a) -> MVector s (Down a) # basicOverlaps :: MVector s (Down a) -> MVector s (Down a) -> Bool # basicUnsafeNew :: Int -> ST s (MVector s (Down a)) # basicInitialize :: MVector s (Down a) -> ST s () # basicUnsafeReplicate :: Int -> Down a -> ST s (MVector s (Down a)) # basicUnsafeRead :: MVector s (Down a) -> Int -> ST s (Down a) # basicUnsafeWrite :: MVector s (Down a) -> Int -> Down a -> ST s () # basicClear :: MVector s (Down a) -> ST s () # basicSet :: MVector s (Down a) -> Down a -> ST s () # basicUnsafeCopy :: MVector s (Down a) -> MVector s (Down a) -> ST s () # basicUnsafeMove :: MVector s (Down a) -> MVector s (Down a) -> ST s () # basicUnsafeGrow :: MVector s (Down a) -> Int -> ST s (MVector s (Down a)) # | |
| FromJSON a => FromJSON (Down a) | Since: aeson-2.2.0.0 |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON a => ToJSON (Down a) | Since: aeson-2.2.0.0 |
| Data a => Data (Down a) | Since: base-4.12.0.0 |
Defined in Data.Data Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Down a -> c (Down a) # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c (Down a) # toConstr :: Down a -> Constr # dataTypeOf :: Down a -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c (Down a)) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c (Down a)) # gmapT :: (forall b. Data b => b -> b) -> Down a -> Down a # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Down a -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Down a -> r # gmapQ :: (forall d. Data d => d -> u) -> Down a -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Down a -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Down a -> m (Down a) # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Down a -> m (Down a) # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Down a -> m (Down a) # | |
| Storable a => Storable (Down a) | Since: base-4.14.0.0 |
| Monoid a => Monoid (Down a) | Since: base-4.11.0.0 |
| Semigroup a => Semigroup (Down a) | Since: base-4.11.0.0 |
| Bits a => Bits (Down a) | Since: base-4.14.0.0 |
Defined in Data.Ord Methods (.&.) :: Down a -> Down a -> Down a # (.|.) :: Down a -> Down a -> Down a # xor :: Down a -> Down a -> Down a # complement :: Down a -> Down a # shift :: Down a -> Int -> Down a # rotate :: Down a -> Int -> Down a # setBit :: Down a -> Int -> Down a # clearBit :: Down a -> Int -> Down a # complementBit :: Down a -> Int -> Down a # testBit :: Down a -> Int -> Bool # bitSizeMaybe :: Down a -> Maybe Int # shiftL :: Down a -> Int -> Down a # unsafeShiftL :: Down a -> Int -> Down a # shiftR :: Down a -> Int -> Down a # unsafeShiftR :: Down a -> Int -> Down a # rotateL :: Down a -> Int -> Down a # | |
| FiniteBits a => FiniteBits (Down a) | Since: base-4.14.0.0 |
Defined in Data.Ord Methods finiteBitSize :: Down a -> Int # countLeadingZeros :: Down a -> Int # countTrailingZeros :: Down a -> Int # | |
| Bounded a => Bounded (Down a) | Swaps Since: base-4.14.0.0 |
| Floating a => Floating (Down a) | Since: base-4.14.0.0 |
| RealFloat a => RealFloat (Down a) | Since: base-4.14.0.0 |
Defined in Data.Ord Methods floatRadix :: Down a -> Integer # floatDigits :: Down a -> Int # floatRange :: Down a -> (Int, Int) # decodeFloat :: Down a -> (Integer, Int) # encodeFloat :: Integer -> Int -> Down a # significand :: Down a -> Down a # scaleFloat :: Int -> Down a -> Down a # isInfinite :: Down a -> Bool # isDenormalized :: Down a -> Bool # isNegativeZero :: Down a -> Bool # | |
| Generic (Down a) | |
| Ix a => Ix (Down a) | Since: base-4.14.0.0 |
| Num a => Num (Down a) | Since: base-4.11.0.0 |
| Read a => Read (Down a) | This instance would be equivalent to the derived instances of the
Since: base-4.7.0.0 |
| Fractional a => Fractional (Down a) | Since: base-4.14.0.0 |
| Real a => Real (Down a) | Since: base-4.14.0.0 |
Defined in Data.Ord Methods toRational :: Down a -> Rational # | |
| RealFrac a => RealFrac (Down a) | Since: base-4.14.0.0 |
| Show a => Show (Down a) | This instance would be equivalent to the derived instances of the
Since: base-4.7.0.0 |
| Eq a => Eq (Down a) | Since: base-4.6.0.0 |
| Ord a => Ord (Down a) | Since: base-4.6.0.0 |
| Prim a => Prim (Down a) | Since: primitive-0.6.5.0 |
Defined in Data.Primitive.Types Methods sizeOfType# :: Proxy (Down a) -> Int# # alignmentOfType# :: Proxy (Down a) -> Int# # alignment# :: Down a -> Int# # indexByteArray# :: ByteArray# -> Int# -> Down a # readByteArray# :: MutableByteArray# s -> Int# -> State# s -> (# State# s, Down a #) # writeByteArray# :: MutableByteArray# s -> Int# -> Down a -> State# s -> State# s # setByteArray# :: MutableByteArray# s -> Int# -> Int# -> Down a -> State# s -> State# s # indexOffAddr# :: Addr# -> Int# -> Down a # readOffAddr# :: Addr# -> Int# -> State# s -> (# State# s, Down a #) # writeOffAddr# :: Addr# -> Int# -> Down a -> State# s -> State# s # setOffAddr# :: Addr# -> Int# -> Int# -> Down a -> State# s -> State# s # | |
| Unbox a => Unbox (Down a) | |
Defined in Data.Vector.Unboxed.Base | |
| type Rep1 Down | Since: base-4.12.0.0 |
Defined in GHC.Generics | |
| newtype MVector s (Down a) | |
Defined in Data.Vector.Unboxed.Base | |
| type Rep (Down a) | Since: base-4.12.0.0 |
Defined in GHC.Generics | |
| newtype Vector (Down a) | |
Defined in Data.Vector.Unboxed.Base | |
comparing :: Ord a => (b -> a) -> b -> b -> Ordering #
comparing p x y = compare (p x) (p y)
Useful combinator for use in conjunction with the xxxBy family
of functions from Data.List, for example:
... sortBy (comparing fst) ...
clamp :: Ord a => (a, a) -> a -> a #
clamp (low, high) a = min high (max a low)
Function for ensursing the value a is within the inclusive bounds given by
low and high. If it is, a is returned unchanged. The result
is otherwise low if a <= low, or high if high <= a.
When clamp is used at Double and Float, it has NaN propagating semantics in
its second argument. That is, clamp (l,h) NaN = NaN, but clamp (NaN, NaN)
x = x.
>>>clamp (0, 10) 22
>>>clamp ('a', 'm') 'x''m'
isSeparator :: Char -> Bool #
Selects Unicode space and separator characters.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Separator".
Examples
Basic usage:
>>>isSeparator 'a'False>>>isSeparator '6'False>>>isSeparator ' 'True
Warning: newlines and tab characters are not considered separators.
>>>isSeparator '\n'False>>>isSeparator '\t'False
But some more exotic characters are (like HTML's ):
>>>isSeparator '\160'True
Selects Unicode numeric characters, including digits from various scripts, Roman numerals, et cetera.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Number".
Examples
Basic usage:
>>>isNumber 'a'False>>>isNumber '%'False>>>isNumber '3'True
ASCII '0' through '9' are all numbers:
>>>and $ map isNumber ['0'..'9']True
Unicode Roman numerals are "numbers" as well:
>>>isNumber 'Ⅸ'True
Selects Unicode mark characters, for example accents and the like, which combine with preceding characters.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Mark".
Examples
Basic usage:
>>>isMark 'a'False>>>isMark '0'False
Combining marks such as accent characters usually need to follow another character before they become printable:
>>>map isMark "ò"[False,True]
Puns are not necessarily supported:
>>>isMark '✓'False
Selects alphabetic Unicode characters (lower-case, upper-case and
title-case letters, plus letters of caseless scripts and
modifiers letters). This function is equivalent to
isAlpha.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Letter".
Examples
Basic usage:
>>>isLetter 'a'True>>>isLetter 'A'True>>>isLetter 'λ'True>>>isLetter '0'False>>>isLetter '%'False>>>isLetter '♥'False>>>isLetter '\31'False
Ensure that isLetter and isAlpha are equivalent.
>>>let chars = [(chr 0)..]>>>let letters = map isLetter chars>>>let alphas = map isAlpha chars>>>letters == alphasTrue
digitToInt :: Char -> Int #
Convert a single digit Char to the corresponding Int. This
function fails unless its argument satisfies isHexDigit, but
recognises both upper- and lower-case hexadecimal digits (that
is, '0'..'9', 'a'..'f', 'A'..'F').
Examples
Characters '0' through '9' are converted properly to
0..9:
>>>map digitToInt ['0'..'9'][0,1,2,3,4,5,6,7,8,9]
Both upper- and lower-case 'A' through 'F' are converted
as well, to 10..15.
>>>map digitToInt ['a'..'f'][10,11,12,13,14,15]>>>map digitToInt ['A'..'F'][10,11,12,13,14,15]
Anything else throws an exception:
>>>digitToInt 'G'*** Exception: Char.digitToInt: not a digit 'G'>>>digitToInt '♥'*** Exception: Char.digitToInt: not a digit '\9829'
partitionEithers :: [Either a b] -> ([a], [b]) #
Partitions a list of Either into two lists.
All the Left elements are extracted, in order, to the first
component of the output. Similarly the Right elements are extracted
to the second component of the output.
Examples
Basic usage:
>>>let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]>>>partitionEithers list(["foo","bar","baz"],[3,7])
The pair returned by should be the same
pair as partitionEithers x(:lefts x, rights x)
>>>let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]>>>partitionEithers list == (lefts list, rights list)True
isRight :: Either a b -> Bool #
Return True if the given value is a Right-value, False otherwise.
Examples
Basic usage:
>>>isRight (Left "foo")False>>>isRight (Right 3)True
Assuming a Left value signifies some sort of error, we can use
isRight to write a very simple reporting function that only
outputs "SUCCESS" when a computation has succeeded.
This example shows how isRight might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>import Control.Monad ( when )>>>let report e = when (isRight e) $ putStrLn "SUCCESS">>>report (Left "parse error")>>>report (Right 1)SUCCESS
Since: base-4.7.0.0
isLeft :: Either a b -> Bool #
Return True if the given value is a Left-value, False otherwise.
Examples
Basic usage:
>>>isLeft (Left "foo")True>>>isLeft (Right 3)False
Assuming a Left value signifies some sort of error, we can use
isLeft to write a very simple error-reporting function that does
absolutely nothing in the case of success, and outputs "ERROR" if
any error occurred.
This example shows how isLeft might be used to avoid pattern
matching when one does not care about the value contained in the
constructor:
>>>import Control.Monad ( when )>>>let report e = when (isLeft e) $ putStrLn "ERROR">>>report (Right 1)>>>report (Left "parse error")ERROR
Since: base-4.7.0.0
fromRight :: b -> Either a b -> b #
Return the contents of a Right-value or a default value otherwise.
Examples
Basic usage:
>>>fromRight 1 (Right 3)3>>>fromRight 1 (Left "foo")1
Since: base-4.10.0.0
fromLeft :: a -> Either a b -> a #
Return the contents of a Left-value or a default value otherwise.
Examples
Basic usage:
>>>fromLeft 1 (Left 3)3>>>fromLeft 1 (Right "foo")1
Since: base-4.10.0.0
either :: (a -> c) -> (b -> c) -> Either a b -> c #
Case analysis for the Either type.
If the value is , apply the first function to Left aa;
if it is , apply the second function to Right bb.
Examples
We create two values of type , one using the
Either String IntLeft constructor and another using the Right constructor. Then
we apply "either" the length function (if we have a String)
or the "times-two" function (if we have an Int):
>>>let s = Left "foo" :: Either String Int>>>let n = Right 3 :: Either String Int>>>either length (*2) s3>>>either length (*2) n6
See openFile
Constructors
| ReadMode | |
| WriteMode | |
| AppendMode | |
| ReadWriteMode |
readLitChar :: ReadS Char #
Read a string representation of a character, using Haskell source-language escape conventions, and convert it to the character that it encodes. For example:
readLitChar "\\nHello" = [('\n', "Hello")]lexLitChar :: ReadS String #
Read a string representation of a character, using Haskell source-language escape conventions. For example:
lexLitChar "\\nHello" = [("\\n", "Hello")]data GeneralCategory #
Unicode General Categories (column 2 of the UnicodeData table) in the order they are listed in the Unicode standard (the Unicode Character Database, in particular).
Examples
Basic usage:
>>>:t OtherLetterOtherLetter :: GeneralCategory
Eq instance:
>>>UppercaseLetter == UppercaseLetterTrue>>>UppercaseLetter == LowercaseLetterFalse
Ord instance:
>>>NonSpacingMark <= MathSymbolTrue
Enum instance:
>>>enumFromTo ModifierLetter SpacingCombiningMark[ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark]
Read instance:
>>>read "DashPunctuation" :: GeneralCategoryDashPunctuation>>>read "17" :: GeneralCategory*** Exception: Prelude.read: no parse
Show instance:
>>>show EnclosingMark"EnclosingMark"
Bounded instance:
>>>minBound :: GeneralCategoryUppercaseLetter>>>maxBound :: GeneralCategoryNotAssigned
Ix instance:
>>>import Data.Ix ( index )>>>index (OtherLetter,Control) FinalQuote12>>>index (OtherLetter,Control) Format*** Exception: Error in array index
Constructors
| UppercaseLetter | Lu: Letter, Uppercase |
| LowercaseLetter | Ll: Letter, Lowercase |
| TitlecaseLetter | Lt: Letter, Titlecase |
| ModifierLetter | Lm: Letter, Modifier |
| OtherLetter | Lo: Letter, Other |
| NonSpacingMark | Mn: Mark, Non-Spacing |
| SpacingCombiningMark | Mc: Mark, Spacing Combining |
| EnclosingMark | Me: Mark, Enclosing |
| DecimalNumber | Nd: Number, Decimal |
| LetterNumber | Nl: Number, Letter |
| OtherNumber | No: Number, Other |
| ConnectorPunctuation | Pc: Punctuation, Connector |
| DashPunctuation | Pd: Punctuation, Dash |
| OpenPunctuation | Ps: Punctuation, Open |
| ClosePunctuation | Pe: Punctuation, Close |
| InitialQuote | Pi: Punctuation, Initial quote |
| FinalQuote | Pf: Punctuation, Final quote |
| OtherPunctuation | Po: Punctuation, Other |
| MathSymbol | Sm: Symbol, Math |
| CurrencySymbol | Sc: Symbol, Currency |
| ModifierSymbol | Sk: Symbol, Modifier |
| OtherSymbol | So: Symbol, Other |
| Space | Zs: Separator, Space |
| LineSeparator | Zl: Separator, Line |
| ParagraphSeparator | Zp: Separator, Paragraph |
| Control | Cc: Other, Control |
| Format | Cf: Other, Format |
| Surrogate | Cs: Other, Surrogate |
| PrivateUse | Co: Other, Private Use |
| NotAssigned | Cn: Other, Not Assigned |
Instances
Convert a letter to the corresponding upper-case letter, if any. Any other character is returned unchanged.
Convert a letter to the corresponding title-case or upper-case letter, if any. (Title case differs from upper case only for a small number of ligature letters.) Any other character is returned unchanged.
Selects upper-case or title-case alphabetic Unicode characters (letters). Title case is used by a small number of letter ligatures like the single-character form of Lj.
Selects Unicode symbol characters, including mathematical and currency symbols.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Symbol".
Examples
Basic usage:
>>>isSymbol 'a'False>>>isSymbol '6'False>>>isSymbol '='True
The definition of "math symbol" may be a little counter-intuitive depending on one's background:
>>>isSymbol '+'True>>>isSymbol '-'False
isPunctuation :: Char -> Bool #
Selects Unicode punctuation characters, including various kinds of connectors, brackets and quotes.
This function returns True if its argument has one of the
following GeneralCategorys, or False otherwise:
ConnectorPunctuationDashPunctuationOpenPunctuationClosePunctuationInitialQuoteFinalQuoteOtherPunctuation
These classes are defined in the Unicode Character Database, part of the Unicode standard. The same document defines what is and is not a "Punctuation".
Examples
Basic usage:
>>>isPunctuation 'a'False>>>isPunctuation '7'False>>>isPunctuation '♥'False>>>isPunctuation '"'True>>>isPunctuation '?'True>>>isPunctuation '—'True
Selects printable Unicode characters (letters, numbers, marks, punctuation, symbols and spaces).
isOctDigit :: Char -> Bool #
Selects ASCII octal digits, i.e. '0'..'7'.
Selects the first 256 characters of the Unicode character set, corresponding to the ISO 8859-1 (Latin-1) character set.
isHexDigit :: Char -> Bool #
Selects ASCII hexadecimal digits,
i.e. '0'..'9', 'a'..'f', 'A'..'F'.
Selects control characters, which are the non-printing characters of the Latin-1 subset of Unicode.
isAsciiUpper :: Char -> Bool #
isAsciiLower :: Char -> Bool #
Selects the first 128 characters of the Unicode character set, corresponding to the ASCII character set.
isAlphaNum :: Char -> Bool #
Selects alphabetic or numeric Unicode characters.
Note that numeric digits outside the ASCII range, as well as numeric
characters which aren't digits, are selected by this function but not by
isDigit. Such characters may be part of identifiers but are not used by
the printer and reader to represent numbers.
generalCategory :: Char -> GeneralCategory #
The Unicode general category of the character. This relies on the
Enum instance of GeneralCategory, which must remain in the
same order as the categories are presented in the Unicode
standard.
Examples
Basic usage:
>>>generalCategory 'a'LowercaseLetter>>>generalCategory 'A'UppercaseLetter>>>generalCategory '0'DecimalNumber>>>generalCategory '%'OtherPunctuation>>>generalCategory '♥'OtherSymbol>>>generalCategory '\31'Control>>>generalCategory ' 'Space
showLitChar :: Char -> ShowS #
Convert a character to a string using only printable characters, using Haskell source-language escape conventions. For example:
showLitChar '\n' s = "\\n" ++ s
intToDigit :: Int -> Char #
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] #
The zipWith3 function takes a function which combines three
elements, as well as three lists and returns a list of the function applied
to corresponding elements, analogous to zipWith.
It is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
zipWith3 (,,) xs ys zs == zip3 xs ys zs zipWith3 f [x1,x2,x3..] [y1,y2,y3..] [z1,z2,z3..] == [f x1 y1 z1, f x2 y2 z2, f x3 y3 z3..]
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] #
\(\mathcal{O}(\min(m,n))\). zipWith generalises zip by zipping with the
function given as the first argument, instead of a tupling function.
zipWith (,) xs ys == zip xs ys zipWith f [x1,x2,x3..] [y1,y2,y3..] == [f x1 y1, f x2 y2, f x3 y3..]
For example, is applied to two lists to produce the list of
corresponding sums:zipWith (+)
>>>zipWith (+) [1, 2, 3] [4, 5, 6][5,7,9]
zipWith is right-lazy:
>>>let f = undefined>>>zipWith f [] undefined[]
zipWith is capable of list fusion, but it is restricted to its
first list argument and its resulting list.
unzip :: [(a, b)] -> ([a], [b]) #
unzip transforms a list of pairs into a list of first components
and a list of second components.
>>>unzip []([],[])>>>unzip [(1, 'a'), (2, 'b')]([1,2],"ab")
takeWhile :: (a -> Bool) -> [a] -> [a] #
takeWhile, applied to a predicate p and a list xs, returns the
longest prefix (possibly empty) of xs of elements that satisfy p.
>>>takeWhile (< 3) [1,2,3,4,1,2,3,4][1,2]>>>takeWhile (< 9) [1,2,3][1,2,3]>>>takeWhile (< 0) [1,2,3][]
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.
\(\mathcal{O}(1)\). Extract the elements after the head of a list, which must be non-empty.
>>>tail [1, 2, 3][2,3]>>>tail [1][]>>>tail []*** Exception: Prelude.tail: empty list
splitAt :: Int -> [a] -> ([a], [a]) #
splitAt n xs returns a tuple where first element is xs prefix of
length n and second element is the remainder of the list:
>>>splitAt 6 "Hello World!"("Hello ","World!")>>>splitAt 3 [1,2,3,4,5]([1,2,3],[4,5])>>>splitAt 1 [1,2,3]([1],[2,3])>>>splitAt 3 [1,2,3]([1,2,3],[])>>>splitAt 4 [1,2,3]([1,2,3],[])>>>splitAt 0 [1,2,3]([],[1,2,3])>>>splitAt (-1) [1,2,3]([],[1,2,3])
It is equivalent to ( when take n xs, drop n xs)n is not _|_
(splitAt _|_ xs = _|_).
splitAt is an instance of the more general genericSplitAt,
in which n may be of any integral type.
scanr1 :: (a -> a -> a) -> [a] -> [a] #
\(\mathcal{O}(n)\). scanr1 is a variant of scanr that has no starting
value argument.
>>>scanr1 (+) [1..4][10,9,7,4]>>>scanr1 (+) [][]>>>scanr1 (-) [1..4][-2,3,-1,4]>>>scanr1 (&&) [True, False, True, True][False,False,True,True]>>>scanr1 (||) [True, True, False, False][True,True,False,False]>>>force $ scanr1 (+) [1..]*** Exception: stack overflow
scanr :: (a -> b -> b) -> b -> [a] -> [b] #
\(\mathcal{O}(n)\). scanr is the right-to-left dual of scanl. Note that the order of parameters on the accumulating function are reversed compared to scanl.
Also note that
head (scanr f z xs) == foldr f z xs.
>>>scanr (+) 0 [1..4][10,9,7,4,0]>>>scanr (+) 42 [][42]>>>scanr (-) 100 [1..4][98,-97,99,-96,100]>>>scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]>>>force $ scanr (+) 0 [1..]*** Exception: stack overflow
scanl1 :: (a -> a -> a) -> [a] -> [a] #
\(\mathcal{O}(n)\). scanl1 is a variant of scanl that has no starting
value argument:
scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
>>>scanl1 (+) [1..4][1,3,6,10]>>>scanl1 (+) [][]>>>scanl1 (-) [1..4][1,-1,-4,-8]>>>scanl1 (&&) [True, False, True, True][True,False,False,False]>>>scanl1 (||) [False, False, True, True][False,False,True,True]>>>scanl1 (+) [1..]* Hangs forever *
scanl :: (b -> a -> b) -> b -> [a] -> [b] #
\(\mathcal{O}(n)\). scanl is similar to foldl, but returns a list of
successive reduced values from the left:
scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
Note that
last (scanl f z xs) == foldl f z xs
>>>scanl (+) 0 [1..4][0,1,3,6,10]>>>scanl (+) 42 [][42]>>>scanl (-) 100 [1..4][100,99,97,94,90]>>>scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']["foo","afoo","bafoo","cbafoo","dcbafoo"]>>>scanl (+) 0 [1..]* Hangs forever *
reverse xs returns the elements of xs in reverse order.
xs must be finite.
>>>reverse [][]>>>reverse [42][42]>>>reverse [2,5,7][7,5,2]>>>reverse [1..]* Hangs forever *
replicate :: Int -> a -> [a] #
replicate n x is a list of length n with x the value of
every element.
It is an instance of the more general genericReplicate,
in which n may be of any integral type.
>>>replicate 0 True[]>>>replicate (-1) True[]>>>replicate 4 True[True,True,True,True]
repeat x is an infinite list, with x the value of every element.
>>>take 20 $ repeat 17[17,17,17,17,17,17,17,17,17...
lookup :: Eq a => a -> [(a, b)] -> Maybe b #
\(\mathcal{O}(n)\). lookup key assocs looks up a key in an association
list.
>>>lookup 2 []Nothing>>>lookup 2 [(1, "first")]Nothing>>>lookup 2 [(1, "first"), (2, "second"), (3, "third")]Just "second"
\(\mathcal{O}(n)\). Extract the last element of a list, which must be finite and non-empty.
>>>last [1, 2, 3]3>>>last [1..]* Hangs forever *>>>last []*** Exception: Prelude.last: empty list
iterate :: (a -> a) -> a -> [a] #
iterate f x returns an infinite list of repeated applications
of f to x:
iterate f x == [x, f x, f (f x), ...]
Note that iterate is lazy, potentially leading to thunk build-up if
the consumer doesn't force each iterate. See iterate' for a strict
variant of this function.
>>>take 10 $ iterate not True[True,False,True,False...>>>take 10 $ iterate (+3) 42[42,45,48,51,54,57,60,63...
\(\mathcal{O}(n)\). Return all the elements of a list except the last one. The list must be non-empty.
>>>init [1, 2, 3][1,2]>>>init [1][]>>>init []*** Exception: Prelude.init: empty list
\(\mathcal{O}(1)\). Extract the first element of a list, which must be non-empty.
>>>head [1, 2, 3]1>>>head [1..]1>>>head []*** Exception: Prelude.head: empty list
drop n xs returns the suffix of xs
after the first n elements, or [] if n >= .length xs
>>>drop 6 "Hello World!""World!">>>drop 3 [1,2,3,4,5][4,5]>>>drop 3 [1,2][]>>>drop 3 [][]>>>drop (-1) [1,2][1,2]>>>drop 0 [1,2][1,2]
It is an instance of the more general genericDrop,
in which n may be of any integral type.
cycle ties a finite list into a circular one, or equivalently,
the infinite repetition of the original list. It is the identity
on infinite lists.
>>>cycle []*** Exception: Prelude.cycle: empty list>>>take 20 $ cycle [42][42,42,42,42,42,42,42,42,42,42...>>>take 20 $ cycle [2, 5, 7][2,5,7,2,5,7,2,5,7,2,5,7...
break :: (a -> Bool) -> [a] -> ([a], [a]) #
break, applied to a predicate p and a list xs, returns a tuple where
first element is longest prefix (possibly empty) of xs of elements that
do not satisfy p and second element is the remainder of the list:
>>>break (> 3) [1,2,3,4,1,2,3,4]([1,2,3],[4,1,2,3,4])>>>break (< 9) [1,2,3]([],[1,2,3])>>>break (> 9) [1,2,3]([1,2,3],[])
(!!) :: [a] -> Int -> a infixl 9 #
List index (subscript) operator, starting from 0.
It is an instance of the more general genericIndex,
which takes an index of any integral type.
>>>['a', 'b', 'c'] !! 0'a'>>>['a', 'b', 'c'] !! 2'c'>>>['a', 'b', 'c'] !! 3*** Exception: Prelude.!!: index too large>>>['a', 'b', 'c'] !! (-1)*** Exception: Prelude.!!: negative index
maybeToList :: Maybe a -> [a] #
The maybeToList function returns an empty list when given
Nothing or a singleton list when given Just.
Examples
Basic usage:
>>>maybeToList (Just 7)[7]
>>>maybeToList Nothing[]
One can use maybeToList to avoid pattern matching when combined
with a function that (safely) works on lists:
>>>import Text.Read ( readMaybe )>>>sum $ maybeToList (readMaybe "3")3>>>sum $ maybeToList (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""
listToMaybe :: [a] -> Maybe a #
The listToMaybe function returns Nothing on an empty list
or where Just aa is the first element of the list.
Examples
Basic usage:
>>>listToMaybe []Nothing
>>>listToMaybe [9]Just 9
>>>listToMaybe [1,2,3]Just 1
Composing maybeToList with listToMaybe should be the identity
on singleton/empty lists:
>>>maybeToList $ listToMaybe [5][5]>>>maybeToList $ listToMaybe [][]
But not on lists with more than one element:
>>>maybeToList $ listToMaybe [1,2,3][1]
fromJust :: HasCallStack => Maybe a -> a #
An MVar (pronounced "em-var") is a synchronising variable, used
for communication between concurrent threads. It can be thought of
as a box, which may be empty or full.
tryTakeMVar :: MVar a -> IO (Maybe a) #
A non-blocking version of takeMVar. The tryTakeMVar function
returns immediately, with Nothing if the MVar was empty, or
if the Just aMVar was full with contents a. After tryTakeMVar,
the MVar is left empty.
tryReadMVar :: MVar a -> IO (Maybe a) #
tryPutMVar :: MVar a -> a -> IO Bool #
A non-blocking version of putMVar. The tryPutMVar function
attempts to put the value a into the MVar, returning True if
it was successful, or False otherwise.
Return the contents of the MVar. If the MVar is currently
empty, takeMVar will wait until it is full. After a takeMVar,
the MVar is left empty.
There are two further important properties of takeMVar:
takeMVaris single-wakeup. That is, if there are multiple threads blocked intakeMVar, and theMVarbecomes full, only one thread will be woken up. The runtime guarantees that the woken thread completes itstakeMVaroperation.- When multiple threads are blocked on an
MVar, they are woken up in FIFO order. This is useful for providing fairness properties of abstractions built usingMVars.
Atomically read the contents of an MVar. If the MVar is
currently empty, readMVar will wait until it is full.
readMVar is guaranteed to receive the next putMVar.
readMVar is multiple-wakeup, so when multiple readers are
blocked on an MVar, all of them are woken up at the same time.
Compatibility note: Prior to base 4.7, readMVar was a combination
of takeMVar and putMVar. This mean that in the presence of
other threads attempting to putMVar, readMVar could block.
Furthermore, readMVar would not receive the next putMVar if there
was already a pending thread blocked on takeMVar. The old behavior
can be recovered by implementing 'readMVar as follows:
readMVar :: MVar a -> IO a
readMVar m =
mask_ $ do
a <- takeMVar m
putMVar m a
return a
putMVar :: MVar a -> a -> IO () #
Put a value into an MVar. If the MVar is currently full,
putMVar will wait until it becomes empty.
There are two further important properties of putMVar:
putMVaris single-wakeup. That is, if there are multiple threads blocked inputMVar, and theMVarbecomes empty, only one thread will be woken up. The runtime guarantees that the woken thread completes itsputMVaroperation.- When multiple threads are blocked on an
MVar, they are woken up in FIFO order. This is useful for providing fairness properties of abstractions built usingMVars.
newEmptyMVar :: IO (MVar a) #
Create an MVar which is initially empty.
isEmptyMVar :: MVar a -> IO Bool #
Check whether a given MVar is empty.
Notice that the boolean value returned is just a snapshot of
the state of the MVar. By the time you get to react on its result,
the MVar may have been filled (or emptied) - so be extremely
careful when using this operation. Use tryTakeMVar instead if possible.
liftM5 :: Monad m => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r #
Promote a function to a monad, scanning the monadic arguments from
left to right (cf. liftM2).
liftM4 :: Monad m => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r #
Promote a function to a monad, scanning the monadic arguments from
left to right (cf. liftM2).
liftM3 :: Monad m => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r #
Promote a function to a monad, scanning the monadic arguments from
left to right (cf. liftM2).
liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d #
Lift a ternary function to actions.
liftA :: Applicative f => (a -> b) -> f a -> f b #
Lift a function to actions.
Equivalent to Functor's fmap but implemented using only Applicative's methods:
`liftA f a = pure f * a`
As such this function may be used to implement a Functor instance from an Applicative one.
(=<<) :: Monad m => (a -> m b) -> m a -> m b infixr 1 #
Same as >>=, but with the arguments interchanged.
(<**>) :: Applicative f => f a -> f (a -> b) -> f b infixl 4 #
A variant of <*> with the arguments reversed.
type HasCallStack = ?callStack :: CallStack #
Request a CallStack.
NOTE: The implicit parameter ?callStack :: CallStack is an
implementation detail and should not be considered part of the
CallStack API, we may decide to change the implementation in the
future.
Since: base-4.9.0.0
flagsVerbosity :: (Verbosity -> a -> a) -> [Flag a] #
Create verbosity flags triggered by -v/--verbose and
-q/--quiet
flagNumericVersion :: (a -> a) -> Flag a #
Create a version flag triggered by --numeric-version.
flagVersion :: (a -> a) -> Flag a #
Create a version flag triggered by -V/--version.
flagHelpFormat :: (HelpFormat -> TextFormat -> a -> a) -> Flag a #
Create a help flag triggered by -?/--help. The user
may optionally modify help by specifying the format, such as:
--help=all - help for all modes --help=html - help in HTML format --help=100 - wrap the text at 100 characters --help=100,one - full text wrapped at 100 characters
flagHelpSimple :: (a -> a) -> Flag a #
Create a help flag triggered by -?/--help.
processValueIO :: Mode a -> [String] -> IO a #
Like processValue but on failure prints to stderr and exits the program.
processValue :: Mode a -> [String] -> a #
Process a list of flags (usually obtained from and getArgs) with a mode.
Throws an error if the command line fails to parse, or returns
the associated value. Implemeneted in terms of expandArgsAtprocess. This function
does not take account of any environment variables that may be set
(see processArgs).
If you are in IO you will probably get a better user experience by calling processValueIO.
processArgs :: Mode a -> IO a #
Process the flags obtained by and getArgs with a mode. Displays
an error and exits with failure if the command line fails to parse, or returns
the associated value. Implemented in terms of expandArgsAtprocess. This function makes
use of the following environment variables:
$CMDARGS_COMPLETE- causes the program to produce completions usingcomplete, then exit. Completions are based on the result ofgetArgs, the index of the current argument is taken from$CMDARGS_COMPLETE(set it to-to complete the last argument), and the index within that argument is taken from$CMDARGS_COMPLETE_POS(if set).$CMDARGS_HELPER/$CMDARGS_HELPER_PROG- uses the helper mechanism for entering command line programs as described in System.Console.CmdArgs.Helper.
helpText :: [String] -> HelpFormat -> Mode a -> [Text] #
Generate a help message from a mode. The first argument is a prefix,
which is prepended when not using HelpFormatBash or HelpFormatZsh.
data HelpFormat #
Specify the format to output the help.
Constructors
| HelpFormatDefault | Equivalent to |
| HelpFormatOne | Display only the first mode. |
| HelpFormatAll | Display all modes. |
| HelpFormatBash | Bash completion information |
| HelpFormatZsh | Z shell completion information |
Instances
Arguments
| :: Mode a | Mode specifying which arguments are allowed |
| -> [String] | Arguments the user has already typed |
| -> (Int, Int) | 0-based index of the argument they are currently on, and the position in that argument |
| -> [Complete] |
Given a current state, return the set of commands you could type now, in preference order.
How to complete a command line option.
The Show instance is suitable for parsing from shell scripts.
Constructors
| CompleteValue String | Complete to a particular value |
| CompleteFile String FilePath | Complete to a prefix, and a file |
| CompleteDir String FilePath | Complete to a prefix, and a directory |
process :: Mode a -> [String] -> Either String a #
Process a list of flags (usually obtained from getArgs/expandArgsAt) with a mode. Returns
Left and an error message if the command line fails to parse, or Right and
the associated value.
flagBool :: [Name] -> (Bool -> a -> a) -> Help -> Flag a #
Create a boolean flag, with a list of flag names, an update function and some help text.
flagArg :: Update a -> FlagHelp -> Arg a #
Create an argument flag, with an update function and the type of the argument.
flagReq :: [Name] -> Update a -> FlagHelp -> Help -> Flag a #
Create a flag taking a required argument value, with a list of flag names, an update function, the type of the argument and some help text.
flagOpt :: String -> [Name] -> Update a -> FlagHelp -> Help -> Flag a #
Create a flag taking an optional argument value, with an optional value, a list of flag names, an update function, the type of the argument and some help text.
flagNone :: [Name] -> (a -> a) -> Help -> Flag a #
Create a flag taking no argument value, with a list of flag names, an update function and some help text.
modes :: String -> a -> Help -> [Mode a] -> Mode a #
Create a list of modes, with a program name, an initial value, some help text and the child modes.
mode :: Name -> a -> Help -> Arg a -> [Flag a] -> Mode a #
Create a mode with a name, an initial value, some help text, a way of processing arguments and a list of flags.
Create an empty mode specifying only modeValue. All other fields will usually be populated
using record updates.
remapUpdate :: (a -> b) -> (b -> (a, a -> b)) -> Update a -> Update b #
remap2 :: Remap m => (a -> b) -> (b -> a) -> m a -> m b #
Restricted version of remap where the values are isomorphic.
fromFlagOpt :: FlagInfo -> String #
Extract the value from inside a FlagOpt or FlagOptRare, or raises an error.
Convert a list into a group, placing all fields in groupUnnamed.
A group of items (modes or flags). The items are treated as a list, but the group structure is used when displaying the help message.
Constructors
| Group | |
Fields
| |
A mode. Do not use the Mode constructor directly, instead
use mode to construct the Mode and then record updates.
Each mode has three main features:
- A list of submodes (
modeGroupModes) - A list of flags (
modeGroupFlags) - Optionally an unnamed argument (
modeArgs)
To produce the help information for a mode, either use helpText or show.
Constructors
| Mode | |
Fields
| |
The FlagInfo type has the following meaning:
FlagReq FlagOpt FlagOptRare/FlagNone -xfoo -x=foo -x=foo -x -foo -x foo -x=foo -x foo -x foo -x=foo -x=foo -x=foo -x=foo --xx foo --xx=foo --xx foo --xx foo --xx=foo --xx=foo --xx=foo --xx=foo
Constructors
| FlagReq | Required argument |
| FlagOpt String | Optional argument |
| FlagOptRare String | Optional argument that requires an = before the value |
| FlagNone | No argument |
type Update a = String -> a -> Either String a #
A function to take a string, and a value, and either produce an error message
(Left), or a modified value (Right).
A flag, consisting of a list of flag names and other information.
Constructors
| Flag | |
An unnamed argument. Anything not starting with - is considered an argument,
apart from "-" which is considered to be the argument "-", and any arguments
following "--". For example:
programname arg1 -j - --foo arg3 -- -arg4 --arg5=1 arg6
Would have the arguments:
["arg1","-","arg3","-arg4","--arg5=1","arg6"]
Constructors
| Arg | |
class Remap (m :: TYPE LiftedRep -> Type) where #
Like functor, but where the the argument isn't just covariant.
Methods
Arguments
| :: (a -> b) | Embed a value |
| -> (b -> (a, a -> b)) | Extract the mode and give a way of re-embedding |
| -> m a | |
| -> m b |
Convert between two values.
Instances
| Remap Arg | |
Defined in System.Console.CmdArgs.Explicit.Type | |
| Remap Flag | |
Defined in System.Console.CmdArgs.Explicit.Type | |
| Remap Mode | |
Defined in System.Console.CmdArgs.Explicit.Type | |
splitArgs :: String -> [String] #
Given a string, split into the available arguments. The inverse of joinArgs.
joinArgs :: [String] -> String #
Given a sequence of arguments, join them together in a manner that could be used on
the command line, giving preference to the Windows cmd shell quoting conventions.
For an alternative version, intended for actual running the result in a shell, see "System.Process.showCommandForUser"
expandArgsAt :: [String] -> IO [String] #
Expand @ directives in a list of arguments, usually obtained from getArgs.
As an example, given the file test.txt with the lines hello and world:
expandArgsAt ["@test.txt","!"] == ["hello","world","!"]
Any @ directives in the files will be recursively expanded (raising an error
if there is infinite recursion).
To supress @ expansion, pass any @ arguments after --.
data ProcessHandle #
A handle to a process, which can be used to wait for termination
of the process using waitForProcess.
None of the process-creation functions in this library wait for
termination: they all return a ProcessHandle which may be used
to wait for the process later.
On Windows a second wait method can be used to block for event completion. This requires two handles. A process job handle and a events handle to monitor.
Constructors
| Inherit | Inherit Handle from parent |
| UseHandle Handle | Use the supplied Handle |
| CreatePipe | Create a new pipe. The returned
|
| NoStream | Close the stream's file descriptor without
passing a Handle. On POSIX systems this may
lead to strange behavior in the child process
because attempting to read or write after the
file has been closed throws an error. This
should only be used with child processes that
don't use the file descriptor at all. If you
wish to ignore the child process's output you
should either create a pipe and drain it
manually or pass a |
Instances
Constructors
| ShellCommand String | A command line to execute using the shell |
| RawCommand FilePath [String] | The name of an executable with a list of arguments The
|
Instances
| IsString CmdSpec | construct a Since: process-1.2.1.0 |
Defined in System.Process.Common Methods fromString :: String -> CmdSpec # | |
| Show CmdSpec | |
| Eq CmdSpec | |
data CreateProcess #
Constructors
| CreateProcess | |
Fields
| |
Instances
| Show CreateProcess | |
Defined in System.Process.Common Methods showsPrec :: Int -> CreateProcess -> ShowS # show :: CreateProcess -> String # showList :: [CreateProcess] -> ShowS # | |
| Eq CreateProcess | |
Defined in System.Process.Common Methods (==) :: CreateProcess -> CreateProcess -> Bool # (/=) :: CreateProcess -> CreateProcess -> Bool # | |
Arguments
| :: String | Function name (for error messages). This can be any |
| -> CreateProcess | |
| -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) |
This function is almost identical to
createProcess. The only differences are:
Handles provided viaUseHandleare not closed automatically.- This function takes an extra
Stringargument to be used in creating error messages.
This function has been available from the System.Process.Internals module for some time, and is part of the System.Process module since version 1.2.1.0.
Since: process-1.2.1.0
createPipe :: IO (Handle, Handle) #
Create a pipe for interprocess communication and return a
(readEnd, writeEnd) Handle pair.
- WinIO Support
When this function is used with WinIO enabled it's the caller's responsibility to register the handles with the I/O manager. If this is not done the operation will deadlock. Association can be done as follows:
#if defined(IO_MANAGER_WINIO)
import GHC.IO.SubSystem ((!))
import GHC.IO.Handle.Windows (handleToHANDLE)
import GHC.Event.Windows (associateHandle')
#endif
...
#if defined (IO_MANAGER_WINIO)
return () ! (do
associateHandle' =handleToHANDLE <handle)
#endif
Only associate handles that you are in charge of read/writing to. Do not associate handles passed to another process. It's the process's reponsibility to register the handle if it supports async access.
Since: process-1.2.1.0
createPipeFd :: IO (FD, FD) #
Create a pipe for interprocess communication and return a
(readEnd, writeEnd) FD pair.
Since: process-1.4.2.0
Arguments
| :: ProcessHandle | A process in the process group |
| -> IO () |
Sends an interrupt signal to the process group of the given process.
On Unix systems, it sends the group the SIGINT signal.
On Windows systems, it generates a CTRL_BREAK_EVENT and will only work for
processes created using createProcess and setting the create_group flag
The platform specific type for a process identifier.
This is always an integral type. Width and signedness are platform specific.
Since: process-1.6.3.0
proc :: FilePath -> [String] -> CreateProcess #
Construct a CreateProcess record for passing to createProcess,
representing a raw command with arguments.
See RawCommand for precise semantics of the specified FilePath.
shell :: String -> CreateProcess #
Construct a CreateProcess record for passing to createProcess,
representing a command to be passed to the shell.
createProcess :: CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) #
This is the most general way to spawn an external process. The
process can be a command line to be executed by a shell or a raw command
with a list of arguments. The stdin, stdout, and stderr streams of
the new process may individually be attached to new pipes, to existing
Handles, or just inherited from the parent (the default.)
The details of how to create the process are passed in the
CreateProcess record. To make it easier to construct a
CreateProcess, the functions proc and shell are supplied that
fill in the fields with default values which can be overriden as
needed.
createProcess returns (mb_stdin_hdl, mb_stdout_hdl, mb_stderr_hdl, ph),
where
- if
, thenstd_in==CreatePipemb_stdin_hdlwill beJust h, wherehis the write end of the pipe connected to the child process'sstdin. - otherwise,
mb_stdin_hdl == Nothing
Similarly for mb_stdout_hdl and mb_stderr_hdl.
For example, to execute a simple ls command:
r <- createProcess (proc "ls" [])
To create a pipe from which to read the output of ls:
(_, Just hout, _, _) <-
createProcess (proc "ls" []){ std_out = CreatePipe }To also set the directory in which to run ls:
(_, Just hout, _, _) <-
createProcess (proc "ls" []){ cwd = Just "/home/bob",
std_out = CreatePipe }Note that Handles provided for std_in, std_out, or std_err via the
UseHandle constructor will be closed by calling this function. This is not
always the desired behavior. In cases where you would like to leave the
Handle open after spawning the child process, please use createProcess_
instead. All created Handles are initially in text mode; if you need them
to be in binary mode then use hSetBinaryMode.
ph contains a handle to the running process. On Windows
use_process_jobs can be set in CreateProcess in order to create a
Win32 Job object to monitor a process tree's progress. If it is set
then that job is also returned inside ph. ph can be used to
kill all running sub-processes. This feature has been available since
1.5.0.0.
withCreateProcess :: CreateProcess -> (Maybe Handle -> Maybe Handle -> Maybe Handle -> ProcessHandle -> IO a) -> IO a #
A bracket-style resource handler for createProcess.
Does automatic cleanup when the action finishes. If there is an exception
in the body then it ensures that the process gets terminated and any
CreatePipe Handles are closed. In particular this means that if the
Haskell thread is killed (e.g. killThread), that the external process is
also terminated.
e.g.
withCreateProcess (proc cmd args) { ... } $ \stdin stdout stderr ph -> do
...Since: process-1.4.3.0
cleanupProcess :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> IO () #
Cleans up the process.
This function is meant to be invoked from any application level cleanup
handler. It terminates the process, and closes any CreatePipe handles.
Since: process-1.6.4.0
spawnProcess :: FilePath -> [String] -> IO ProcessHandle #
Creates a new process to run the specified raw command with the given
arguments. It does not wait for the program to finish, but returns the
ProcessHandle.
Since: process-1.2.0.0
spawnCommand :: String -> IO ProcessHandle #
Creates a new process to run the specified shell command.
It does not wait for the program to finish, but returns the ProcessHandle.
Since: process-1.2.0.0
callProcess :: FilePath -> [String] -> IO () #
Creates a new process to run the specified command with the given arguments, and wait for it to finish. If the command returns a non-zero exit code, an exception is raised.
If an asynchronous exception is thrown to the thread executing
callProcess, the forked process will be terminated and
callProcess will wait (block) until the process has been
terminated.
Since: process-1.2.0.0
callCommand :: String -> IO () #
Creates a new process to run the specified shell command. If the command returns a non-zero exit code, an exception is raised.
If an asynchronous exception is thrown to the thread executing
callCommand, the forked process will be terminated and
callCommand will wait (block) until the process has been
terminated.
Since: process-1.2.0.0
Arguments
| :: FilePath | Filename of the executable (see |
| -> [String] | any arguments |
| -> String | standard input |
| -> IO String | stdout |
readProcess forks an external process, reads its standard output
strictly, blocking until the process terminates, and returns the output
string. The external process inherits the standard error.
If an asynchronous exception is thrown to the thread executing
readProcess, the forked process will be terminated and readProcess will
wait (block) until the process has been terminated.
Output is returned strictly, so this is not suitable for launching processes that require interaction over the standard file streams.
This function throws an IOError if the process ExitCode is
anything other than ExitSuccess. If instead you want to get the
ExitCode then use readProcessWithExitCode.
Users of this function should compile with -threaded if they
want other Haskell threads to keep running while waiting on
the result of readProcess.
> readProcess "date" [] [] "Thu Feb 7 10:03:39 PST 2008\n"
The arguments are:
- The command to run, which must be in the $PATH, or an absolute or relative path
- A list of separate command line arguments to the program
- A string to pass on standard input to the forked process.
Arguments
| :: CreateProcess | |
| -> String | standard input |
| -> IO String | stdout |
readCreateProcess works exactly like readProcess except that it
lets you pass CreateProcess giving better flexibility.
> readCreateProcess ((shell "pwd") { cwd = Just "/etc/" }) ""
"/etc\n"Note that Handles provided for std_in or std_out via the CreateProcess
record will be ignored.
Since: process-1.2.3.0
Arguments
| :: FilePath | Filename of the executable (see |
| -> [String] | any arguments |
| -> String | standard input |
| -> IO (ExitCode, String, String) | exitcode, stdout, stderr |
readProcessWithExitCode is like readProcess but with two differences:
- it returns the
ExitCodeof the process, and does not throw any exception if the code is notExitSuccess. - it reads and returns the output from process' standard error handle, rather than the process inheriting the standard error handle.
On Unix systems, see waitForProcess for the meaning of exit codes
when the process died as the result of a signal.
readCreateProcessWithExitCode #
Arguments
| :: CreateProcess | |
| -> String | standard input |
| -> IO (ExitCode, String, String) | exitcode, stdout, stderr |
readCreateProcessWithExitCode works exactly like readProcessWithExitCode except that it
lets you pass CreateProcess giving better flexibility.
Note that Handles provided for std_in, std_out, or std_err via the CreateProcess
record will be ignored.
Since: process-1.2.3.0
showCommandForUser :: FilePath -> [String] -> String #
Given a program p and arguments args,
showCommandForUser p args returns a string suitable for pasting
into /bin/sh (on Unix systems) or CMD.EXE (on Windows).
getPid :: ProcessHandle -> IO (Maybe Pid) #
Returns the PID (process ID) of a subprocess.
Nothing is returned if the handle was already closed. Otherwise a
PID is returned that remains valid as long as the handle is open.
The operating system may reuse the PID as soon as the last handle to
the process is closed.
Since: process-1.6.3.0
getCurrentPid :: IO Pid #
Returns the PID (process ID) of the current process. On POSIX systems,
this calls getProcessID from System.Posix.Process in the unix package.
On Windows, this calls getCurrentProcessId from System.Win32.Process in
the Win32 package.
Since: process-1.6.12.0
waitForProcess :: ProcessHandle -> IO ExitCode #
Waits for the specified process to terminate, and returns its exit code.
On Unix systems, may throw UserInterrupt when using delegate_ctlc.
GHC Note: in order to call waitForProcess without blocking all the
other threads in the system, you must compile the program with
-threaded.
Note that it is safe to call waitForProcess for the same process in multiple
threads. When the process ends, threads blocking on this call will wake in
FIFO order. When using delegate_ctlc and the process is interrupted, only
the first waiting thread will throw UserInterrupt.
(Since: 1.2.0.0) On Unix systems, a negative value
indicates that the child was terminated by signal ExitFailure -signumsignum.
The signal numbers are platform-specific, so to test for a specific signal use
the constants provided by System.Posix.Signals in the unix package.
Note: core dumps are not reported, use System.Posix.Process if you need this
detail.
getProcessExitCode :: ProcessHandle -> IO (Maybe ExitCode) #
This is a non-blocking version of waitForProcess. If the process is
still running, Nothing is returned. If the process has exited, then
is returned where Just ee is the exit code of the process.
On Unix systems, see waitForProcess for the meaning of exit codes
when the process died as the result of a signal. May throw
UserInterrupt when using delegate_ctlc.
terminateProcess :: ProcessHandle -> IO () #
Attempts to terminate the specified process. This function should
not be used under normal circumstances - no guarantees are given regarding
how cleanly the process is terminated. To check whether the process
has indeed terminated, use getProcessExitCode.
On Unix systems, terminateProcess sends the process the SIGTERM signal.
On Windows systems, if use_process_jobs is True then the Win32 TerminateJobObject
function is called to kill all processes associated with the job and passing the
exit code of 1 to each of them. Otherwise if use_process_jobs is False then the
Win32 TerminateProcess function is called, passing an exit code of 1.
Note: on Windows, if the process was a shell command created by
createProcess with shell, or created by runCommand or
runInteractiveCommand, then terminateProcess will only
terminate the shell, not the command itself. On Unix systems, both
processes are in a process group and will be terminated together.
runCommand :: String -> IO ProcessHandle #
Runs a command using the shell.
Arguments
| :: FilePath | Filename of the executable (see |
| -> [String] | Arguments to pass to the executable |
| -> Maybe FilePath | Optional path to the working directory |
| -> Maybe [(String, String)] | Optional environment (otherwise inherit) |
| -> Maybe Handle | Handle to use for |
| -> Maybe Handle | Handle to use for |
| -> Maybe Handle | Handle to use for |
| -> IO ProcessHandle |
Runs a raw command, optionally specifying Handles from which to
take the stdin, stdout and stderr channels for the new
process (otherwise these handles are inherited from the current
process).
Any Handles passed to runProcess are placed immediately in the
closed state.
Note: consider using the more general createProcess instead of
runProcess.
runInteractiveCommand :: String -> IO (Handle, Handle, Handle, ProcessHandle) #
Runs a command using the shell, and returns Handles that may
be used to communicate with the process via its stdin, stdout,
and stderr respectively.
Arguments
| :: FilePath | Filename of the executable (see |
| -> [String] | Arguments to pass to the executable |
| -> Maybe FilePath | Optional path to the working directory |
| -> Maybe [(String, String)] | Optional environment (otherwise inherit) |
| -> IO (Handle, Handle, Handle, ProcessHandle) |
Runs a raw command, and returns Handles that may be used to communicate
with the process via its stdin, stdout and stderr respectively.
For example, to start a process and feed a string to its stdin:
(inp,out,err,pid) <- runInteractiveProcess "..." forkIO (hPutStr inp str)
system :: String -> IO ExitCode #
Computation system cmd returns the exit code produced when the
operating system runs the shell command cmd.
This computation may fail with one of the following
IOErrorType exceptions:
PermissionDenied- The process has insufficient privileges to perform the operation.
ResourceExhausted- Insufficient resources are available to perform the operation.
UnsupportedOperation- The implementation does not support system calls.
On Windows, system passes the command to the Windows command
interpreter (CMD.EXE or COMMAND.COM), hence Unixy shell tricks
will not work.
On Unix systems, see waitForProcess for the meaning of exit codes
when the process died as the result of a signal.
rawSystem :: String -> [String] -> IO ExitCode #
The computation runs the operating system command
rawSystem cmd argscmd in such a way that it receives as arguments the args strings
exactly as given, with no funny escaping or shell meta-syntax expansion.
It will therefore behave more portably between operating systems than system.
The return codes and possible failures are the same as for system.
getTemporaryDirectory :: IO FilePath #
Returns the current directory for temporary files.
On Unix, getTemporaryDirectory returns the value of the TMPDIR
environment variable or "/tmp" if the variable isn't defined.
On Windows, the function checks for the existence of environment variables in
the following order and uses the first path found:
- TMP environment variable.
- TEMP environment variable.
- USERPROFILE environment variable.
- The Windows directory
The operation may fail with:
UnsupportedOperationThe operating system has no notion of temporary directory.
The function doesn't verify whether the path exists.
getUserDocumentsDirectory :: IO FilePath #
Returns the current user's document directory.
The directory returned is expected to be writable by the current user,
but note that it isn't generally considered good practice to store
application-specific data here; use getXdgDirectory or
getAppUserDataDirectory instead.
On Unix, getUserDocumentsDirectory returns the value of the HOME
environment variable. On Windows, the system is queried for a
suitable path; a typical path might be C:/Users/<user>/Documents.
The operation may fail with:
UnsupportedOperationThe operating system has no notion of document directory.isDoesNotExistErrorThe document directory for the current user does not exist, or cannot be found.
Obtain the path to a special directory for storing user-specific
application data (traditional Unix location). Newer applications may
prefer the the XDG-conformant location provided by getXdgDirectory
(migration guide).
The argument is usually the name of the application. Since it will be integrated into the path, it must consist of valid path characters.
- On Unix-like systems, the path is
~/.<app>. - On Windows, the path is
%APPDATA%/<app>(e.g.C:/Users/<user>/AppData/Roaming/<app>)
Note: the directory may not actually exist, in which case you would need to create it. It is expected that the parent directory exists and is writable.
The operation may fail with:
UnsupportedOperationThe operating system has no notion of application-specific data directory.isDoesNotExistErrorThe home directory for the current user does not exist, or cannot be found.
Arguments
| :: XdgDirectoryList | which special directory list |
| -> IO [FilePath] |
Similar to getXdgDirectory but retrieves the entire list of XDG
directories.
On Windows, XdgDataDirs and XdgConfigDirs usually map to the same list
of directories unless overridden.
Refer to the docs of XdgDirectoryList for more details.
Arguments
| :: XdgDirectory | which special directory |
| -> FilePath | a relative path that is appended to the path; if empty, the base path is returned |
| -> IO FilePath |
Obtain the paths to special directories for storing user-specific
application data, configuration, and cache files, conforming to the
XDG Base Directory Specification.
Compared with getAppUserDataDirectory, this function provides a more
fine-grained hierarchy as well as greater flexibility for the user.
On Windows, XdgData and XdgConfig usually map to the same directory
unless overridden.
Refer to the docs of XdgDirectory for more details.
The second argument is usually the name of the application. Since it will be integrated into the path, it must consist of valid path characters. Note: if the second argument is an absolute path, it will just return the second argument.
Note: The directory may not actually exist, in which case you would need
to create it with file mode 700 (i.e. only accessible by the owner).
As of 1.3.5.0, the environment variable is ignored if set to a relative path, per revised XDG Base Directory Specification. See #100.
Since: directory-1.2.3.0
getHomeDirectory :: IO FilePath #
Returns the current user's home directory.
The directory returned is expected to be writable by the current user,
but note that it isn't generally considered good practice to store
application-specific data here; use getXdgDirectory or
getAppUserDataDirectory instead.
On Unix, getHomeDirectory behaves as follows:
- Returns $HOME env variable if set (including to an empty string).
- Otherwise uses home directory returned by
getpwuid_rusing the UID of the current proccesses user. This basically reads the etcpasswd file. An empty home directory field is considered valid.
On Windows, the system is queried for a suitable path; a typical path might be C:/Users/<user>.
The operation may fail with:
UnsupportedOperationThe operating system has no notion of home directory.isDoesNotExistErrorThe home directory for the current user does not exist, or cannot be found.
setModificationTime :: FilePath -> UTCTime -> IO () #
Change the time at which the file or directory was last modified.
The operation may fail with:
isPermissionErrorif the user is not permitted to alter the modification time; orisDoesNotExistErrorif the file or directory does not exist.
Some caveats for POSIX systems:
- Not all systems support
utimensat, in which case the function can only emulate the behavior by reading the access time and then setting both the access and modification times together. On systems whereutimensatis supported, the modification time is set atomically with nanosecond precision. - If compiled against a version of
unixprior to2.7.0.0, the function would not be able to set timestamps with sub-second resolution. In this case, there would also be loss of precision in the access time.
Since: directory-1.2.3.0
setAccessTime :: FilePath -> UTCTime -> IO () #
Change the time at which the file or directory was last accessed.
The operation may fail with:
isPermissionErrorif the user is not permitted to alter the access time; orisDoesNotExistErrorif the file or directory does not exist.
Some caveats for POSIX systems:
- Not all systems support
utimensat, in which case the function can only emulate the behavior by reading the modification time and then setting both the access and modification times together. On systems whereutimensatis supported, the access time is set atomically with nanosecond precision. - If compiled against a version of
unixprior to2.7.0.0, the function would not be able to set timestamps with sub-second resolution. In this case, there would also be loss of precision in the modification time.
Since: directory-1.2.3.0
getModificationTime :: FilePath -> IO UTCTime #
Obtain the time at which the file or directory was last modified.
The operation may fail with:
isPermissionErrorif the user is not permitted to read the modification time; orisDoesNotExistErrorif the file or directory does not exist.
Caveat for POSIX systems: This function returns a timestamp with sub-second
resolution only if this package is compiled against unix-2.6.0.0 or later
and the underlying filesystem supports them.
getAccessTime :: FilePath -> IO UTCTime #
Obtain the time at which the file or directory was last accessed.
The operation may fail with:
isPermissionErrorif the user is not permitted to read the access time; orisDoesNotExistErrorif the file or directory does not exist.
Caveat for POSIX systems: This function returns a timestamp with sub-second
resolution only if this package is compiled against unix-2.6.0.0 or later
and the underlying filesystem supports them.
Since: directory-1.2.3.0
getSymbolicLinkTarget :: FilePath -> IO FilePath #
Retrieve the target path of either a file or directory symbolic link. The returned path may not be absolute, may not exist, and may not even be a valid path.
On Windows systems, this calls DeviceIoControl with
FSCTL_GET_REPARSE_POINT. In addition to symbolic links, the function
also works on junction points. On POSIX systems, this calls readlink.
Windows-specific errors: This operation may fail with
illegalOperationErrorType if the file system does not support symbolic
links.
Since: directory-1.3.1.0
isSymbolicLink :: FilePath -> IO Bool #
pathIsSymbolicLink :: FilePath -> IO Bool #
Check whether an existing path is a symbolic link. If path is a
regular file or directory, False is returned. If path does not exist
or is otherwise inaccessible, an exception is thrown (see below).
On Windows, this checks for FILE_ATTRIBUTE_REPARSE_POINT. In addition to
symbolic links, the function also returns true on junction points. On
POSIX systems, this checks for S_IFLNK.
The operation may fail with:
isDoesNotExistErrorif the symbolic link does not exist; orisPermissionErrorif the user is not permitted to read the symbolic link.
Since: directory-1.3.0.0
removeDirectoryLink :: FilePath -> IO () #
Remove an existing directory symbolic link.
On Windows, this is an alias for removeDirectory. On POSIX systems, this
is an alias for removeFile.
See also: removeFile, which can remove an existing file symbolic link.
Since: directory-1.3.1.0
Create a directory symbolic link. The target path can be either absolute or relative and need not refer to an existing directory. The order of arguments follows the POSIX convention.
To remove an existing directory symbolic link, use removeDirectoryLink.
Although the distinction between file symbolic links and directory symbolic links does not exist on POSIX systems, on Windows this is an intrinsic property of every symbolic link and cannot be changed without recreating the link. A file symbolic link that actually points to a directory will fail to dereference and vice versa. Moreover, creating symbolic links on Windows may require privileges unavailable to users outside the Administrators group. Portable programs that use symbolic links should take both into consideration.
On Windows, the function is implemented using CreateSymbolicLink with
SYMBOLIC_LINK_FLAG_DIRECTORY. Since 1.3.3.0, the
SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE flag is also included if
supported by the operating system. On POSIX, this is an alias for
createFileLink and is therefore atomic.
Windows-specific errors: This operation may fail with permissionErrorType
if the user lacks the privileges to create symbolic links. It may also
fail with illegalOperationErrorType if the file system does not support
symbolic links.
Since: directory-1.3.1.0
Create a file symbolic link. The target path can be either absolute or relative and need not refer to an existing file. The order of arguments follows the POSIX convention.
To remove an existing file symbolic link, use removeFile.
Although the distinction between file symbolic links and directory symbolic links does not exist on POSIX systems, on Windows this is an intrinsic property of every symbolic link and cannot be changed without recreating the link. A file symbolic link that actually points to a directory will fail to dereference and vice versa. Moreover, creating symbolic links on Windows may require privileges unavailable to users outside the Administrators group. Portable programs that use symbolic links should take both into consideration.
On Windows, the function is implemented using CreateSymbolicLink. Since
1.3.3.0, the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE flag is included
if supported by the operating system. On POSIX, the function uses symlink
and is therefore atomic.
Windows-specific errors: This operation may fail with permissionErrorType
if the user lacks the privileges to create symbolic links. It may also
fail with illegalOperationErrorType if the file system does not support
symbolic links.
Since: directory-1.3.1.0
doesFileExist :: FilePath -> IO Bool #
The operation doesFileExist returns True
if the argument file exists and is not a directory, and False otherwise.
doesDirectoryExist :: FilePath -> IO Bool #
The operation doesDirectoryExist returns True if the argument file
exists and is either a directory or a symbolic link to a directory,
and False otherwise.
doesPathExist :: FilePath -> IO Bool #
Test whether the given path points to an existing filesystem object. If the user lacks necessary permissions to search the parent directories, this function may return false even if the file does actually exist.
Since: directory-1.2.7.0
getFileSize :: FilePath -> IO Integer #
Obtain the size of a file in bytes.
Since: directory-1.2.7.0
Run an IO action with the given working directory and restore the
original working directory afterwards, even if the given action fails due
to an exception.
The operation may fail with the same exceptions as getCurrentDirectory
and setCurrentDirectory.
Since: directory-1.2.3.0
setCurrentDirectory :: FilePath -> IO () #
Change the working directory to the given path.
In a multithreaded program, the current working directory is a global state
shared among all threads of the process. Therefore, when performing
filesystem operations from multiple threads, it is highly recommended to
use absolute rather than relative paths (see: makeAbsolute).
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentThe operand is not a valid directory name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThe directory does not exist.[ENOENT, ENOTDIR]isPermissionErrorThe process has insufficient privileges to perform the operation.[EACCES]UnsupportedOperationThe operating system has no notion of current working directory, or the working directory cannot be dynamically changed.InappropriateTypeThe path refers to an existing non-directory object.[ENOTDIR]
listDirectory :: FilePath -> IO [FilePath] #
returns a list of all entries in dir without
the special entries (listDirectory dir. and ..).
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentThe operand is not a valid directory name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThe directory does not exist.[ENOENT, ENOTDIR]isPermissionErrorThe process has insufficient privileges to perform the operation.[EACCES]isFullErrorInsufficient resources are available to perform the operation.[EMFILE, ENFILE]InappropriateTypeThe path refers to an existing non-directory object.[ENOTDIR]
Since: directory-1.2.5.0
getDirectoryContents :: FilePath -> IO [FilePath] #
Similar to listDirectory, but always includes the special entries (.
and ..). (This applies to Windows as well.)
The operation may fail with the same exceptions as listDirectory.
exeExtension :: String #
Filename extension for executable files (including the dot if any)
(usually "" on POSIX systems and ".exe" on Windows or OS/2).
Since: directory-1.2.4.0
findFilesWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO [FilePath] #
findFilesWith predicate dirs name searches through the list of
directories (dirs) for files that have the given name and satisfy the
given predicate and returns the paths of those files. The directories
are checked in a left-to-right order and the paths are returned in the same
order.
If the name is a relative path, then for every search directory dir,
the function checks whether dir exists and satisfies the
predicate. If so, </> namedir is returned as one of the results. In
other words, the returned paths can be either relative or absolute
depending on the search directories were used. If there are no search
directories, no results are ever returned.</> name
If the name is an absolute path, then the function will return a single
result if the file exists and satisfies the predicate and no results
otherwise. This is irrespective of what search directories were given.
Since: directory-1.2.1.0
findFileWith :: (FilePath -> IO Bool) -> [FilePath] -> String -> IO (Maybe FilePath) #
Search through a given list of directories for a file that has the given name and satisfies the given predicate and return the path of the first occurrence. The directories are checked in a left-to-right order.
This is essentially a more performant version of findFilesWith that
always returns the first result, if any. Details can be found in the
documentation of findFilesWith.
Since: directory-1.2.6.0
findFiles :: [FilePath] -> String -> IO [FilePath] #
Search through the given list of directories for the given file and returns all paths where the given file exists.
The behavior is equivalent to findFilesWith. Details can be found in the
documentation of findFilesWith.
Since: directory-1.2.1.0
findFile :: [FilePath] -> String -> IO (Maybe FilePath) #
Search through the given list of directories for the given file.
The behavior is equivalent to findFileWith, returning only the first
occurrence. Details can be found in the documentation of findFileWith.
findExecutablesInDirectories :: [FilePath] -> String -> IO [FilePath] #
Given a name or path, findExecutable appends the exeExtension to the
query and searches for executable files in the list of given search
directories and returns all occurrences.
The behavior is equivalent to findFileWith using the given search
directories and testing each file for executable permissions. Details can
be found in the documentation of findFileWith.
Unlike other similarly named functions, findExecutablesInDirectories does
not use SearchPath from the Win32 API. The behavior of this function on
Windows is therefore equivalent to those on non-Windows platforms.
Since: directory-1.2.4.0
findExecutables :: String -> IO [FilePath] #
Search for executable files in a list of system-defined locations, which
generally includes PATH and possibly more.
On Windows, this only returns the first occurrence, if any. Its behavior
is therefore equivalent to findExecutable.
On non-Windows platforms, the behavior is equivalent to
findExecutablesInDirectories using the search directories from the PATH
environment variable. Details can be found in the documentation of
findExecutablesInDirectories.
Since: directory-1.2.2.0
findExecutable :: String -> IO (Maybe FilePath) #
Given the name or path of an executable file, findExecutable searches
for such a file in a list of system-defined locations, which generally
includes PATH and possibly more. The full path to the executable is
returned if found. For example, (findExecutable "ghc") would normally
give you the path to GHC.
The path returned by corresponds to the program
that would be executed by
findExecutable namecreateProcess
when passed the same string (as a RawCommand, not a ShellCommand),
provided that name is not a relative path with more than one segment.
On Windows, findExecutable calls the Win32 function
SearchPath,
which may search other places before checking the directories in the PATH
environment variable. Where it actually searches depends on registry
settings, but notably includes the directory containing the current
executable.
On non-Windows platforms, the behavior is equivalent to findFileWith
using the search directories from the PATH environment variable and
testing each file for executable permissions. Details can be found in the
documentation of findFileWith.
makeRelativeToCurrentDirectory :: FilePath -> IO FilePath #
Construct a path relative to the current directory, similar to
makeRelative.
The operation may fail with the same exceptions as getCurrentDirectory.
makeAbsolute :: FilePath -> IO FilePath #
Convert a path into an absolute path. If the given path is relative, the
current directory is prepended and then the combined result is normalized.
If the path is already absolute, the path is simply normalized. The
function preserves the presence or absence of the trailing path separator
unless the path refers to the root directory /.
If the path is already absolute, the operation never fails. Otherwise, the
operation may fail with the same exceptions as getCurrentDirectory.
Since: directory-1.2.2.0
canonicalizePath :: FilePath -> IO FilePath #
Make a path absolute, normalize the path, and remove as many indirections
from it as possible. Any trailing path separators are discarded via
dropTrailingPathSeparator. Additionally, on Windows the letter case of
the path is canonicalized.
Note: This function is a very big hammer. If you only need an absolute
path, makeAbsolute is sufficient for removing dependence on the current
working directory.
Indirections include the two special directories . and .., as well as
any symbolic links (and junction points on Windows). The input path need
not point to an existing file or directory. Canonicalization is performed
on the longest prefix of the path that points to an existing file or
directory. The remaining portion of the path that does not point to an
existing file or directory will still be normalized, but case
canonicalization and indirection removal are skipped as they are impossible
to do on a nonexistent path.
Most programs should not worry about the canonicity of a path. In particular, despite the name, the function does not truly guarantee canonicity of the returned path due to the presence of hard links, mount points, etc.
If the path points to an existing file or directory, then the output path shall also point to the same file or directory, subject to the condition that the relevant parts of the file system do not change while the function is still running. In other words, the function is definitively not atomic. The results can be utterly wrong if the portions of the path change while this function is running.
Since some indirections (symbolic links on all systems, .. on non-Windows
systems, and junction points on Windows) are dependent on the state of the
existing filesystem, the function can only make a conservative attempt by
removing such indirections from the longest prefix of the path that still
points to an existing file or directory.
Note that on Windows parent directories .. are always fully expanded
before the symbolic links, as consistent with the rest of the Windows API
(such as GetFullPathName). In contrast, on POSIX systems parent
directories .. are expanded alongside symbolic links from left to right.
To put this more concretely: if L is a symbolic link for R/P, then on
Windows L\.. refers to ., whereas on other operating systems L/..
refers to R.
Similar to normalise, passing an empty path is equivalent
to passing the current directory.
canonicalizePath can resolve at least 64 indirections in a single path,
more than what is supported by most operating systems. Therefore, it may
return the fully resolved path even though the operating system itself
would have long given up.
On Windows XP or earlier systems, junction expansion is not performed due
to their lack of GetFinalPathNameByHandle.
Changes since 1.2.3.0: The function has been altered to be more robust
and has the same exception behavior as makeAbsolute.
Changes since 1.3.0.0: The function no longer preserves the trailing path separator. File symbolic links that appear in the middle of a path are properly dereferenced. Case canonicalization and symbolic link expansion are now performed on Windows.
Copy a file with its associated metadata. If the destination file already exists, it is overwritten. There is no guarantee of atomicity in the replacement of the destination file. Neither path may refer to an existing directory. If the source and/or destination are symbolic links, the copy is performed on the targets of the links.
On Windows, it behaves like the Win32 function CopyFile, which copies various kinds of metadata including file attributes and security resource properties.
On Unix-like systems, permissions, access time, and modification time are preserved. If possible, the owner and group are also preserved. Note that the very act of copying can change the access time of the source file, hence the access times of the two files may differ after the operation completes.
Since: directory-1.2.6.0
Copy a file with its permissions. If the destination file already exists, it is replaced atomically. Neither path may refer to an existing directory. No exceptions are thrown if the permissions could not be copied.
Rename a file or directory. If the destination path already exists, it is replaced atomically. The destination path must not point to an existing directory. A conformant implementation need not support renaming files in all situations (e.g. renaming across different physical devices), but the constraints must be documented.
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentEither operand is not a valid file name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThe original file does not exist, or there is no path to the target.[ENOENT, ENOTDIR]isPermissionErrorThe process has insufficient privileges to perform the operation.[EROFS, EACCES, EPERM]isFullErrorInsufficient resources are available to perform the operation.[EDQUOT, ENOSPC, ENOMEM, EMLINK]UnsatisfiedConstraintsImplementation-dependent constraints are not satisfied.[EBUSY]UnsupportedOperationThe implementation does not support renaming in this situation.[EXDEV]InappropriateTypeEither the destination path refers to an existing directory, or one of the parent segments in the destination path is not a directory.[ENOTDIR, EISDIR, EINVAL, EEXIST, ENOTEMPTY]
Since: directory-1.2.7.0
renameFile :: FilePath -> FilePath -> IO () #
changes the name of an existing file system
object from old to new. If the new object already exists, it is
replaced by the old object. Neither path may refer to an existing
directory. A conformant implementation need not support renaming files
in all situations (e.g. renaming across different physical devices), but
the constraints must be documented.renameFile old new
On Windows, this calls MoveFileEx with MOVEFILE_REPLACE_EXISTING set,
which is not guaranteed to be atomic
(https://github.com/haskell/directory/issues/109).
On other platforms, this operation is atomic.
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentEither operand is not a valid file name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThe original file does not exist, or there is no path to the target.[ENOENT, ENOTDIR]isPermissionErrorThe process has insufficient privileges to perform the operation.[EROFS, EACCES, EPERM]isFullErrorInsufficient resources are available to perform the operation.[EDQUOT, ENOSPC, ENOMEM, EMLINK]UnsatisfiedConstraintsImplementation-dependent constraints are not satisfied.[EBUSY]UnsupportedOperationThe implementation does not support renaming in this situation.[EXDEV]InappropriateTypeEither path refers to an existing directory.[ENOTDIR, EISDIR, EINVAL, EEXIST, ENOTEMPTY]
renameDirectory :: FilePath -> FilePath -> IO () #
changes the name of an existing
directory from old to new. If the new directory
already exists, it is atomically replaced by the old directory.
If the new directory is neither the old directory nor an
alias of the old directory, it is removed as if by
renameDirectory old newremoveDirectory. A conformant implementation need not support
renaming directories in all situations (e.g. renaming to an existing
directory, or across different physical devices), but the constraints
must be documented.
On Win32 platforms, renameDirectory fails if the new directory already
exists.
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentEither operand is not a valid directory name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThe original directory does not exist, or there is no path to the target.[ENOENT, ENOTDIR]isPermissionErrorThe process has insufficient privileges to perform the operation.[EROFS, EACCES, EPERM]isFullErrorInsufficient resources are available to perform the operation.[EDQUOT, ENOSPC, ENOMEM, EMLINK]UnsatisfiedConstraintsImplementation-dependent constraints are not satisfied.[EBUSY, ENOTEMPTY, EEXIST]UnsupportedOperationThe implementation does not support renaming in this situation.[EINVAL, EXDEV]InappropriateTypeEither path refers to an existing non-directory object.[ENOTDIR, EISDIR]
removeFile :: FilePath -> IO () #
removeFile file removes the directory entry for an existing file
file, where file is not itself a directory. The
implementation may specify additional constraints which must be
satisfied before a file can be removed (e.g. the file may not be in
use by other processes).
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentThe operand is not a valid file name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThe file does not exist.[ENOENT, ENOTDIR]isPermissionErrorThe process has insufficient privileges to perform the operation.[EROFS, EACCES, EPERM]UnsatisfiedConstraintsImplementation-dependent constraints are not satisfied.[EBUSY]InappropriateTypeThe operand refers to an existing directory.[EPERM, EINVAL]
removePathForcibly :: FilePath -> IO () #
Removes a file or directory at path together with its contents and subdirectories. Symbolic links are removed without affecting their targets. If the path does not exist, nothing happens.
Unlike other removal functions, this function will also attempt to delete files marked as read-only or otherwise made unremovable due to permissions. As a result, if the removal is incomplete, the permissions or attributes on the remaining files may be altered. If there are hard links in the directory, then permissions on all related hard links may be altered.
If an entry within the directory vanishes while removePathForcibly is
running, it is silently ignored.
If an exception occurs while removing an entry, removePathForcibly will
still try to remove as many entries as it can before failing with an
exception. The first exception that it encountered is re-thrown.
Since: directory-1.2.7.0
removeDirectoryRecursive :: FilePath -> IO () #
removes an existing directory dir
together with its contents and subdirectories. Within this directory,
symbolic links are removed without affecting their targets.removeDirectoryRecursive dir
On Windows, the operation fails if dir is a directory symbolic link.
This operation is reported to be flaky on Windows so retry logic may be advisable. See: https://github.com/haskell/directory/pull/108
removeDirectory :: FilePath -> IO () #
removes an existing directory dir. The
implementation may specify additional constraints which must be
satisfied before a directory can be removed (e.g. the directory has to
be empty, or may not be in use by other processes). It is not legal
for an implementation to partially remove a directory unless the
entire directory is removed. A conformant implementation need not
support directory removal in all situations (e.g. removal of the root
directory).removeDirectory dir
The operation may fail with:
HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentThe operand is not a valid directory name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThe directory does not exist.[ENOENT, ENOTDIR]isPermissionErrorThe process has insufficient privileges to perform the operation.[EROFS, EACCES, EPERM]UnsatisfiedConstraintsImplementation-dependent constraints are not satisfied.[EBUSY, ENOTEMPTY, EEXIST]UnsupportedOperationThe implementation does not support removal in this situation.[EINVAL]InappropriateTypeThe operand refers to an existing non-directory object.[ENOTDIR]
Arguments
| :: Bool | Create its parents too? |
| -> FilePath | The path to the directory you want to make |
| -> IO () |
creates a new directory
createDirectoryIfMissing parents dirdir if it doesn't exist. If the first argument is True
the function will also create all parent directories if they are missing.
createDirectory :: FilePath -> IO () #
creates a new directory createDirectory dirdir which is
initially empty, or as near to empty as the operating system
allows.
The operation may fail with:
isPermissionErrorThe process has insufficient privileges to perform the operation.[EROFS, EACCES]isAlreadyExistsErrorThe operand refers to a directory that already exists.[EEXIST]HardwareFaultA physical I/O error has occurred.[EIO]InvalidArgumentThe operand is not a valid directory name.[ENAMETOOLONG, ELOOP]isDoesNotExistErrorThere is no path to the directory.[ENOENT, ENOTDIR]isFullErrorInsufficient resources (virtual memory, process file descriptors, physical disk space, etc.) are available to perform the operation.[EDQUOT, ENOSPC, ENOMEM, EMLINK]InappropriateTypeThe path refers to an existing non-directory object.[EEXIST]
copyPermissions :: FilePath -> FilePath -> IO () #
Copy the permissions of one file to another. This reproduces the
permissions more accurately than using getPermissions followed by
setPermissions.
On Windows, this copies only the read-only attribute.
On POSIX systems, this is equivalent to stat followed by chmod.
setPermissions :: FilePath -> Permissions -> IO () #
Set the permissions of a file or directory.
On Windows, this is only capable of changing the writable permission,
which corresponds to the "read-only" attribute. Changing the other
permissions has no effect.
On POSIX systems, this sets the owner permissions.
The operation may fail with:
isPermissionErrorif the user is not permitted to set the permissions, orisDoesNotExistErrorif the file or directory does not exist.
getPermissions :: FilePath -> IO Permissions #
Get the permissions of a file or directory.
On Windows, the writable permission corresponds to the "read-only"
attribute. The executable permission is set if the file extension is of
an executable file type. The readable permission is always set.
On POSIX systems, this returns the result of access.
The operation may fail with:
isPermissionErrorif the user is not permitted to access the permissions, orisDoesNotExistErrorif the file or directory does not exist.
setOwnerSearchable :: Bool -> Permissions -> Permissions #
setOwnerExecutable :: Bool -> Permissions -> Permissions #
setOwnerWritable :: Bool -> Permissions -> Permissions #
setOwnerReadable :: Bool -> Permissions -> Permissions #
data Permissions #
Instances
| Read Permissions | |
Defined in System.Directory.Internal.Common Methods readsPrec :: Int -> ReadS Permissions # readList :: ReadS [Permissions] # readPrec :: ReadPrec Permissions # readListPrec :: ReadPrec [Permissions] # | |
| Show Permissions | |
Defined in System.Directory.Internal.Common Methods showsPrec :: Int -> Permissions -> ShowS # show :: Permissions -> String # showList :: [Permissions] -> ShowS # | |
| Eq Permissions | |
Defined in System.Directory.Internal.Common | |
| Ord Permissions | |
Defined in System.Directory.Internal.Common Methods compare :: Permissions -> Permissions -> Ordering # (<) :: Permissions -> Permissions -> Bool # (<=) :: Permissions -> Permissions -> Bool # (>) :: Permissions -> Permissions -> Bool # (>=) :: Permissions -> Permissions -> Bool # max :: Permissions -> Permissions -> Permissions # min :: Permissions -> Permissions -> Permissions # | |
data XdgDirectory #
Special directories for storing user-specific application data, configuration, and cache files, as specified by the XDG Base Directory Specification.
Note: On Windows, XdgData and XdgConfig usually map to the same
directory.
Since: directory-1.2.3.0
Constructors
| XdgData | For data files (e.g. images).
It uses the |
| XdgConfig | For configuration files.
It uses the |
| XdgCache | For non-essential files (e.g. cache).
It uses the |
| XdgState | For data that should persist between (application) restarts,
but that is not important or portable enough to the user that it
should be stored in Since: directory-1.3.7.0 |
Instances
data XdgDirectoryList #
Search paths for various application data, as specified by the XDG Base Directory Specification.
The list of paths is split using searchPathSeparator,
which on Windows is a semicolon.
Note: On Windows, XdgDataDirs and XdgConfigDirs usually yield the same
result.
Since: directory-1.3.2.0
Constructors
| XdgDataDirs | For data files (e.g. images).
It uses the |
| XdgConfigDirs | For configuration files.
It uses the |
Instances
Returns width of a character in a monospace font: 0 for a combining character, 1 for a regular character, 2 for an East Asian wide character. Ambiguous characters are treated as width 1.
isAbsolute :: FilePath -> Bool #
not . isRelativeisAbsolute x == not (isRelative x)
isRelative :: FilePath -> Bool #
Is a path relative, or is it fixed to the root?
Windows: isRelative "path\\test" == True Windows: isRelative "c:\\test" == False Windows: isRelative "c:test" == True Windows: isRelative "c:\\" == False Windows: isRelative "c:/" == False Windows: isRelative "c:" == True Windows: isRelative "\\\\foo" == False Windows: isRelative "\\\\?\\foo" == False Windows: isRelative "\\\\?\\UNC\\foo" == False Windows: isRelative "/foo" == True Windows: isRelative "\\foo" == True Posix: isRelative "test/path" == True Posix: isRelative "/test" == False Posix: isRelative "/" == False
According to [1]:
- "A UNC name of any format [is never relative]."
- "You cannot use the "\?" prefix with a relative path."
makeValid :: FilePath -> FilePath #
Take a FilePath and make it valid; does not change already valid FILEPATHs.
isValid (makeValid x) isValid x ==> makeValid x == x makeValid "" == "_" makeValid "file\0name" == "file_name" Windows: makeValid "c:\\already\\/valid" == "c:\\already\\/valid" Windows: makeValid "c:\\test:of_test" == "c:\\test_of_test" Windows: makeValid "test*" == "test_" Windows: makeValid "c:\\test\\nul" == "c:\\test\\nul_" Windows: makeValid "c:\\test\\prn.txt" == "c:\\test\\prn_.txt" Windows: makeValid "c:\\test/prn.txt" == "c:\\test/prn_.txt" Windows: makeValid "c:\\nul\\file" == "c:\\nul_\\file" Windows: makeValid "\\\\\\foo" == "\\\\drive" Windows: makeValid "\\\\?\\D:file" == "\\\\?\\D:\\file" Windows: makeValid "nul .txt" == "nul _.txt"
Is a FilePath valid, i.e. could you create a file like it? This function checks for invalid names, and invalid characters, but does not check if length limits are exceeded, as these are typically filesystem dependent.
isValid "" == False
isValid "\0" == False
Posix: isValid "/random_ path:*" == True
Posix: isValid x == not (null x)
Windows: isValid "c:\\test" == True
Windows: isValid "c:\\test:of_test" == False
Windows: isValid "test*" == False
Windows: isValid "c:\\test\\nul" == False
Windows: isValid "c:\\test\\prn.txt" == False
Windows: isValid "c:\\nul\\file" == False
Windows: isValid "\\\\" == False
Windows: isValid "\\\\\\foo" == False
Windows: isValid "\\\\?\\D:file" == False
Windows: isValid "foo\tbar" == False
Windows: isValid "nul .txt" == False
Windows: isValid " nul.txt" == Truenormalise :: FilePath -> FilePath #
Normalise a file
- // outside of the drive can be made blank
- / ->
pathSeparator - ./ -> ""
Does not remove "..", because of symlinks.
Posix: normalise "/file/\\test////" == "/file/\\test/"
Posix: normalise "/file/./test" == "/file/test"
Posix: normalise "/test/file/../bob/fred/" == "/test/file/../bob/fred/"
Posix: normalise "../bob/fred/" == "../bob/fred/"
Posix: normalise "/a/../c" == "/a/../c"
Posix: normalise "./bob/fred/" == "bob/fred/"
Windows: normalise "c:\\file/bob\\" == "C:\\file\\bob\\"
Windows: normalise "c:\\" == "C:\\"
Windows: normalise "c:\\\\\\\\" == "C:\\"
Windows: normalise "C:.\\" == "C:"
Windows: normalise "\\\\server\\test" == "\\\\server\\test"
Windows: normalise "//server/test" == "\\\\server\\test"
Windows: normalise "c:/file" == "C:\\file"
Windows: normalise "/file" == "\\file"
Windows: normalise "\\" == "\\"
Windows: normalise "/./" == "\\"
normalise "." == "."
Posix: normalise "./" == "./"
Posix: normalise "./." == "./"
Posix: normalise "/./" == "/"
Posix: normalise "/" == "/"
Posix: normalise "bob/fred/." == "bob/fred/"
Posix: normalise "//home" == "/home"makeRelative :: FilePath -> FilePath -> FilePath #
Contract a filename, based on a relative path. Note that the resulting path
will never introduce .. paths, as the presence of symlinks means ../b
may not reach a/b if it starts from a/c. For a worked example see
this blog post.
The corresponding makeAbsolute function can be found in
System.Directory.
makeRelative "/directory" "/directory/file.ext" == "file.ext"
Valid x => makeRelative (takeDirectory x) x `equalFilePath` takeFileName x
makeRelative x x == "."
Valid x y => equalFilePath x y || (isRelative x && makeRelative y x == x) || equalFilePath (y </> makeRelative y x) x
Windows: makeRelative "C:\\Home" "c:\\home\\bob" == "bob"
Windows: makeRelative "C:\\Home" "c:/home/bob" == "bob"
Windows: makeRelative "C:\\Home" "D:\\Home\\Bob" == "D:\\Home\\Bob"
Windows: makeRelative "C:\\Home" "C:Home\\Bob" == "C:Home\\Bob"
Windows: makeRelative "/Home" "/home/bob" == "bob"
Windows: makeRelative "/" "//" == "//"
Posix: makeRelative "/Home" "/home/bob" == "/home/bob"
Posix: makeRelative "/home/" "/home/bob/foo/bar" == "bob/foo/bar"
Posix: makeRelative "/fred" "bob" == "bob"
Posix: makeRelative "/file/test" "/file/test/fred" == "fred"
Posix: makeRelative "/file/test" "/file/test/fred/" == "fred/"
Posix: makeRelative "some/path" "some/path/a/b/c" == "a/b/c"equalFilePath :: FilePath -> FilePath -> Bool #
Equality of two FILEPATHs.
If you call System.Directory.canonicalizePath
first this has a much better chance of working.
Note that this doesn't follow symlinks or DOSNAM~1s.
Similar to normalise, this does not expand "..", because of symlinks.
x == y ==> equalFilePath x y
normalise x == normalise y ==> equalFilePath x y
equalFilePath "foo" "foo/"
not (equalFilePath "/a/../c" "/c")
not (equalFilePath "foo" "/foo")
Posix: not (equalFilePath "foo" "FOO")
Windows: equalFilePath "foo" "FOO"
Windows: not (equalFilePath "C:" "C:/")joinPath :: [FilePath] -> FilePath #
Join path elements back together.
joinPath z == foldr (</>) "" z joinPath ["/","directory/","file.ext"] == "/directory/file.ext" Valid x => joinPath (splitPath x) == x joinPath [] == "" Posix: joinPath ["test","file","path"] == "test/file/path"
splitDirectories :: FilePath -> [FilePath] #
Just as splitPath, but don't add the trailing slashes to each element.
splitDirectories "/directory/file.ext" == ["/","directory","file.ext"]
splitDirectories "test/file" == ["test","file"]
splitDirectories "/test/file" == ["/","test","file"]
Windows: splitDirectories "C:\\test\\file" == ["C:\\", "test", "file"]
Valid x => joinPath (splitDirectories x) `equalFilePath` x
splitDirectories "" == []
Windows: splitDirectories "C:\\test\\\\\\file" == ["C:\\", "test", "file"]
splitDirectories "/test///file" == ["/","test","file"]splitPath :: FilePath -> [FilePath] #
Split a path by the directory separator.
splitPath "/directory/file.ext" == ["/","directory/","file.ext"] concat (splitPath x) == x splitPath "test//item/" == ["test//","item/"] splitPath "test/item/file" == ["test/","item/","file"] splitPath "" == [] Windows: splitPath "c:\\test\\path" == ["c:\\","test\\","path"] Posix: splitPath "/file/test" == ["/","file/","test"]
(</>) :: FilePath -> FilePath -> FilePath infixr 5 #
Combine two paths with a path separator.
If the second path starts with a path separator or a drive letter, then it returns the second.
The intention is that readFile (dir will access the same file as
</> file)setCurrentDirectory dir; readFile file.
Posix: "/directory" </> "file.ext" == "/directory/file.ext"
Windows: "/directory" </> "file.ext" == "/directory\\file.ext"
"directory" </> "/file.ext" == "/file.ext"
Valid x => (takeDirectory x </> takeFileName x) `equalFilePath` xCombined:
Posix: "/" </> "test" == "/test" Posix: "home" </> "bob" == "home/bob" Posix: "x:" </> "foo" == "x:/foo" Windows: "C:\\foo" </> "bar" == "C:\\foo\\bar" Windows: "home" </> "bob" == "home\\bob"
Not combined:
Posix: "home" </> "/bob" == "/bob" Windows: "home" </> "C:\\bob" == "C:\\bob"
Not combined (tricky):
On Windows, if a filepath starts with a single slash, it is relative to the
root of the current drive. In [1], this is (confusingly) referred to as an
absolute path.
The current behavior of </> is to never combine these forms.
Windows: "home" </> "/bob" == "/bob" Windows: "home" </> "\\bob" == "\\bob" Windows: "C:\\home" </> "\\bob" == "\\bob"
On Windows, from [1]: "If a file name begins with only a disk designator
but not the backslash after the colon, it is interpreted as a relative path
to the current directory on the drive with the specified letter."
The current behavior of </> is to never combine these forms.
Windows: "D:\\foo" </> "C:bar" == "C:bar" Windows: "C:\\foo" </> "C:bar" == "C:bar"
replaceDirectory :: FilePath -> String -> FilePath #
Set the directory, keeping the filename the same.
replaceDirectory "root/file.ext" "/directory/" == "/directory/file.ext" Valid x => replaceDirectory x (takeDirectory x) `equalFilePath` x
takeDirectory :: FilePath -> FilePath #
Get the directory name, move up one level.
takeDirectory "/directory/other.ext" == "/directory"
isPrefixOf (takeDirectory x) x || takeDirectory x == "."
takeDirectory "foo" == "."
takeDirectory "/" == "/"
takeDirectory "/foo" == "/"
takeDirectory "/foo/bar/baz" == "/foo/bar"
takeDirectory "/foo/bar/baz/" == "/foo/bar/baz"
takeDirectory "foo/bar/baz" == "foo/bar"
Windows: takeDirectory "foo\\bar" == "foo"
Windows: takeDirectory "foo\\bar\\\\" == "foo\\bar"
Windows: takeDirectory "C:\\" == "C:\\"dropTrailingPathSeparator :: FilePath -> FilePath #
Remove any trailing path separators
dropTrailingPathSeparator "file/test/" == "file/test"
dropTrailingPathSeparator "/" == "/"
Windows: dropTrailingPathSeparator "\\" == "\\"
Posix: not (hasTrailingPathSeparator (dropTrailingPathSeparator x)) || isDrive xaddTrailingPathSeparator :: FilePath -> FilePath #
Add a trailing file path separator if one is not already present.
hasTrailingPathSeparator (addTrailingPathSeparator x) hasTrailingPathSeparator x ==> addTrailingPathSeparator x == x Posix: addTrailingPathSeparator "test/rest" == "test/rest/"
hasTrailingPathSeparator :: FilePath -> Bool #
Is an item either a directory or the last character a path separator?
hasTrailingPathSeparator "test" == False hasTrailingPathSeparator "test/" == True
replaceBaseName :: FilePath -> String -> FilePath #
Set the base name.
replaceBaseName "/directory/other.ext" "file" == "/directory/file.ext" replaceBaseName "file/test.txt" "bob" == "file/bob.txt" replaceBaseName "fred" "bill" == "bill" replaceBaseName "/dave/fred/bob.gz.tar" "new" == "/dave/fred/new.tar" Valid x => replaceBaseName x (takeBaseName x) == x
takeBaseName :: FilePath -> String #
Get the base name, without an extension or path.
takeBaseName "/directory/file.ext" == "file" takeBaseName "file/test.txt" == "test" takeBaseName "dave.ext" == "dave" takeBaseName "" == "" takeBaseName "test" == "test" takeBaseName (addTrailingPathSeparator x) == "" takeBaseName "file/file.tar.gz" == "file.tar"
takeFileName :: FilePath -> FilePath #
Get the file name.
takeFileName "/directory/file.ext" == "file.ext" takeFileName "test/" == "" isSuffixOf (takeFileName x) x takeFileName x == snd (splitFileName x) Valid x => takeFileName (replaceFileName x "fred") == "fred" Valid x => takeFileName (x </> "fred") == "fred" Valid x => isRelative (takeFileName x)
dropFileName :: FilePath -> FilePath #
Drop the filename. Unlike takeDirectory, this function will leave
a trailing path separator on the directory.
dropFileName "/directory/file.ext" == "/directory/" dropFileName x == fst (splitFileName x)
replaceFileName :: FilePath -> String -> FilePath #
Set the filename.
replaceFileName "/directory/other.txt" "file.ext" == "/directory/file.ext" Valid x => replaceFileName x (takeFileName x) == x
splitFileName :: FilePath -> (String, String) #
Split a filename into directory and file. </> is the inverse.
The first component will often end with a trailing slash.
splitFileName "/directory/file.ext" == ("/directory/","file.ext")
Valid x => uncurry (</>) (splitFileName x) == x || fst (splitFileName x) == "./"
Valid x => isValid (fst (splitFileName x))
splitFileName "file/bob.txt" == ("file/", "bob.txt")
splitFileName "file/" == ("file/", "")
splitFileName "bob" == ("./", "bob")
Posix: splitFileName "/" == ("/","")
Windows: splitFileName "c:" == ("c:","")
Windows: splitFileName "\\\\?\\A:\\fred" == ("\\\\?\\A:\\","fred")Is an element a drive
Posix: isDrive "/" == True
Posix: isDrive "/foo" == False
Windows: isDrive "C:\\" == True
Windows: isDrive "C:\\foo" == False
isDrive "" == FalsehasDrive :: FilePath -> Bool #
Does a path have a drive.
not (hasDrive x) == null (takeDrive x)
Posix: hasDrive "/foo" == True
Windows: hasDrive "C:\\foo" == True
Windows: hasDrive "C:foo" == True
hasDrive "foo" == False
hasDrive "" == FalsejoinDrive :: FilePath -> FilePath -> FilePath #
Join a drive and the rest of the path.
Valid x => uncurry joinDrive (splitDrive x) == x Windows: joinDrive "C:" "foo" == "C:foo" Windows: joinDrive "C:\\" "bar" == "C:\\bar" Windows: joinDrive "\\\\share" "foo" == "\\\\share\\foo" Windows: joinDrive "/:" "foo" == "/:\\foo"
splitDrive :: FilePath -> (FilePath, FilePath) #
Split a path into a drive and a path. On Posix, / is a Drive.
uncurry (<>) (splitDrive x) == x
Windows: splitDrive "file" == ("","file")
Windows: splitDrive "c:/file" == ("c:/","file")
Windows: splitDrive "c:\\file" == ("c:\\","file")
Windows: splitDrive "\\\\shared\\test" == ("\\\\shared\\","test")
Windows: splitDrive "\\\\shared" == ("\\\\shared","")
Windows: splitDrive "\\\\?\\UNC\\shared\\file" == ("\\\\?\\UNC\\shared\\","file")
Windows: splitDrive "\\\\?\\UNCshared\\file" == ("\\\\?\\","UNCshared\\file")
Windows: splitDrive "\\\\?\\d:\\file" == ("\\\\?\\d:\\","file")
Windows: splitDrive "/d" == ("","/d")
Posix: splitDrive "/test" == ("/","test")
Posix: splitDrive "//test" == ("//","test")
Posix: splitDrive "test/file" == ("","test/file")
Posix: splitDrive "file" == ("","file")replaceExtensions :: FilePath -> String -> FilePath #
Replace all extensions of a file with a new extension. Note
that replaceExtension and addExtension both work for adding
multiple extensions, so only required when you need to drop
all extensions first.
replaceExtensions "file.fred.bob" "txt" == "file.txt" replaceExtensions "file.fred.bob" "tar.gz" == "file.tar.gz"
takeExtensions :: FilePath -> String #
Get all extensions.
takeExtensions "/directory/path.ext" == ".ext" takeExtensions "file.tar.gz" == ".tar.gz"
dropExtensions :: FilePath -> FilePath #
Drop all extensions.
dropExtensions "/directory/path.ext" == "/directory/path" dropExtensions "file.tar.gz" == "file" not $ hasExtension $ dropExtensions x not $ any isExtSeparator $ takeFileName $ dropExtensions x
splitExtensions :: FilePath -> (FilePath, String) #
Split on all extensions.
splitExtensions "/directory/path.ext" == ("/directory/path",".ext")
splitExtensions "file.tar.gz" == ("file",".tar.gz")
uncurry (<>) (splitExtensions x) == x
Valid x => uncurry addExtension (splitExtensions x) == x
splitExtensions "file.tar.gz" == ("file",".tar.gz")stripExtension :: String -> FilePath -> Maybe FilePath #
Drop the given extension from a FilePath, and the "." preceding it.
Returns Nothing if the FilePath does not have the given extension, or
Just and the part before the extension if it does.
This function can be more predictable than dropExtensions, especially if the filename
might itself contain . characters.
stripExtension "hs.o" "foo.x.hs.o" == Just "foo.x" stripExtension "hi.o" "foo.x.hs.o" == Nothing dropExtension x == fromJust (stripExtension (takeExtension x) x) dropExtensions x == fromJust (stripExtension (takeExtensions x) x) stripExtension ".c.d" "a.b.c.d" == Just "a.b" stripExtension ".c.d" "a.b..c.d" == Just "a.b." stripExtension "baz" "foo.bar" == Nothing stripExtension "bar" "foobar" == Nothing stripExtension "" x == Just x
isExtensionOf :: String -> FilePath -> Bool #
Does the given filename have the specified extension?
"png" `isExtensionOf` "/directory/file.png" == True ".png" `isExtensionOf` "/directory/file.png" == True ".tar.gz" `isExtensionOf` "bar/foo.tar.gz" == True "ar.gz" `isExtensionOf` "bar/foo.tar.gz" == False "png" `isExtensionOf` "/directory/file.png.jpg" == False "csv/table.csv" `isExtensionOf` "/data/csv/table.csv" == False
hasExtension :: FilePath -> Bool #
Does the given filename have an extension?
hasExtension "/directory/path.ext" == True hasExtension "/directory/path" == False null (takeExtension x) == not (hasExtension x)
addExtension :: FilePath -> String -> FilePath #
Add an extension, even if there is already one there, equivalent to <.>.
addExtension "/directory/path" "ext" == "/directory/path.ext" addExtension "file.txt" "bib" == "file.txt.bib" addExtension "file." ".bib" == "file..bib" addExtension "file" ".bib" == "file.bib" addExtension "/" "x" == "/.x" addExtension x "" == x Valid x => takeFileName (addExtension (addTrailingPathSeparator x) "ext") == ".ext" Windows: addExtension "\\\\share" ".txt" == "\\\\share\\.txt"
dropExtension :: FilePath -> FilePath #
Remove last extension, and the "." preceding it.
dropExtension "/directory/path.ext" == "/directory/path" dropExtension x == fst (splitExtension x)
(<.>) :: FilePath -> String -> FilePath infixr 7 #
Add an extension, even if there is already one there, equivalent to addExtension.
"/directory/path" <.> "ext" == "/directory/path.ext" "/directory/path" <.> ".ext" == "/directory/path.ext"
replaceExtension :: FilePath -> String -> FilePath #
Set the extension of a file, overwriting one if already present, equivalent to -<.>.
replaceExtension "/directory/path.txt" "ext" == "/directory/path.ext" replaceExtension "/directory/path.txt" ".ext" == "/directory/path.ext" replaceExtension "file.txt" ".bob" == "file.bob" replaceExtension "file.txt" "bob" == "file.bob" replaceExtension "file" ".bob" == "file.bob" replaceExtension "file.txt" "" == "file" replaceExtension "file.fred.bob" "txt" == "file.fred.txt" replaceExtension x y == addExtension (dropExtension x) y
(-<.>) :: FilePath -> String -> FilePath infixr 7 #
Remove the current extension and add another, equivalent to replaceExtension.
"/directory/path.txt" -<.> "ext" == "/directory/path.ext" "/directory/path.txt" -<.> ".ext" == "/directory/path.ext" "foo.o" -<.> "c" == "foo.c"
takeExtension :: FilePath -> String #
Get the extension of a file, returns "" for no extension, .ext otherwise.
takeExtension "/directory/path.ext" == ".ext" takeExtension x == snd (splitExtension x) Valid x => takeExtension (addExtension x "ext") == ".ext" Valid x => takeExtension (replaceExtension x "ext") == ".ext"
splitExtension :: FilePath -> (String, String) #
Split on the extension. addExtension is the inverse.
splitExtension "/directory/path.ext" == ("/directory/path",".ext")
uncurry (<>) (splitExtension x) == x
Valid x => uncurry addExtension (splitExtension x) == x
splitExtension "file.txt" == ("file",".txt")
splitExtension "file" == ("file","")
splitExtension "file/file.txt" == ("file/file",".txt")
splitExtension "file.txt/boris" == ("file.txt/boris","")
splitExtension "file.txt/boris.ext" == ("file.txt/boris",".ext")
splitExtension "file/path.txt.bob.fred" == ("file/path.txt.bob",".fred")
splitExtension "file/path.txt/" == ("file/path.txt/","")getSearchPath :: IO [FilePath] #
Get a list of FILEPATHs in the $PATH variable.
splitSearchPath :: String -> [FilePath] #
Take a string, split it on the searchPathSeparator character.
Blank items are ignored on Windows, and converted to . on Posix.
On Windows path elements are stripped of quotes.
Follows the recommendations in http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html
Posix: splitSearchPath "File1:File2:File3" == ["File1","File2","File3"] Posix: splitSearchPath "File1::File2:File3" == ["File1",".","File2","File3"] Windows: splitSearchPath "File1;File2;File3" == ["File1","File2","File3"] Windows: splitSearchPath "File1;;File2;File3" == ["File1","File2","File3"] Windows: splitSearchPath "File1;\"File2\";File3" == ["File1","File2","File3"]
isExtSeparator :: Char -> Bool #
Is the character an extension character?
isExtSeparator a == (a == extSeparator)
extSeparator :: Char #
File extension character
extSeparator == '.'
isSearchPathSeparator :: Char -> Bool #
Is the character a file separator?
isSearchPathSeparator a == (a == searchPathSeparator)
The character that is used to separate the entries in the $PATH environment variable.
Windows: searchPathSeparator == ';' Posix: searchPathSeparator == ':'
isPathSeparator :: Char -> Bool #
Rather than using (== , use this. Test if something
is a path separator.pathSeparator)
isPathSeparator a == (a `elem` pathSeparators)
pathSeparators :: [Char] #
The list of all possible separators.
Windows: pathSeparators == ['\\', '/'] Posix: pathSeparators == ['/'] pathSeparator `elem` pathSeparators
pathSeparator :: Char #
The character that separates directories. In the case where more than
one character is possible, pathSeparator is the 'ideal' one.
Windows: pathSeparator == '\\' Posix: pathSeparator == '/' isPathSeparator pathSeparator
type AssertionPredicate = IO Bool #
The result of an assertion that hasn't been evaluated yet.
Most test cases follow the following steps:
- Do some processing or an action.
- Assert certain conditions.
However, this flow is not always suitable. AssertionPredicate allows for
additional steps to be inserted without the initial action to be affected
by side effects. Additionally, clean-up can be done before the test case
has a chance to end. A potential work flow is:
- Write data to a file.
- Read data from a file, evaluate conditions.
- Clean up the file.
- Assert that the side effects of the read operation meet certain conditions.
- Assert that the conditions evaluated in step 2 are met.
class Assertable t where #
Allows the extension of the assertion mechanism.
Since an Assertion can be a sequence of Assertions and IO actions,
there is a fair amount of flexibility of what can be achieved. As a rule,
the resulting Assertion should be the body of a TestCase or part of
a TestCase; it should not be used to assert multiple, independent
conditions.
If more complex arrangements of assertions are needed, Test and
Testable should be used.
Instances
| Assertable String | |
Defined in Test.Tasty.HUnit.Orig | |
| Assertable () | |
Defined in Test.Tasty.HUnit.Orig | |
| Assertable Bool | |
Defined in Test.Tasty.HUnit.Orig | |
| Assertable t => Assertable (IO t) | |
Defined in Test.Tasty.HUnit.Orig | |
data HUnitFailure #
Exception thrown by assertFailure etc.
Constructors
| HUnitFailure (Maybe SrcLoc) String |
Instances
| Exception HUnitFailure | |
Defined in Test.Tasty.HUnit.Orig Methods toException :: HUnitFailure -> SomeException # fromException :: SomeException -> Maybe HUnitFailure # displayException :: HUnitFailure -> String # | |
| Show HUnitFailure | |
Defined in Test.Tasty.HUnit.Orig Methods showsPrec :: Int -> HUnitFailure -> ShowS # show :: HUnitFailure -> String # showList :: [HUnitFailure] -> ShowS # | |
| Eq HUnitFailure | |
Defined in Test.Tasty.HUnit.Orig | |
class AssertionPredicable t where #
An ad-hoc class used to overload the @? operator.
The only intended instances of this class are and Bool.IO Bool
You shouldn't need to interact with this class directly.
Methods
assertionPredicate :: t -> IO Bool #
Instances
| AssertionPredicable Bool | |
Defined in Test.Tasty.HUnit.Orig Methods assertionPredicate :: Bool -> IO Bool # | |
| AssertionPredicable t => AssertionPredicable (IO t) | |
Defined in Test.Tasty.HUnit.Orig Methods assertionPredicate :: IO t -> IO Bool # | |
Arguments
| :: HasCallStack | |
| => String | A message that is displayed with the assertion failure |
| -> IO a |
Unconditionally signals that a failure has occured. All other assertions can be expressed with the form:
if conditionIsMet
then return ()
else assertFailure msg
Arguments
| :: HasCallStack | |
| => String | The message that is displayed if the assertion fails |
| -> Bool | The condition |
| -> Assertion |
Asserts that the specified condition holds.
Arguments
| :: (Eq a, Show a, HasCallStack) | |
| => String | The message prefix |
| -> a | The expected value |
| -> a | The actual value |
| -> Assertion |
Asserts that the specified actual value is equal to the expected value. The output message will contain the prefix, the expected value, and the actual value.
If the prefix is the empty string (i.e., ""), then the prefix is omitted
and only the expected and actual values are output.
Arguments
| :: (Eq a, Show a, HasCallStack) | |
| => a | The expected value |
| -> a | The actual value |
| -> Assertion |
Asserts that the specified actual value is equal to the expected value (with the expected value on the left-hand side).
Arguments
| :: (Eq a, Show a, HasCallStack) | |
| => a | The actual value |
| -> a | The expected value |
| -> Assertion |
Asserts that the specified actual value is equal to the expected value (with the actual value on the left-hand side).
Arguments
| :: (AssertionPredicable t, HasCallStack) | |
| => t | A value of which the asserted condition is predicated |
| -> String | A message that is displayed if the assertion fails |
| -> Assertion |
An infix and flipped version of assertBool. E.g. instead of
assertBool "Non-empty list" (null [1])
you can write
null [1] @? "Non-empty list"
@? is also overloaded to accept predicates, so instead
ofIO Bool
do e <- doesFileExist "test" e @? "File does not exist"
you can write
doesFileExist "test" @? "File does not exist"
Arguments
| :: HasCallStack | |
| => String | The message that is displayed with the assertion failure |
| -> Assertion |
Signals an assertion failure if a non-empty message (i.e., a message
other than "") is passed.
testCaseSteps :: TestName -> ((String -> IO ()) -> Assertion) -> TestTree #
Create a multi-step unit test.
Example:
main = defaultMain $ testCaseSteps "Multi-step test" $ \step -> do step "Preparing..." -- do something step "Running part 1" -- do something step "Running part 2" -- do something assertFailure "BAM!" step "Running part 3" -- do something
The step calls are mere annotations. They let you see which steps were
performed successfully, and which step failed.
You can think of step
as putStrLn, except putStrLn would mess up the output with the
console reporter and get lost with the others.
For the example above, the output will be
Multi-step test: FAIL
Preparing...
Running part 1
Running part 2
BAM!
1 out of 1 tests failed (0.00s)Note that:
- Tasty still treats this as a single test, even though it consists of multiple steps.
- The execution stops after the first failure. When we are looking at a failed test, we know that all displayed steps but the last one were successful, and the last one failed. The steps after the failed one are not displayed, since they didn't run.
testCaseInfo :: TestName -> IO String -> TestTree #
Like testCase, except in case the test succeeds, the returned string
will be shown as the description. If the empty string is returned, it
will be ignored.
An assertion is simply an IO action. Assertion failure is indicated
by throwing an exception, typically HUnitFailure.
Instead of throwing the exception directly, you should use
functions like assertFailure and assertBool.
Test cases are composed of a sequence of one or more assertions.
tests_Read :: TestTree #
saveLatestDatesForFiles :: [LatestDatesForFile] -> IO () #
Save each file's latest dates.
saveLatestDates :: LatestDates -> FilePath -> IO () #
Save the given latest date(s) seen in the given data FILE, in a hidden file named .latest.FILE, creating it if needed.
ensureJournalFileExists :: FilePath -> IO () #
Ensure there is a journal file at the given path, creating an empty one if needed.
On Windows, also ensure that the path contains no trailing dots
which could cause data loss (see isWindowsUnsafeDotPath).
requireJournalFileExists :: FilePath -> IO () #
If the specified journal file does not exist (and is not "-"), give a helpful error and quit.
orDieTrying :: MonadIO m => ExceptT String m a -> m a #
Extract ExceptT to the IO monad, failing with an error message if necessary.
readJournalFiles' :: [PrefixedFilePath] -> IO Journal #
An easy version of readJournalFiles' which assumes default options, and fails
in the IO monad.
readJournalFile' :: PrefixedFilePath -> IO Journal #
An easy version of readJournalFile which assumes default options, and fails
in the IO monad.
readJournal' :: Text -> IO Journal #
An easy version of readJournal which assumes default options, and fails
in the IO monad.
journalStrictChecks :: Journal -> Either String () #
Run the extra -s/--strict checks on a journal, returning the first error message if any of them fail.
readJournalFilesAndLatestDates :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO (Journal, [LatestDatesForFile]) #
readJournalFiles :: InputOpts -> [PrefixedFilePath] -> ExceptT String IO Journal #
Read a Journal from each specified file path (using readJournalFile)
and combine them into one; or return the first error message.
Strict checks, if enabled, are deferred till the end.
Writing .latest files, if enabled, is also deferred till the end,
and happens only if strict checks pass.
Combining Journals means concatenating them, basically. The parse state resets at the start of each file, which means that directives & aliases do not affect subsequent sibling or parent files. They do affect included child files though. Also the final parse state saved in the Journal does span all files.
readJournalFile :: InputOpts -> PrefixedFilePath -> ExceptT String IO Journal #
Read a Journal from this file, or from stdin if the file path is -, with strict checks if enabled, or return an error message. The file path can have a READER: prefix.
The reader (data format) to use is determined from (in priority order):
the mformat_ specified in the input options, if any;
the file path's READER: prefix, if any;
a recognised file name extension.
if none of these identify a known reader, the journal reader is used.
The input options can also configure balance assertion checking, automated posting generation, a rules file for converting CSV data, etc.
If using --new, and if latest-file writing is enabled in input options, and after passing strict checks if enabled, a .latest.FILE file will be created/updated (for the main file only, not for included files), to remember the latest transaction date (and how many transactions on this date) successfully read.
readJournal :: InputOpts -> Maybe FilePath -> Text -> ExceptT String IO Journal #
readJournal iopts mfile txt
Read a Journal from some text, with strict checks if enabled, or return an error message.
The reader (data format) is chosen based on, in this order:
- a reader name provided in
iopts - a reader prefix in the
mfilepath - a file extension in
mfile
If none of these is available, or if the reader name is unrecognised, we use the journal reader (for predictability).
defaultJournalPath :: IO String #
Get the default journal file path specified by the environment.
Like ledger, we look first for the LEDGER_FILE environment
variable, and if that does not exist, for the legacy LEDGER
environment variable. If neither is set, or the value is blank,
return the hard-coded default, which is .hledger.journal in the
users's home directory (or in the current directory, if we cannot
determine a home directory).
defaultJournal :: IO Journal #
Read the default journal file specified by the environment, or raise an error.
type PrefixedFilePath = FilePath #
A file path optionally prefixed by a reader name and colon (journal:, csv:, timedot:, etc.).
tmpostingrulep :: forall (m :: Type -> Type). Maybe Year -> JournalParser m TMPostingRule #
splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath) #
If a filepath is prefixed by one of the reader names and a colon, split that off. Eg "csv:-" -> (Just "csv", "-").
findReader :: forall (m :: Type -> Type). MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m) #
findReader mformat mpath
Find the reader named by mformat, if provided.
Or, if a file path is provided, find the first reader that handles
its file extension, if any.
runJournalParser :: Monad m => JournalParser m a -> Text -> m (Either HledgerParseErrors a) #
Run a journal parser in some monad. See also: parseWithState.
accountaliasp :: forall (m :: Type -> Type). TextParser m AccountAlias #
aliasesFromOpts :: InputOpts -> [AccountAlias] #
Get the account name aliases from options, if any.
bracketeddatetagsp :: forall (m :: Type -> Type). Maybe Year -> TextParser m [(TagName, Day)] #
Parse Ledger-style bracketed posting dates ([DATE=DATE2]), as "date" and/or "date2" tags. Anything that looks like an attempt at this (a square-bracketed sequence of 0123456789/-.= containing at least one digit and one date separator) is also parsed, and will throw an appropriate error.
The dates are parsed in full here so that errors are reported in the right position. A missing year in DATE can be inferred if a default date is provided. A missing year in DATE2 will be inferred from DATE.
>>>either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"Right [("date",2016-01-02),("date2",2016-03-04)]
>>>either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"Left ...not a bracketed date...
>>>either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"Left ...1:2:...This date is invalid...
>>>either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]"Left ...1:2:...The partial date 1/31 can not be parsed...
>>>either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"Left ...1:13:...expecting month or day...
postingcommentp :: forall (m :: Type -> Type). Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day) #
Parse a posting comment and extract its tags and dates.
Postings may be followed by comments, which begin with semicolons and extend to the end of the line. Posting comments may span multiple lines, but comment lines below the posting must be preceded by leading whitespace.
200011 account1 $1 ; a posting comment starting on the same line ... ; extending to the next line
account2 ; a posting comment beginning on the next line
Tags are name-value pairs.
>>>let getTags (_,tags,_,_) = tags>>>let parseTags = fmap getTags . rtp (postingcommentp Nothing)
>>>parseTags "; name1: val1, name2:all this is value2"Right [("name1","val1"),("name2","all this is value2")]
A tag's name must be immediately followed by a colon, without separating whitespace. The corresponding value consists of all the text following the colon up until the next colon or newline, stripped of leading and trailing whitespace.
Posting dates may be expressed with "date"/"date2" tags or with bracketed date syntax. Posting dates will inherit their year from the transaction date if the year is not specified. We throw parse errors on invalid dates.
>>>let getDates (_,_,d1,d2) = (d1, d2)>>>let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))
>>>parseDates "; date: 1/2, date2: 1999/12/31"Right (Just 2000-01-02,Just 1999-12-31)>>>parseDates "; [1/2=1999/12/31]"Right (Just 2000-01-02,Just 1999-12-31)
Example: tags, date tags, and bracketed dates >>> rtp (postingcommentp (Just 2000)) "; a:b, date:34, [=56]" Right ("a:b, date:34, [=56]n",[("a","b"),("date","3/4")],Just 2000-03-04,Just 2000-05-06)
Example: extraction of dates from date tags ignores trailing text >>> rtp (postingcommentp (Just 2000)) "; date:34=56" Right ("date:34=56n",[("date","34=56")],Just 2000-03-04,Nothing)
commenttagsp :: forall (m :: Type -> Type). TextParser m [Tag] #
transactioncommentp :: forall (m :: Type -> Type). TextParser m (Text, [Tag]) #
Parse a transaction comment and extract its tags.
The first line of a transaction may be followed by comments, which begin with semicolons and extend to the end of the line. Transaction comments may span multiple lines, but comment lines below the transaction must be preceded by leading whitespace.
200011 ; a transaction comment starting on the same line ... ; extending to the next line account1 $1 account2
Tags are name-value pairs.
>>>let getTags (_,tags) = tags>>>let parseTags = fmap getTags . rtp transactioncommentp
>>>parseTags "; name1: val1, name2:all this is value2"Right [("name1","val1"),("name2","all this is value2")]
A tag's name must be immediately followed by a colon, without separating whitespace. The corresponding value consists of all the text following the colon up until the next colon or newline, stripped of leading and trailing whitespace.
followingcommentp :: forall (m :: Type -> Type). TextParser m Text #
Parse the text of a (possibly multiline) comment following a journal item.
>>>rtp followingcommentp "" -- no commentRight "">>>rtp followingcommentp ";" -- just a (empty) same-line comment. newline is addedRight "\n">>>rtp followingcommentp "; \n"Right "\n">>>rtp followingcommentp ";\n ;\n" -- a same-line and a next-line commentRight "\n\n">>>rtp followingcommentp "\n ;\n" -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.Right "\n\n"
isSameLineCommentStart :: Char -> Bool #
Is this a character that, appearing anywhere within a line, starts a comment ?
isLineCommentStart :: Char -> Bool #
Is this a character that, as the first non-whitespace on a line, starts a comment line ?
emptyorcommentlinep :: forall (m :: Type -> Type). TextParser m () #
A blank or comment line in journal format: a line that's empty or containing only whitespace or whose first non-whitespace character is semicolon, hash, or star.
multilinecommentp :: forall (m :: Type -> Type). TextParser m () #
rawnumberp :: forall (m :: Type -> Type). TextParser m (Either AmbiguousNumber RawNumber) #
Parse and interpret the structure of a number without external hints. Numbers are digit strings, possibly separated into digit groups by one of two types of separators. (1) Numbers may optionally have a decimal mark, which may be either a period or comma. (2) Numbers may optionally contain digit group marks, which must all be either a period, a comma, or a space.
It is our task to deduce the characters used as decimal mark and digit group mark, based on the allowed syntax. For instance, we make use of the fact that a decimal mark can occur at most once and must be to the right of all digit group marks.
>>>parseTest rawnumberp "1,234,567.89"Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))>>>parseTest rawnumberp "1,000"Left (AmbiguousNumber "1" ',' "000")>>>parseTest rawnumberp "1 000"Right (WithSeparators ' ' ["1","000"] Nothing)
fromRawNumber :: RawNumber -> Maybe Integer -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) #
Interpret a raw number as a decimal number.
Returns: - the decimal number - the precision (number of digits after the decimal point) - the decimal point character, if any - the digit group style, if any (digit group character and sizes of digit groups)
numberp :: forall (m :: Type -> Type). Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) #
Parse a string representation of a number for its value and display attributes.
Some international number formats are accepted, eg either period or comma may be used for the decimal mark, and the other of these may be used for separating digit groups in the integer part. See http://en.wikipedia.org/wiki/Decimal_separator for more examples.
This returns: the parsed numeric value, the precision (number of digits seen following the decimal mark), the decimal mark character used if any, and the digit group style if any.
lotcostp :: forall (m :: Type -> Type). JournalParser m () #
balanceassertionp :: forall (m :: Type -> Type). JournalParser m BalanceAssertion #
costp :: forall (m :: Type -> Type). Amount -> JournalParser m AmountPrice #
Ledger-style cost notation:
UNITAMT, TOTALAMT, () UNITAMT, or (@@) TOTALAMT. The () are ignored.
commoditysymbolp :: forall (m :: Type -> Type). TextParser m CommoditySymbol #
parsemixedamount' :: String -> MixedAmount #
Like parseamount', but returns a MixedAmount.
parsemixedamount :: String -> Either HledgerParseErrors MixedAmount #
Like parseamount', but returns a MixedAmount.
parseamount' :: String -> Amount #
Parse a single-commodity amount from a string, or get an error.
parseamount :: String -> Either HledgerParseErrors Amount #
Try to parse a single-commodity amount from a string
amountp :: forall (m :: Type -> Type). JournalParser m Amount #
Parse a single-commodity amount, applying the default commodity if there is no commodity symbol; optionally followed by, in any order: a Ledger-style cost, Ledger-style valuation expression, and/or Ledger-style cost basis, which is one or more of lot cost, lot date, and/or lot note (we loosely call this triple the lot's cost basis). The cost basis makes it a lot rather than just an amount. Both cost basis info and valuation expression are discarded for now. The main amount's sign is significant; here are the possibilities and their interpretation. Also imagine an optional VALUATIONEXPR added to any of these (omitted for clarity): @
AMT -- acquiring an amount AMT COST -- acquiring an amount at some cost AMT COST COSTBASIS -- acquiring a lot at some cost, saving its cost basis AMT COSTBASIS COST -- like the above AMT COSTBASIS -- like the above with cost same as the cost basis
- AMT -- releasing an amount
- AMT SELLPRICE -- releasing an amount at some selling price
- AMT SELLPRICE COSTBASISSEL -- releasing a lot at some selling price, selecting it by its cost basis
- AMT COSTBASISSEL SELLPRICE -- like the above
- AMT COSTBASISSEL -- like the above with selling price same as the selected lot's cost basis amount
COST/SELLPRICE can be UNITAMT, TOTALAMT, () UNITAMT, or (@@) TOTALAMT. The () are ignored.
COSTBASIS is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order, with LOTCOST defaulting to COST.
COSTBASISSEL is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order.
{LOTCOST} can be {UNITAMT}, {{TOTALAMT}}, {=UNITAMT}, or {{=TOTALAMT}}. The = is ignored.
VALUATIONEXPR can be ((VALUE AMOUNT)) or ((VALUE FUNCTION)).
@ Ledger amount syntax is really complex. Rule of thumb: curly braces, parentheses, and/or square brackets in an amount means a Ledger-style cost basis is involved.
To parse an amount's numeric quantity we need to know which character represents a decimal mark. We find it in one of three ways:
- If a decimal mark has been set explicitly in the journal parse state, we use that
- Or if the journal has a commodity declaration for the amount's commodity, we get the decimal mark from that
- Otherwise we will parse any valid decimal mark appearing in the number, as long as the number appears well formed. (This means we handle files with any supported decimal mark without configuration, but it also allows different decimal marks in different amounts, which is a bit too loose. There's an open issue.)
spaceandamountormissingp :: forall (m :: Type -> Type). JournalParser m MixedAmount #
Parse whitespace then an amount, or return the special "missing" marker amount.
singlespacep :: forall (m :: Type -> Type). TextParser m () #
Parse one non-newline whitespace character that is not followed by another one.
singlespacedtextsatisfying1p :: forall (m :: Type -> Type). (Char -> Bool) -> TextParser m Text #
Parse non-empty, single-spaced text starting and ending with non-whitespace, where all characters satisfy the given predicate.
singlespacednoncommenttext1p :: forall (m :: Type -> Type). TextParser m Text #
Parse non-empty, single-spaced text starting and ending with non-whitespace, until a comment start (semicolon), double space, or newline.
singlespacedtext1p :: forall (m :: Type -> Type). TextParser m Text #
Parse non-empty, single-spaced text starting and ending with non-whitespace, until a double space or newline.
noncommenttext1p :: forall (m :: Type -> Type). TextParser m Text #
Parse non-empty text, including whitespace, until a comment start (semicolon) or newline.
noncommenttextp :: forall (m :: Type -> Type). TextParser m Text #
Parse possibly empty text, including whitespace, until a comment start (semicolon) or newline.
doublequotedtextp :: forall (m :: Type -> Type). TextParser m Text #
Parse a single line of possibly empty text enclosed in double quotes.
accountnamep :: forall (m :: Type -> Type). TextParser m AccountName #
Parse an account name, plus one following space if present. Account names have one or more parts separated by the account separator character, and are terminated by two or more spaces (or end of input). Each part is at least one character long, may have single spaces inside it, and starts with a non-whitespace. Note, this means "{account}", "%^!" and ";comment" are all accepted (parent parsers usually prevent/consume the last). It should have required parts to start with an alphanumeric; for now it remains as-is for backwards compatibility.
modifiedaccountnamep :: forall (m :: Type -> Type). JournalParser m AccountName #
Parse an account name (plus one following space if present), then apply any parent account prefix and/or account aliases currently in effect, in that order. (Ie first add the parent account prefix, then rewrite with aliases). This calls error if any account alias with an invalid regular expression exists.
secondarydatep :: forall (m :: Type -> Type). Day -> TextParser m Day #
datetimep :: forall (m :: Type -> Type). JournalParser m LocalTime #
Parse a date and time in YYYY-MM-DD HH:MM[:SS][+-ZZZZ] format. Slash (/) and period (.) are also allowed as date separators. The year may be omitted if a default year has been set. Seconds are optional. The timezone is optional and ignored (the time is always interpreted as a local time). Leading zeroes may be omitted (except in a timezone).
datep :: forall (m :: Type -> Type). JournalParser m Day #
Parse a date in YYYY-MM-DD format. Slash (/) and period (.) are also allowed as separators. The year may be omitted if a default year has been set. Leading zeroes may be omitted.
descriptionp :: forall (m :: Type -> Type). TextParser m Text #
Parse possibly empty text until a semicolon or newline. Whitespace is preserved (for now - perhaps helps preserve alignment of same-line comments ?).
clearAccountAliases :: MonadState Journal m => m () #
getAccountAliases :: MonadState Journal m => m [AccountAlias] #
addAccountAlias :: MonadState Journal m => AccountAlias -> m () #
getParentAccount :: forall (m :: Type -> Type). JournalParser m AccountName #
popParentAccount :: forall (m :: Type -> Type). JournalParser m () #
pushParentAccount :: forall (m :: Type -> Type). AccountName -> JournalParser m () #
addDeclaredAccountType :: forall (m :: Type -> Type). AccountName -> AccountType -> JournalParser m () #
addDeclaredAccountTags :: forall (m :: Type -> Type). AccountName -> [Tag] -> JournalParser m () #
getAmountStyle :: forall (m :: Type -> Type). CommoditySymbol -> JournalParser m (Maybe AmountStyle) #
Get the AmountStyle declared by the most recently parsed (in the current or parent files,
prior to the current position) commodity directive for the given commodity, if any.
getDefaultAmountStyle :: forall (m :: Type -> Type). JournalParser m (Maybe AmountStyle) #
Get amount style associated with default currency.
Returns AmountStyle used to defined by a latest default commodity directive
prior to current position within this file or its parents.
getDefaultCommodityAndStyle :: forall (m :: Type -> Type). JournalParser m (Maybe (CommoditySymbol, AmountStyle)) #
setDefaultCommodityAndStyle :: forall (m :: Type -> Type). (CommoditySymbol, AmountStyle) -> JournalParser m () #
journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal #
Generate periodic transactions from all periodic transaction rules in the journal. These transactions are added to the in-memory Journal (but not the on-disk file).
The start & end date for generated periodic transactions are determined in a somewhat complicated way; see the hledger manual -> Periodic transactions.
journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal #
Apply any auto posting rules to generate extra postings on this journal's transactions. With a true first argument, adds visible tags to generated postings and modified transactions.
journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal #
Post-process a Journal that has just been parsed or generated, in this order:
- add misc info (file path, read time)
- reverse transactions into their original parse order
- apply canonical commodity styles
- add tags from account directives to postings' tags
- add forecast transactions if enabled
- add tags from account directives to postings' tags (again to affect forecast transactions)
- add auto postings if enabled
- add tags from account directives to postings' tags (again to affect auto postings)
- evaluate balance assignments and balance each transaction
- check balance assertions if enabled
- infer equity postings in conversion transactions if enabled
- infer market prices from costs if enabled
- check all accounts have been declared if in strict mode
- check all commodities have been declared if in strict mode
initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal #
Given a parser to ParsedJournal, input options, file path and
content: run the parser on the content. This is all steps of
parseAndFinaliseJournal without the finalisation step, and is used when
you need to perform other actions before finalisation, as in parsing
Timeclock and Timedot files.
parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts -> FilePath -> Text -> ExceptT String IO Journal #
Given a parser to ParsedJournal, input options, file path and content: run the parser on the content, and finalise the result to get a Journal; or throw an error.
rawOptsToInputOpts :: Day -> RawOpts -> InputOpts #
Parse an InputOpts from a RawOpts and a provided date. This will fail with a usage error if the forecast period expression cannot be parsed.
data Reader (m :: Type -> Type) #
A hledger journal reader is a triple of storage format name, a detector of that format, and a parser from that format to Journal. The type variable m appears here so that rParserr can hold a journal parser, which depends on it.
Constructors
| Reader | |
Fields
| |
accountTransactionsReportByCommodity :: AccountTransactionsReport -> [(CommoditySymbol, AccountTransactionsReport)] #
Split an account transactions report whose items may involve several commodities, into one or more single-commodity account transactions reports.
transactionRegisterDate :: WhichDate -> Query -> Query -> Transaction -> Day #
What date should be shown for a transaction in an account register report ? This will be in context of a particular account (the "this account" query) and any additional report query. It could be:
- if postings are matched by both thisacctq and reportq, the earliest of those matched postings' dates (or their secondary dates if --date2 was used)
- the transaction date, or its secondary date if --date2 was used.
accountTransactionsReportItems :: Query -> Query -> MixedAmount -> (MixedAmount -> MixedAmount) -> (AccountName -> Maybe AccountType) -> [(Day, Transaction)] -> [AccountTransactionsReportItem] #
Generate transactions report items from a list of transactions, using the provided user-specified report query, a query specifying which account to use as the focus, a starting balance, and a sign-setting function. Each transaction is accompanied by the date that should be shown for it in the report. This is not necessarily the transaction date - see transactionRegisterDate.
triCommodityBalance :: CommoditySymbol -> (a, b, c, d, e, MixedAmount) -> MixedAmount #
triCommodityAmount :: CommoditySymbol -> (a, b, c, d, MixedAmount, f) -> MixedAmount #
triBalance :: (a, b, c, d, e, f) -> f #
triDate :: (a, Transaction, c, d, e, f) -> Day #
triOrigTransaction :: (a, b, c, d, e, f) -> a #
type AccountTransactionsReport = [AccountTransactionsReportItem] #
An account transactions report represents transactions affecting a particular account (or possibly several accounts, but we don't use that). It is used eg by hledger-ui's and hledger-web's register view, and hledger's aregister report, where we want to show one row per transaction, in the context of the current account. Report items consist of:
- the transaction, unmodified
- the transaction as seen in the context of the current account and query, which means:
- the transaction date is set to the "transaction context date": the earliest of the transaction date and any other posting dates of postings to the current account (matched by the report query).
- the transaction's postings are filtered, excluding any which are not matched by the report query
- a text description of the other account(s) posted to/from
- a flag indicating whether there's more than one other account involved
- the total increase/decrease to the current account
- the report transactions' running total after this transaction; or if historical balance is requested (-H), the historical running total. The historical running total includes transactions from before the report start date if one is specified, filtered by the report query. The historical running total may or may not be the account's historical running balance, depending on the report query.
Items are sorted by transaction register date (the earliest date the transaction posts to the current account), most recent first. Reporting intervals are currently ignored.
type AccountTransactionsReportItem = (Transaction, Transaction, Bool, Text, MixedAmount, MixedAmount) #
balanceReport :: ReportSpec -> Journal -> BalanceReport #
Enabling this makes balance --flat --empty also show parent accounts without postings, in addition to those with postings and a zero balance. Disabling it shows only the latter. No longer supported, but leave this here for a bit. flatShowsPostinglessAccounts = True
Generate a simple balance report, containing the matched accounts and their balances (change of balance) during the specified period. If the normalbalance_ option is set, it adjusts the sorting and sign of amounts (see ReportOpts and CompoundBalanceCommand).
flatShowsExclusiveBalance :: Bool #
When true (the default), this makes balance --flat reports and their implementation clearer. Single/multi-col balance reports currently aren't all correct if this is false.
type BalanceReport = ([BalanceReportItem], MixedAmount) #
A simple balance report. It has:
- a list of items, one per account, each containing:
- the full account name
- the Ledger-style elided short account name (the leaf account name, prefixed by any boring parents immediately above); or with --flat, the full account name again
- the number of indentation steps for rendering a Ledger-style account tree, taking into account elided boring parents, --no-elide and --flat
- an amount
- the total of all amounts
type BalanceReportItem = (AccountName, AccountName, Int, MixedAmount) #
budgetReportAsCsv :: ReportOpts -> BudgetReport -> [[Text]] #
Render a budget report as CSV. Like multiBalanceReportAsCsv, but includes alternating actual and budget amount columns.
budgetReportAsTable :: ReportOpts -> BudgetReport -> Table Text Text WideBuilder #
Build a Table from a multi-column balance report.
budgetReportAsText :: ReportOpts -> BudgetReport -> Text #
Render a budget report as plain text suitable for console output.
combineBudgetAndActual :: ReportOpts -> Journal -> MultiBalanceReport -> MultiBalanceReport -> BudgetReport #
Combine a per-account-and-subperiod report of budget goals, and one of actual change amounts, into a budget performance report. The two reports should have the same report interval, but need not have exactly the same account rows or date columns. (Cells in the combined budget report can be missing a budget goal, an actual amount, or both.) The combined report will include:
- consecutive subperiods at the same interval as the two reports, spanning the period of both reports
- all accounts mentioned in either report, sorted by account code or account name or amount as appropriate.
budgetReport :: ReportSpec -> BalancingOpts -> DateSpan -> Journal -> BudgetReport #
Calculate per-account, per-period budget (balance change) goals
from all periodic transactions, calculate actual balance changes
from the regular transactions, and compare these to get a BudgetReport.
Unbudgeted accounts may be hidden or renamed (see journalWithBudgetAccountNames).
type BudgetGoal = Change #
type BudgetTotal = Total #
type BudgetAverage = Average #
type BudgetCell = (Maybe Change, Maybe BudgetGoal) #
A budget report tracks expected and actual changes per account and subperiod.
entriesReport :: ReportSpec -> Journal -> EntriesReport #
Select transactions for an entries report.
type EntriesReport = [EntriesReportItem] #
A journal entries report is a list of whole transactions as originally entered in the journal (mostly). This is used by eg hledger's print command and hledger-web's journal entries view.
type EntriesReportItem = Transaction #
balanceReportTableAsText :: ReportOpts -> Table Text Text WideBuilder -> Builder #
Given a table representing a multi-column balance report (for example,
made using balanceReportAsTable), render it in a format suitable for
console output. Amounts with more than two commodities will be elided
unless --no-elide is used.
sortRowsLike :: [AccountName] -> [PeriodicReportRow DisplayName b] -> [PeriodicReportRow DisplayName b] #
A sorting helper: sort a list of things (eg report rows) keyed by account name to match the provided ordering of those same account names.
sortRows :: ReportOpts -> Journal -> [MultiBalanceReportRow] -> [MultiBalanceReportRow] #
Sort the rows by amount or by account declaration order.
generateMultiBalanceReport :: ReportSpec -> Journal -> PriceOracle -> Set AccountName -> [(DateSpan, [Posting])] -> HashMap AccountName Account -> MultiBalanceReport #
Lay out a set of postings grouped by date span into a regular matrix with rows given by AccountName and columns by DateSpan, then generate a MultiBalanceReport from the columns.
getPostings :: ReportSpec -> Journal -> PriceOracle -> [Posting] #
Gather postings matching the query within the report period.
getPostingsByColumn :: ReportSpec -> Journal -> PriceOracle -> [DateSpan] -> [(DateSpan, [Posting])] #
Group postings, grouped by their column
makeReportQuery :: ReportSpec -> DateSpan -> ReportSpec #
Remove any date queries and insert queries from the report span. The user's query expanded to the report span if there is one (otherwise any date queries are left as-is, which handles the hledger-ui+future txns case above).
startingPostings :: ReportSpec -> Journal -> PriceOracle -> DateSpan -> [Posting] #
Postings needed to calculate starting balances.
Balances at report start date, from all earlier postings which otherwise match the query. These balances are unvalued. TODO: Do we want to check whether to bother calculating these? isHistorical and startDate is not nothing, otherwise mempty? This currently gives a failure with some totals which are supposed to be 0 being blank.
compoundBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount #
A helper for compoundBalanceReport, similar to multiBalanceReportWith.
compoundBalanceReport :: ReportSpec -> Journal -> [CBCSubreportSpec a] -> CompoundPeriodicReport a MixedAmount #
Generate a compound balance report from a list of CBCSubreportSpec. This shares postings between the subreports.
multiBalanceReportWith :: ReportSpec -> Journal -> PriceOracle -> Set AccountName -> MultiBalanceReport #
A helper for multiBalanceReport. This one takes some extra arguments,
a PriceOracle to be used for looking up market prices, and a set of
AccountNames which should not be elided. Commands which run multiple
reports (bs etc.) can generate the price oracle just once for efficiency,
passing it to each report by calling this function directly.
multiBalanceReport :: ReportSpec -> Journal -> MultiBalanceReport #
Generate a multicolumn balance report for the matched accounts, showing the change of balance, accumulated balance, or historical balance in each of the specified periods. If the normalbalance_ option is set, it adjusts the sorting and sign of amounts (see ReportOpts and CompoundBalanceCommand). hledger's most powerful and useful report, used by the balance command (in multiperiod mode) and (via compoundBalanceReport) by the bscfis commands.
type MultiBalanceReport = PeriodicReport DisplayName MixedAmount #
A multi balance report is a kind of periodic report, where the amounts correspond to balance changes or ending balances in a given period. It has:
- a list of each column's period (date span)
- a list of rows, each containing:
- the full account name, display name, and display depth
- A list of amounts, one for each column.
- the total of the row's amounts for a periodic report
- the average of the row's amounts
- the column totals, and the overall grand total (or zero for cumulative/historical reports) and grand average.
mkpostingsReportItem :: Bool -> Bool -> WhichDate -> Maybe Period -> Posting -> MixedAmount -> PostingsReportItem #
Generate one postings report line item, containing the posting, the current running balance, and optionally the posting date and/or the transaction description.
postingsReport :: ReportSpec -> Journal -> PostingsReport #
Select postings from the journal and add running balance and other information to make a postings report. Used by eg hledger's register command.
type PostingsReport = [PostingsReportItem] #
A postings report is a list of postings with a running total, and a little extra transaction info to help with rendering. This is used eg for the register command.
type PostingsReportItem = (Maybe Day, Maybe Period, Maybe Text, Posting, MixedAmount) #
prrDepth :: PeriodicReportRow DisplayName a -> Int #
Get the display depth of a PeriodicReportRow tagged by a DisplayName.
prrDisplayName :: PeriodicReportRow DisplayName a -> AccountName #
Get the display name of a PeriodicReportRow tagged by a DisplayName.
prrFullName :: PeriodicReportRow DisplayName a -> AccountName #
Get the full, canonical, name of a PeriodicReportRow tagged by a DisplayName.
treeDisplayName :: AccountName -> DisplayName #
Construct a tree display name, where only the leaf is displayed at its given depth
flatDisplayName :: AccountName -> DisplayName #
Construct a flat display name, where the full name is also displayed at depth 1
prMapMaybeName :: (a -> Maybe b) -> PeriodicReport a c -> PeriodicReport b c #
Map a function over the row names, possibly discarding some.
prMapName :: (a -> b) -> PeriodicReport a c -> PeriodicReport b c #
Map a function over the row names.
periodicReportSpan :: PeriodicReport a b -> DateSpan #
Figure out the overall date span of a PeriodicReport
prrAdd :: Semigroup b => PeriodicReportRow a b -> PeriodicReportRow a b -> PeriodicReportRow a b #
Add two PeriodicReportRows, preserving the name of the first.
type Percentage = Decimal #
Arguments
| = MixedAmount | A change in balance during a certain period. |
Arguments
| = MixedAmount | An ending balance as of some date. |
Arguments
| = MixedAmount | The sum of |
Arguments
| = MixedAmount | The average of |
data PeriodicReport a b #
A periodic report is a generic tabular report, where each row corresponds to some label (usually an account name) and each column to a date period. The column periods are usually consecutive subperiods formed by splitting the overall report period by some report interval (daily, weekly, etc.). It has:
- a list of each column's period (date span)
- a list of rows, each containing:
- an account label
- the account's depth
- A list of amounts, one for each column. Depending on the value type,
these can represent balance changes, ending balances, budget
performance, etc. (for example, see
BalanceAccumulationand Hledger.Cli.Commands.Balance). - the total of the row's amounts for a periodic report, or zero for cumulative/historical reports (since summing end balances generally doesn't make sense).
- the average of the row's amounts
- the column totals, and the overall grand total (or zero for cumulative/historical reports) and grand average.
Constructors
| PeriodicReport | |
Fields
| |
Instances
data PeriodicReportRow a b #
Constructors
| PeriodicReportRow | |
Fields
| |
Instances
data CompoundPeriodicReport a b #
A compound balance report has:
- an overall title
- the period (date span) of each column
- one or more named, normal-positive multi balance reports, with columns corresponding to the above, and a flag indicating whether they increased or decreased the overall totals
- a list of overall totals for each column, and their grand total and average
It is used in compound balance report commands like balancesheet, cashflow and incomestatement.
Constructors
| CompoundPeriodicReport | |
Fields
| |
Instances
data CBCSubreportSpec a #
Description of one subreport within a compound balance report. Part of a CompoundBalanceCommandSpec, but also used in hledger-lib.
Constructors
| CBCSubreportSpec | |
Fields
| |
data DisplayName #
A full name, display name, and depth for an account.
Constructors
| DisplayName | |
Fields | |
Instances
| ToJSON DisplayName | |
Defined in Hledger.Reports.ReportTypes Methods toJSON :: DisplayName -> Value # toEncoding :: DisplayName -> Encoding # toJSONList :: [DisplayName] -> Value # toEncodingList :: [DisplayName] -> Encoding # omitField :: DisplayName -> Bool # | |
| Show DisplayName | |
Defined in Hledger.Reports.ReportTypes Methods showsPrec :: Int -> DisplayName -> ShowS # show :: DisplayName -> String # showList :: [DisplayName] -> ShowS # | |
| Eq DisplayName | |
Defined in Hledger.Reports.ReportTypes | |
| Ord DisplayName | |
Defined in Hledger.Reports.ReportTypes Methods compare :: DisplayName -> DisplayName -> Ordering # (<) :: DisplayName -> DisplayName -> Bool # (<=) :: DisplayName -> DisplayName -> Bool # (>) :: DisplayName -> DisplayName -> Bool # (>=) :: DisplayName -> DisplayName -> Bool # max :: DisplayName -> DisplayName -> DisplayName # min :: DisplayName -> DisplayName -> DisplayName # | |
rawOptsToReportSpec :: Day -> RawOpts -> Either String ReportSpec #
Generate a ReportSpec from RawOpts and a provided day, or return an error string if there are regular expression errors.
updateReportSpecWith :: (ReportOpts -> ReportOpts) -> ReportSpec -> Either String ReportSpec #
Like updateReportSpec, but takes a ReportOpts-modifying function.
updateReportSpec :: ReportOpts -> ReportSpec -> Either String ReportSpec #
Update the ReportOpts and the fields derived from it in a ReportSpec, or return an error message if there is a problem such as missing or unparseable options data. This is the safe way to change a ReportSpec, ensuring that all fields (_rsQuery, _rsReportOpts, querystring_, etc.) are in sync.
reportOptsToSpec :: Day -> ReportOpts -> Either String ReportSpec #
Generate a ReportSpec from a set of ReportOpts on a given day.
class HasReportSpec c where #
Minimal complete definition
Methods
reportSpec :: Lens' c ReportSpec #
rsQueryOpts :: Lens' c [QueryOpt] #
rsReportOpts :: Lens' c ReportOpts #
Instances
| HasReportSpec CliOpts Source # | |
Defined in Hledger.Cli.CliOptions Methods reportSpec :: Lens' CliOpts ReportSpec # rsQuery :: Lens' CliOpts Query # rsQueryOpts :: Lens' CliOpts [QueryOpt] # | |
| HasReportSpec ReportSpec | |
Defined in Hledger.Reports.ReportOptions Methods reportSpec :: Lens' ReportSpec ReportSpec # rsDay :: Lens' ReportSpec Day # rsQuery :: Lens' ReportSpec Query # rsQueryOpts :: Lens' ReportSpec [QueryOpt] # | |
class HasReportOptsNoUpdate a => HasReportOpts a where #
Special lenses for ReportOpts which also update the Query and QueryOpts in ReportSpec. Note that these are not true lenses, as they have a further restriction on the functor. This will work as a normal lens for all common uses, but since they don't obey the lens laws for some fancy cases, they may fail in some exotic circumstances.
Note that setEither/overEither should only be necessary with querystring and reportOpts: the other lenses should never fail.
Examples:
>>>import Lens.Micro (set)>>>_rsQuery <$> setEither querystring ["assets"] defreportspecRight (Acct (RegexpCI "assets"))>>>_rsQuery <$> setEither querystring ["(assets"] defreportspecLeft "This regular expression is malformed, please correct it:\n(assets">>>_rsQuery $ set querystring ["assets"] defreportspecAcct (RegexpCI "assets")>>>_rsQuery $ set querystring ["(assets"] defreportspec*** Exception: Error: Updating ReportSpec failed: try using overEither instead of over or setEither instead of set>>>_rsQuery $ set period (MonthPeriod 2021 08) defreportspecDate DateSpan 2021-08
Minimal complete definition
Nothing
Methods
reportOpts :: ReportableLens' a ReportOpts #
period :: ReportableLens' a Period #
statuses :: ReportableLens' a [Status] #
depth :: ReportableLens' a (Maybe Int) #
date2 :: ReportableLens' a Bool #
real :: ReportableLens' a Bool #
querystring :: ReportableLens' a [Text] #
Instances
class HasReportOptsNoUpdate c where #
Lenses for ReportOpts.
Minimal complete definition
Methods
reportOptsNoUpdate :: Lens' c ReportOpts #
accountlistmode :: Lens' c AccountListMode #
balanceaccum :: Lens' c BalanceAccumulation #
balancecalc :: Lens' c BalanceCalculation #
budgetpat :: Lens' c (Maybe Text) #
conversionop :: Lens' c (Maybe ConversionOp) #
date2NoUpdate :: Lens' c Bool #
depthNoUpdate :: Lens' c (Maybe Int) #
format :: Lens' c StringFormat #
infer_prices :: Lens' c Bool #
interval :: Lens' c Interval #
normalbalance :: Lens' c (Maybe NormalSign) #
periodNoUpdate :: Lens' c Period #
querystringNoUpdate :: Lens' c [Text] #
realNoUpdate :: Lens' c Bool #
show_costs :: Lens' c Bool #
sort_amount :: Lens' c Bool #
statusesNoUpdate :: Lens' c [Status] #
summary_only :: Lens' c Bool #
transpose__ :: Lens' c Bool #
value :: Lens' c (Maybe ValuationType) #
Instances
setEither :: ((a -> Either e b) -> s -> Either e t) -> b -> s -> Either e t #
Set a field using a lens, but report on failure.
overEither :: ((a -> Either e b) -> s -> Either e t) -> (a -> b) -> s -> Either e t #
Apply a function over a lens, but report on failure.
reportPeriodName :: BalanceAccumulation -> [DateSpan] -> DateSpan -> Text #
Make a name for the given period in a multiperiod report, given the type of balance being reported and the full set of report periods. This will be used as a column heading (or row heading, in a register summary report). We try to pick a useful name as follows:
- ending-balance reports: the period's end date
- balance change reports where the periods are months and all in the same year: the short month name in the current locale
- all other balance change reports: a description of the datespan, abbreviated to compact form if possible (see showDateSpan).
reportPeriodOrJournalLastDay :: ReportSpec -> Journal -> Maybe Day #
reportPeriodLastDay :: ReportSpec -> Maybe Day #
reportPeriodOrJournalStart :: ReportSpec -> Journal -> Maybe Day #
reportPeriodStart :: ReportSpec -> Maybe Day #
reportEndDate :: Journal -> ReportSpec -> Maybe Day #
reportStartDate :: Journal -> ReportSpec -> Maybe Day #
reportSpanBothDates :: Journal -> ReportSpec -> (DateSpan, [DateSpan]) #
Like reportSpan, but uses both primary and secondary dates when calculating the span.
reportSpan :: Journal -> ReportSpec -> (DateSpan, [DateSpan]) #
The effective report span is the start and end dates specified by options or queries, or otherwise the earliest and latest transaction or posting dates in the journal. If no dates are specified by options/queries and the journal is empty, returns the null date span. Also return the intervals if they are requested.
queryFromFlags :: ReportOpts -> Query #
Convert report options to a query, ignoring any non-flag command line arguments.
valuationAfterSum :: ReportOpts -> Maybe (Maybe CommoditySymbol) #
If the ReportOpts specify that we are performing valuation after summing amounts, return Just of the commodity symbol we're converting to, Just Nothing for the default, and otherwise return Nothing. Used for example with historical reports with --value=end.
mixedAmountApplyValuationAfterSumFromOptsWith :: ReportOpts -> Journal -> PriceOracle -> DateSpan -> MixedAmount -> MixedAmount #
Select the Account valuation functions required for performing valuation after summing amounts. Used in MultiBalanceReport to value historical and similar reports.
journalApplyValuationFromOptsWith :: ReportSpec -> Journal -> PriceOracle -> Journal #
Like journalApplyValuationFromOpts, but takes PriceOracle as an argument.
journalApplyValuationFromOpts :: ReportSpec -> Journal -> Journal #
Convert this journal's postings' amounts to cost and/or to value, if specified by options (-B--cost-V-X--value etc.). Strip prices if not needed. This should be the main stop for performing costing and valuation. The exception is whenever you need to perform valuation _after_ summing up amounts, as in a historical balance report with --value=end. valuationAfterSum will check for this condition.
journalValueAndFilterPostingsWith :: ReportSpec -> Journal -> PriceOracle -> Journal #
Like journalValueAndFilterPostings, but takes a PriceOracle as an argument.
journalValueAndFilterPostings :: ReportSpec -> Journal -> Journal #
Convert a Journal's amounts to cost and/or to value (see
journalApplyValuationFromOpts), and filter by the ReportSpec Query.
We make sure to first filter by amt: and cur: terms, then value the
Journal, then filter by the remaining terms.
flat_ :: ReportOpts -> Bool #
tree_ :: ReportOpts -> Bool #
Legacy-compatible convenience aliases for accountlistmode_.
whichDate :: ReportOpts -> WhichDate #
Report which date we will report on based on --date2.
postingDateFn :: ReportOpts -> Posting -> Day #
Select the Posting date accessor based on --date2.
transactionDateFn :: ReportOpts -> Transaction -> Day #
Select the Transaction date accessor based on --date2.
reportOptsToggleStatus :: Status -> ReportOpts -> ReportOpts #
Add/remove this status from the status list. Used by hledger-ui.
simplifyStatuses :: Ord a => [a] -> [a] #
Reduce a list of statuses to just one of each status, and if all statuses are present return the empty list.
intervalFromRawOpts :: RawOpts -> Interval #
Get the report interval, if any, specified by the last of -p/--period, -D--daily, -W--weekly, -M/--monthly etc. options. An interval from --period counts only if it is explicitly defined.
setDefaultConversionOp :: ConversionOp -> ReportSpec -> ReportSpec #
Set the default ConversionOp.
rawOptsToReportOpts :: Day -> RawOpts -> ReportOpts #
Generate a ReportOpts from raw command-line input, given a day. This will fail with a usage error if it is passed - an invalid --format argument, - an invalid --value argument, - if --valuechange is called with a valuation type other than -V/--value=end. - an invalid --pretty argument,
data BalanceCalculation #
What to calculate for each cell in a balance report. "Balance report types -> Calculation type" in the hledger manual.
Constructors
| CalcChange | Sum of posting amounts in the period. |
| CalcBudget | Sum of posting amounts and the goal for the period. |
| CalcValueChange | Change from previous period's historical end value to this period's historical end value. |
| CalcGain | Change from previous period's gain, i.e. valuation minus cost basis. |
| CalcPostingsCount | Number of postings in the period. |
Instances
| Show BalanceCalculation | |
Defined in Hledger.Reports.ReportOptions Methods showsPrec :: Int -> BalanceCalculation -> ShowS # show :: BalanceCalculation -> String # showList :: [BalanceCalculation] -> ShowS # | |
| Default BalanceCalculation | |
Defined in Hledger.Reports.ReportOptions Methods | |
| Eq BalanceCalculation | |
Defined in Hledger.Reports.ReportOptions Methods (==) :: BalanceCalculation -> BalanceCalculation -> Bool # (/=) :: BalanceCalculation -> BalanceCalculation -> Bool # | |
data BalanceAccumulation #
How to accumulate calculated values across periods (columns) in a balance report. "Balance report types -> Accumulation type" in the hledger manual.
Constructors
| PerPeriod | No accumulation. Eg, shows the change of balance in each period. |
| Cumulative | Accumulate changes across periods, starting from zero at report start. |
| Historical | Accumulate changes across periods, including any from before report start. Eg, shows the historical end balance of each period. |
Instances
| Show BalanceAccumulation | |
Defined in Hledger.Reports.ReportOptions Methods showsPrec :: Int -> BalanceAccumulation -> ShowS # show :: BalanceAccumulation -> String # showList :: [BalanceAccumulation] -> ShowS # | |
| Default BalanceAccumulation | |
Defined in Hledger.Reports.ReportOptions Methods | |
| Eq BalanceAccumulation | |
Defined in Hledger.Reports.ReportOptions Methods (==) :: BalanceAccumulation -> BalanceAccumulation -> Bool # (/=) :: BalanceAccumulation -> BalanceAccumulation -> Bool # | |
data AccountListMode #
Should accounts be displayed: in the command's default style, hierarchically, or as a flat list ?
Instances
| Show AccountListMode | |
Defined in Hledger.Reports.ReportOptions Methods showsPrec :: Int -> AccountListMode -> ShowS # show :: AccountListMode -> String # showList :: [AccountListMode] -> ShowS # | |
| Default AccountListMode | |
Defined in Hledger.Reports.ReportOptions Methods def :: AccountListMode # | |
| Eq AccountListMode | |
Defined in Hledger.Reports.ReportOptions Methods (==) :: AccountListMode -> AccountListMode -> Bool # (/=) :: AccountListMode -> AccountListMode -> Bool # | |
Constructors
| LayoutWide (Maybe Int) | |
| LayoutTall | |
| LayoutBare | |
| LayoutTidy |
data ReportOpts #
Standard options for customising report filtering and output. Most of these correspond to standard hledger command-line options or query arguments, but not all. Some are used only by certain commands, as noted below.
Constructors
| ReportOpts | |
Fields
| |
Instances
data ReportSpec #
A fully-determined set of report parameters (report options with all partial values made total, eg the begin and end dates are known, avoiding date/regex errors; plus the reporting date), and the query successfully calculated from them.
If you change the report options or date in one of these, you should
use reportOptsToSpec to regenerate the whole thing, avoiding inconsistency.
Constructors
| ReportSpec | |
Fields
| |
Instances
tests_Data :: TestTree #
ledgerCommodities :: Ledger -> [CommoditySymbol] #
All commodities used in this ledger.
ledgerDateSpan :: Ledger -> DateSpan #
The (fully specified) date span containing all the ledger's (filtered) transactions, or DateSpan Nothing Nothing if there are none.
ledgerPostings :: Ledger -> [Posting] #
List a ledger's postings, in the order parsed.
ledgerLeafAccounts :: Ledger -> [Account] #
List a ledger's bottom-level (subaccount-less) accounts, in tree order.
ledgerTopAccounts :: Ledger -> [Account] #
List a ledger's top-level accounts (the ones below the root), in tree order.
ledgerRootAccount :: Ledger -> Account #
Get this ledger's root account, which is a dummy "root" account above all others. This should always be first in the account list, if somehow not this returns a null account.
ledgerAccount :: Ledger -> AccountName -> Maybe Account #
Get the named account from a ledger.
ledgerAccountNames :: Ledger -> [AccountName] #
List a ledger's account names.
ledgerFromJournal :: Query -> Journal -> Ledger #
Filter a journal's transactions with the given query, then build a Ledger, containing the journal plus the tree of all its accounts with their subaccount-inclusive and subaccount-exclusive balances. If the query includes a depth limit, the ledger's journal will be depth limited, but the ledger's account tree will not.
nullledger :: Ledger #
showAccountsBoringFlag :: Account -> String #
showAccounts :: Account -> String #
printAccounts :: Account -> IO () #
lookupAccount :: AccountName -> [Account] -> Maybe Account #
Search an account list by name.
sortAccountNamesByDeclaration :: Journal -> Bool -> [AccountName] -> [AccountName] #
Sort account names by the order in which they were declared in the journal, at each level of the account tree (ie within each group of siblings). Undeclared accounts are sorted last and alphabetically. This is hledger's default sort for reports organised by account. The account list is converted to a tree temporarily, adding any missing parents; these can be kept (suitable for a tree-mode report) or removed (suitable for a flat-mode report).
accountSetDeclarationInfo :: Journal -> Account -> Account #
Add extra info for this account derived from the Journal's account directives, if any (comment, tags, declaration order..).
sortAccountTreeByAmount :: NormalSign -> Account -> Account #
Sort each group of siblings in an account tree by inclusive amount, so that the accounts with largest normal balances are listed first. The provided normal balance sign determines whether normal balances are negative or positive, affecting the sort order. Ie, if balances are normally negative, then the most negative balances sort first, and vice versa.
flattenAccounts :: Account -> [Account] #
Flatten an account tree into a list, which is sometimes convenient. Note since accounts link to their parents/subs, the tree's structure remains intact and can still be used. It's a tree/list!
pruneAccounts :: (Account -> Bool) -> Account -> Maybe Account #
Remove all leaf accounts and subtrees matching a predicate.
clipAccountsAndAggregate :: Maybe Int -> [Account] -> [Account] #
Remove subaccounts below the specified depth, aggregating their balance at the depth limit (accounts at the depth limit will have any sub-balances merged into their exclusive balance). If the depth is Nothing, return the original accounts
clipAccounts :: Int -> Account -> Account #
Remove all subaccounts below a certain depth.
sumAccounts :: Account -> Account #
Add subaccount-inclusive balances to an account tree.
anyAccounts :: (Account -> Bool) -> Account -> Bool #
Is the predicate true on any of this account or its subaccounts ?
mapAccounts :: (Account -> Account) -> Account -> Account #
Map a (non-tree-structure-modifying) function over this and sub accounts.
accountsLevels :: Account -> [[Account]] #
List the accounts at each level of the account tree.
parentAccounts :: Account -> [Account] #
Get this account's parent accounts, from the nearest up to the root.
accountTree :: AccountName -> [AccountName] -> Account #
Convert a list of account names to a tree of Account objects, with just the account names filled in. A single root account with the given name is added.
accountsFromPostings :: [Posting] -> [Account] #
Derive 1. an account tree and 2. each account's total exclusive and inclusive changes from a list of postings. This is the core of the balance command (and of *ledger). The accounts are returned as a list in flattened tree order, and also reference each other as a tree. (The first account is the root of the tree.)
class HasInputOpts c where #
Minimal complete definition
Methods
inputOpts :: Lens' c InputOpts #
balancingopts :: Lens' c BalancingOpts #
forecast :: Lens' c (Maybe DateSpan) #
infer_costs :: Lens' c Bool #
infer_equity :: Lens' c Bool #
mformat :: Lens' c (Maybe StorageFormat) #
mrules_file :: Lens' c (Maybe FilePath) #
reportspan :: Lens' c DateSpan #
verbose_tags :: Lens' c Bool #
Instances
forecastPeriod :: InputOpts -> Journal -> Maybe DateSpan #
Get the Maybe the DateSpan to generate forecast options from. This begins on: - the start date supplied to the `--forecast` argument, if present - otherwise, the later of - the report start date if specified with -b-pdate: - the day after the latest normal (non-periodic) transaction in the journal, if any - otherwise today. It ends on: - the end date supplied to the `--forecast` argument, if present - otherwise the report end date if specified with -e-pdate: - otherwise 180 days (6 months) from today.
Constructors
| InputOpts | |
Fields
| |
Instances
| Show InputOpts | |
| HasBalancingOpts InputOpts | |
Defined in Hledger.Read.InputOptions | |
| HasInputOpts InputOpts | |
Defined in Hledger.Read.InputOptions Methods inputOpts :: Lens' InputOpts InputOpts # aliases :: Lens' InputOpts [String] # anon__ :: Lens' InputOpts Bool # auto__ :: Lens' InputOpts Bool # balancingopts :: Lens' InputOpts BalancingOpts # forecast :: Lens' InputOpts (Maybe DateSpan) # infer_costs :: Lens' InputOpts Bool # infer_equity :: Lens' InputOpts Bool # ioDay :: Lens' InputOpts Day # mformat :: Lens' InputOpts (Maybe StorageFormat) # mrules_file :: Lens' InputOpts (Maybe FilePath) # new__ :: Lens' InputOpts Bool # new_save :: Lens' InputOpts Bool # pivot :: Lens' InputOpts String # reportspan :: Lens' InputOpts DateSpan # | |
class HasBalancingOpts c where #
Minimal complete definition
Methods
balancingOpts :: Lens' c BalancingOpts #
commodity_styles :: Lens' c (Maybe (Map CommoditySymbol AmountStyle)) #
ignore_assertions :: Lens' c Bool #
infer_balancing_costs :: Lens' c Bool #
Instances
journalBalanceTransactions :: BalancingOpts -> Journal -> Either String Journal #
Infer any missing amounts and/or conversion costs (as needed to balance transactions and satisfy balance assignments); and check that all transactions are balanced; and (optional) check that all balance assertions pass. Or, return an error message (just the first error encountered).
Assumes journalStyleAmounts has been called, since amount styles affect transaction balancing.
This does multiple things at once because amount inferring, balance assignments, balance assertions and posting dates are interdependent.
journalCheckBalanceAssertions :: Journal -> Maybe String #
Check any balance assertions in the journal and return an error message if any of them fail (or if the transaction balancing they require fails).
balanceTransactionHelper :: BalancingOpts -> Transaction -> Either String (Transaction, [(AccountName, MixedAmount)]) #
Helper used by balanceTransaction and balanceTransactionWithBalanceAssignmentAndCheckAssertionsB; use one of those instead. It also returns a list of accounts and amounts that were inferred.
balanceTransaction :: BalancingOpts -> Transaction -> Either String Transaction #
Balance this transaction, ensuring that its postings (and its balanced virtual postings) sum to 0, by inferring a missing amount or conversion price(s) if needed. Or if balancing is not possible, because the amounts don't sum to 0 or because there's more than one missing amount, return an error message.
Transactions with balance assignments can have more than one missing amount; to balance those you should use the more powerful journalBalanceTransactions.
The "sum to 0" test is done using commodity display precisions, if provided, so that the result agrees with the numbers users can see.
isTransactionBalanced :: BalancingOpts -> Transaction -> Bool #
Legacy form of transactionCheckBalanced.
data BalancingOpts #
Constructors
| BalancingOpts | |
Fields
| |
Instances
| Show BalancingOpts | |
Defined in Hledger.Data.Balancing Methods showsPrec :: Int -> BalancingOpts -> ShowS # show :: BalancingOpts -> String # showList :: [BalancingOpts] -> ShowS # | |
| HasBalancingOpts BalancingOpts | |
journalCheckRecentAssertions :: Day -> Journal -> Either String () #
Check that accounts with balance assertions have no posting more than maxlag days after their latest balance assertion. Today's date is provided for error messages.
journalCheckPairedConversionPostings :: Journal -> Either String () #
In each tranaction, check that any conversion postings occur in adjacent pairs.
journalCheckTags :: Journal -> Either String () #
Check that all the journal's tags (on accounts, transactions, postings..) have been declared with tag directives, returning an error message otherwise.
journalCheckPayees :: Journal -> Either String () #
Check that all the journal's transactions have payees declared with payee directives, returning an error message otherwise.
journalCheckCommodities :: Journal -> Either String () #
Check that all the commodities used in this journal's postings have been declared by commodity directives, returning an error message otherwise.
journalCheckAccounts :: Journal -> Either String () #
Check that all the journal's postings are to accounts with account directives, returning an error message otherwise.
journalCheckUniqueleafnames :: Journal -> Either String () #
Check that all the journal's postings are to accounts with a unique leaf name. Otherwise, return an error message for the first offending posting.
journalApplyAliases :: [AccountAlias] -> Journal -> Either RegexError Journal #
Apply some account aliases to all posting account names in the journal, as described by accountNameApplyAliases. This can fail due to a bad replacement pattern in a regular expression alias.
journalPivot :: Text -> Journal -> Journal #
Apply the pivot transformation to all postings in a journal, replacing their account name by their value for the given field or tag.
journalLastDay :: Bool -> Journal -> Maybe Day #
The latest of this journal's transaction and posting dates, or Nothing if there are none.
journalEndDate :: Bool -> Journal -> Maybe Day #
The "exclusive end date" of this journal: the day following its latest transaction or posting date, or Nothing if there are none.
journalStartDate :: Bool -> Journal -> Maybe Day #
The earliest of this journal's transaction and posting dates, or Nothing if there are none.
journalDateSpanBothDates :: Journal -> DateSpan #
The fully specified date span enclosing the dates (primary and secondary) of all this journal's transactions and postings, or DateSpan Nothing Nothing if there are none.
journalDateSpan :: Bool -> Journal -> DateSpan #
The fully specified exact date span enclosing the dates (primary or secondary) of all this journal's transactions and postings, or DateSpan Nothing Nothing if there are none.
journalMarkRedundantCosts :: Journal -> Either String Journal #
Do just the internal tagging that is normally done by journalInferCostsFromEquity, identifying equity conversion postings and, in particular, postings which have redundant costs. Tagging the latter is useful as it allows them to be ignored during transaction balancedness checking. And that allows journalInferCostsFromEquity to be postponed till after transaction balancing, when it will have more information (amounts) to work with.
journalInferCostsFromEquity :: Journal -> Either String Journal #
Add costs inferred from equity conversion postings, where needed and possible. See hledger manual > Cost reporting.
journalInferEquityFromCosts :: Bool -> Journal -> Journal #
Add equity postings inferred from costs, where needed and possible. See hledger manual > Cost reporting.
journalToCost :: ConversionOp -> Journal -> Journal #
Convert all this journal's amounts to cost using their attached prices, if any.
journalInferMarketPricesFromTransactions :: Journal -> Journal #
Infer transaction-implied market prices from commodity-exchanging transactions, if any. It's best to call this after transactions have been balanced and posting amounts have appropriate prices attached.
canonicalStyleFrom :: [AmountStyle] -> AmountStyle #
Given a list of amount styles (assumed to be from parsed amounts in a single commodity), in parse order, choose a canonical style.
commodityStylesFromAmounts :: [Amount] -> Either String (Map CommoditySymbol AmountStyle) #
Given a list of amounts, in parse order (roughly speaking; see journalStyleInfluencingAmounts), build a map from their commodity names to standard commodity display formats. Can return an error message eg if inconsistent number formats are found.
Though, these amounts may have come from multiple files, so we shouldn't assume they use consistent number formats. Currently we don't enforce that even within a single file, and this function never reports an error.
journalInferCommodityStyles :: Journal -> Either String Journal #
Collect and save inferred amount styles for each commodity based on the posting amounts in that commodity (excluding price amounts), ie: "the format of the first amount, adjusted to the highest precision of all amounts". Can return an error message eg if inconsistent number formats are found.
journalCommodityStylesWith :: Rounding -> Journal -> Map CommoditySymbol AmountStyle #
Like journalCommodityStyles, but attach a particular rounding strategy to the styles, affecting how they will affect display precisions when applied.
journalCommodityStyles :: Journal -> Map CommoditySymbol AmountStyle #
Get the canonical amount styles for this journal, whether (in order of precedence): set globally in InputOpts, declared by commodity directives, declared by a default commodity (D) directive, or inferred from posting amounts, as a map from symbol to style. Styles from directives are assumed to specify the decimal mark.
journalStyleAmounts :: Journal -> Either String Journal #
Apply this journal's commodity display styles to all of its amounts. This does no display rounding, keeping decimal digits as they were; it is suitable for an early cleanup pass before calculations. Reports may want to do additional rounding/styling at render time. This can return an error message eg if inconsistent number formats are found.
journalModifyTransactions :: Bool -> Day -> Journal -> Either String Journal #
Apply any transaction modifier rules in the journal (adding automated postings to transactions, eg). Or if a modifier rule fails to parse, return the error message. A reference date is provided to help interpret relative dates in transaction modifier queries. The first argument selects whether to add visible tags to generated postings & modified transactions.
journalUntieTransactions :: Transaction -> Transaction #
Untie all transaction-posting knots in this journal, so that eg recursiveSize and GHCI's :sprint can work on it.
journalNumberTransactions :: Journal -> Journal #
Number (set the tindex field) this journal's transactions, counting upward from 1.
journalSetLastReadTime :: POSIXTime -> Journal -> Journal #
Set this journal's last read time, ie when its files were last read.
journalReverse :: Journal -> Journal #
Reverse all lists of parsed items, which during parsing were prepended to, so that the items are in parse order. Part of post-parse finalisation.
journalMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Journal -> Journal #
Apply a transformation to a journal's posting amounts.
journalMapPostings :: (Posting -> Posting) -> Journal -> Journal #
Apply a transformation to a journal's postings.
journalMapTransactions :: (Transaction -> Transaction) -> Journal -> Journal #
Apply a transformation to a journal's transactions.
filterTransactionPostingsExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Transaction #
filterPostingAmount :: Query -> Posting -> Maybe Posting #
Filter out all parts of this posting's amount which do not match the query, and remove the posting if this removes all amounts.
filterTransactionAmounts :: Query -> Transaction -> Transaction #
Filter out all parts of this transaction's amounts which do not match the query, and remove any postings with all amounts removed. This can leave the transaction unbalanced.
filterJournalAmounts :: Query -> Journal -> Journal #
Within each posting's amount, keep only the parts matching the query, and remove any postings with all amounts removed. This can leave unbalanced transactions.
filterJournalRelatedPostings :: Query -> Journal -> Journal #
Keep only postings which do not match the query expression, but for which a related posting does. This can leave unbalanced transactions.
filterJournalPostings :: Query -> Journal -> Journal #
Keep only postings matching the query expression. This can leave unbalanced transactions.
filterJournalTransactions :: Query -> Journal -> Journal #
Keep only transactions matching the query expression.
journalPostingsAddAccountTags :: Journal -> Journal #
To all postings in the journal, add any tags from their account (including those inherited from parent accounts). If the same tag exists on posting and account, the latter is ignored.
journalAccountTypes :: Journal -> Map AccountName AccountType #
Build a map of all known account types, explicitly declared or inferred from the account's parent or name.
journalAddAccountTypes :: Journal -> Journal #
Add a map of all known account types to the journal.
journalAccountType :: Journal -> AccountName -> Maybe AccountType #
journalConversionAccount :: Journal -> AccountName #
The AccountName to use for automatically generated conversion postings.
journalTransactionsSimilarTo :: Journal -> Text -> Query -> SimilarityScore -> Int -> [(DateWeightedSimilarityScore, Age, SimilarityScore, Transaction)] #
Find up to N most similar and most recent transactions matching the given transaction description and query and exceeding the given description similarity score (0 to 1, see compareDescriptions). Returns transactions along with their age in days compared to the latest transaction date, their description similarity score, and a heuristically date-weighted variant of this that favours more recent transactions.
journalInheritedAccountTags :: Journal -> AccountName -> [Tag] #
Which tags are in effect for this account, including tags inherited from parent accounts ?
journalAccountTags :: Journal -> AccountName -> [Tag] #
Which tags have been declared explicitly for this account, if any ?
journalLeafAccountNames :: Journal -> [AccountName] #
Sorted unique account names declared or implied in this journal which have no children.
journalAccountNames :: Journal -> [AccountName] #
Convenience/compatibility alias for journalAccountNamesDeclaredOrImplied.
journalAccountNamesDeclaredOrImplied :: Journal -> [AccountName] #
Sorted unique account names declared by account directives, or posted to or implied as parents by transactions in this journal.
journalAccountNamesDeclaredOrUsed :: Journal -> [AccountName] #
Sorted unique account names declared by account directives or posted to by transactions in this journal.
journalLeafAccountNamesDeclared :: Journal -> [AccountName] #
Sorted unique account names declared by account directives in this journal, which have no children.
journalAccountNamesDeclared :: Journal -> [AccountName] #
Sorted unique account names declared by account directives in this journal.
journalAccountNamesImplied :: Journal -> [AccountName] #
Sorted unique account names implied by this journal's transactions - accounts posted to and all their implied parent accounts.
journalAccountNamesUsed :: Journal -> [AccountName] #
Sorted unique account names posted to by this journal's transactions.
journalTagsDeclaredOrUsed :: Journal -> [TagName] #
Sorted unique tag names used in transactions or declared by tag directives in this journal.
journalTagsUsed :: Journal -> [TagName] #
Sorted unique tag names used in this journal (in account directives, transactions, postings..)
journalTagsDeclared :: Journal -> [TagName] #
Sorted unique tag names declared by tag directives in this journal.
journalPayeesDeclaredOrUsed :: Journal -> [Payee] #
Sorted unique payees used in transactions or declared by payee directives in this journal.
journalPayeesUsed :: Journal -> [Payee] #
Sorted unique payees used by transactions in this journal.
journalPayeesDeclared :: Journal -> [Payee] #
Sorted unique payees declared by payee directives in this journal.
journalDescriptions :: Journal -> [Text] #
Unique transaction descriptions used in this journal.
journalCommodities :: Journal -> Set CommoditySymbol #
Sorted unique commodity symbols declared or inferred from this journal.
journalCommoditiesDeclared :: Journal -> [CommoditySymbol] #
Sorted unique commodity symbols declared by commodity directives in this journal.
showJournalAmountsDebug :: Journal -> String #
Show the journal amounts rendered, suitable for debug logging.
journalPostingAmounts :: Journal -> [MixedAmount] #
All posting amounts from this journal, in order.
journalPostings :: Journal -> [Posting] #
All postings from this journal's transactions, in order.
journalPrevTransaction :: Journal -> Transaction -> Maybe Transaction #
Get the transaction that appeared immediately before this one in the input stream, if any.
journalNextTransaction :: Journal -> Transaction -> Maybe Transaction #
Get the transaction that appeared immediately after this one in the input stream, if any.
journalTransactionAt :: Journal -> Integer -> Maybe Transaction #
Get the transaction with this index (its 1-based position in the input stream), if any.
addPriceDirective :: PriceDirective -> Journal -> Journal #
addTransaction :: Transaction -> Journal -> Journal #
journalFilePaths :: Journal -> [FilePath] #
journalFilePath :: Journal -> FilePath #
nulljournal :: Journal #
dbgJournalAcctDeclOrder :: String -> Journal -> Journal #
Debug log the ordering of a journal's account declarations (at debug level 5+).
journalRenumberAccountDeclarations :: Journal -> Journal #
Renumber all the account declarations. This is useful to call when finalising or concatenating Journals, to give account declarations a total order across files.
journalConcat :: Journal -> Journal -> Journal #
Merge two journals into one. Transaction counts are summed, map fields are combined, the second's list fields are appended to the first's, the second's parse state is kept.
type JournalParser (m :: Type -> Type) a = StateT Journal (ParsecT HledgerParseErrorData Text m) a #
A parser of text that runs in some monad, keeping a Journal as state.
type ErroringJournalParser (m :: Type -> Type) a = StateT Journal (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a #
A parser of text that runs in some monad, keeping a Journal as state, that can throw an exception to end parsing, preventing further parser backtracking.
readJsonFile :: FromJSON a => FilePath -> IO a #
Read a JSON file and decode it to the target type, or raise an error if we can't. Eg: readJsonFile "a.json" :: IO Transaction
writeJsonFile :: ToJSON a => FilePath -> a -> IO () #
Write a JSON-convertible haskell value to a pretty-printed JSON file. Eg: writeJsonFile "a.json" nulltransaction
toJsonText :: ToJSON a => a -> Text #
Show a JSON-convertible haskell value as pretty-printed JSON text.
checkPeriodicTransactionStartDate :: Interval -> DateSpan -> Text -> Maybe String #
Check that this date span begins at a boundary of this interval, or return an explanatory error message including the provided period expression (from which the span and interval are derived).
runPeriodicTransaction :: Bool -> PeriodicTransaction -> DateSpan -> [Transaction] #
Generate transactions from PeriodicTransaction within a DateSpan.
This should be a closed span with both start and end dates specified;
an open ended span will generate no transactions.
Note that new transactions require txnTieKnot post-processing.
The new transactions will have three tags added:
- a recur:PERIODICEXPR tag whose value is the generating periodic expression
- a generated-transaction: tag
- a hidden _generated-transaction: tag which does not appear in the comment.
>>>import Data.Time (fromGregorian)>>>_ptgen "monthly from 2017/1 to 2017/4"2017-01-01 ; generated-transaction: ~ monthly from 2017/1 to 2017/4 a $1.00 2017-02-01 ; generated-transaction: ~ monthly from 2017/1 to 2017/4 a $1.00 2017-03-01 ; generated-transaction: ~ monthly from 2017/1 to 2017/4 a $1.00
>>>_ptgen "monthly from 2017/1 to 2017/5"2017-01-01 ; generated-transaction: ~ monthly from 2017/1 to 2017/5 a $1.00 2017-02-01 ; generated-transaction: ~ monthly from 2017/1 to 2017/5 a $1.00 2017-03-01 ; generated-transaction: ~ monthly from 2017/1 to 2017/5 a $1.00 2017-04-01 ; generated-transaction: ~ monthly from 2017/1 to 2017/5 a $1.00
>>>_ptgen "every 2nd day of month from 2017/02 to 2017/04"2017-01-02 ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04 a $1.00 2017-02-02 ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04 a $1.00 2017-03-02 ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04 a $1.00
>>>_ptgen "every 30th day of month from 2017/1 to 2017/5"2016-12-30 ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5 a $1.00 2017-01-30 ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5 a $1.00 2017-02-28 ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5 a $1.00 2017-03-30 ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5 a $1.00 2017-04-30 ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5 a $1.00
>>>_ptgen "every 2nd Thursday of month from 2017/1 to 2017/4"2016-12-08 ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4 a $1.00 2017-01-12 ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4 a $1.00 2017-02-09 ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4 a $1.00 2017-03-09 ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4 a $1.00
>>>_ptgen "every nov 29th from 2017 to 2019"2016-11-29 ; generated-transaction: ~ every nov 29th from 2017 to 2019 a $1.00 2017-11-29 ; generated-transaction: ~ every nov 29th from 2017 to 2019 a $1.00 2018-11-29 ; generated-transaction: ~ every nov 29th from 2017 to 2019 a $1.00
>>>_ptgen "2017/1"2017-01-01 ; generated-transaction: ~ 2017/1 a $1.00
>>>let reportperiod="daily from 2018/01/03" in let (i,s) = parsePeriodExpr' nulldate reportperiod in runPeriodicTransaction True (nullperiodictransaction{ptperiodexpr=reportperiod, ptspan=s, ptinterval=i, ptpostings=["a" `post` usd 1]}) (DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03))[]
>>>_ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 01 01) (Just $ Flex $ fromGregorian 2020 02 01))
>>>_ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 02 01) (Just $ Flex $ fromGregorian 2020 03 01))2020-02-01 ; generated-transaction: ~ every 3 months from 2019-05 a $1.00>>>_ptgenspan "every 3 days from 2018" (DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 05))2018-01-01 ; generated-transaction: ~ every 3 days from 2018 a $1.00 2018-01-04 ; generated-transaction: ~ every 3 days from 2018 a $1.00>>>_ptgenspan "every 3 days from 2018" (DateSpan (Just $ Flex $ fromGregorian 2018 01 02) (Just $ Flex $ fromGregorian 2018 01 05))2018-01-04 ; generated-transaction: ~ every 3 days from 2018 a $1.00
makeBalanceAssertionErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text) #
From the given posting, make an error excerpt showing the transaction with the balance assertion highlighted.
makePostingAccountErrorExcerpt :: Posting -> (FilePath, Int, Maybe (Int, Maybe Int), Text) #
From the given posting, make an error excerpt showing the transaction with this posting's account part highlighted.
transactionFindPostingIndex :: (Posting -> Bool) -> Transaction -> Maybe Int #
Find the 1-based index of the first posting in this transaction satisfying the given predicate.
makePostingErrorExcerpt :: Posting -> (Posting -> Transaction -> Text -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text) #
Given a problem posting and a function calculating the best column(s) for marking the error region: look up error info from the parent transaction, and render the transaction as a megaparsec-style excerpt, showing the original line number on the problem posting's line, and a column indicator. Returns the file path, line number, column(s) if known, and the rendered excerpt, or as much of these as is possible. A limitation: columns will be accurate for the rendered error message but not for the original journal data.
makeTransactionErrorExcerpt :: Transaction -> (Transaction -> Maybe (Int, Maybe Int)) -> (FilePath, Int, Maybe (Int, Maybe Int), Text) #
Given a problem transaction and a function calculating the best column(s) for marking the error region: render it as a megaparsec-style excerpt, showing the original line number on the transaction line, and a column(s) marker. Returns the file path, line number, column(s) if known, and the rendered excerpt, or as much of these as is possible. The returned columns will be accurate for the rendered error message but not for the original journal data.
makeAccountTagErrorExcerpt :: (AccountName, AccountDeclarationInfo) -> TagName -> (FilePath, Int, Maybe (Int, Maybe Int), Text) #
Given an account name and its account directive, and a problem tag within the latter: render it as a megaparsec-style excerpt, showing the original line number and marked column or region. Returns the file path, line number, column(s) if known, and the rendered excerpt, or as much of these as is possible. The returned columns will be accurate for the rendered error message but not for the original journal data.
timeclockEntriesToTransactions :: LocalTime -> [TimeclockEntry] -> [Transaction] #
Convert time log entries to journal transactions. When there is no clockout, add one with the provided current time. Sessions crossing midnight are split into days to give accurate per-day totals.
modifyTransactions :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Map CommoditySymbol AmountStyle -> Day -> Bool -> [TransactionModifier] -> [Transaction] -> Either String [Transaction] #
Apply all the given transaction modifiers, in turn, to each transaction. Or if any of them fails to be parsed, return the first error. A reference date is provided to help interpret relative dates in transaction modifier queries.
tests_Query :: TestTree #
matchesPriceDirective :: Query -> PriceDirective -> Bool #
Does the query match this market price ?
matchesTags :: Regexp -> Maybe Regexp -> [Tag] -> Bool #
Does the query match the name and optionally the value of any of these tags ?
matchesPayeeWIP :: Query -> Payee -> Bool #
Does the query match this transaction payee ? Tests desc: (and payee: ?) terms, any other terms are ignored. XXX Currently an alias for matchDescription. I'm not sure if more is needed, There's some shenanigan with payee: and "payeeTag" to figure out.
matchesDescription :: Query -> Text -> Bool #
Does the query match this transaction description ? Tests desc: terms, any other terms are ignored.
matchesTransactionExtra :: (AccountName -> Maybe AccountType) -> Query -> Transaction -> Bool #
Like matchesTransaction, but if the journal's account types are provided, any type: terms in the query must match at least one posting's account type (and any negated type: terms must match none).
matchesTransaction :: Query -> Transaction -> Bool #
Does the match expression match this transaction ?
matchesPostingExtra :: (AccountName -> Maybe AccountType) -> Query -> Posting -> Bool #
Like matchesPosting, but if the posting's account's type is provided, any type: terms in the query must match it (and any negated type: terms must not match it).
matchesPosting :: Query -> Posting -> Bool #
Does the match expression match this posting ? When matching account name, and the posting has been transformed in some way, we will match either the original or transformed name.
matchesAccountExtra :: (AccountName -> Maybe AccountType) -> (AccountName -> [Tag]) -> Query -> AccountName -> Bool #
Like matchesAccount, but with optional extra matching features:
- If the account's type is provided, any type: terms in the query must match it (and any negated type: terms must not match it).
- If the account's tags are provided, any tag: terms must match at least one of them (and any negated tag: terms must match none).
matchesAccount :: Query -> AccountName -> Bool #
Does the query match this account name ? A matching in: clause is also considered a match.
matchesMixedAmount :: Query -> MixedAmount -> Bool #
matchesAmount :: Query -> Amount -> Bool #
Does the match expression match this (simple) amount ?
matchesCommodity :: Query -> CommoditySymbol -> Bool #
inAccountQuery :: [QueryOpt] -> Maybe Query #
A query for the account(s) we are currently focussed on, if any. Just looks at the first query option.
inAccount :: [QueryOpt] -> Maybe (AccountName, Bool) #
The account we are currently focussed on, if any, and whether subaccounts are included. Just looks at the first query option.
queryDepth :: Query -> Maybe Int #
The depth limit this query specifies, if it has one
queryDateSpan' :: Query -> DateSpan #
What date span does this query specify, treating primary and secondary dates as equivalent ? OR clauses specifying multiple spans return their union (the span enclosing all of them). AND clauses specifying multiple spans return their intersection. NOT clauses are ignored.
queryDateSpan :: Bool -> Query -> DateSpan #
What date span (or with a true argument, what secondary date span) does this query specify ? OR clauses specifying multiple spans return their union (the span enclosing all of them). AND clauses specifying multiple spans return their intersection. NOT clauses are ignored.
queryEndDate :: Bool -> Query -> Maybe Day #
What end date (or secondary date) does this query specify, if any ? For OR expressions, use the latest of the dates. NOT is ignored.
queryStartDate :: Bool -> Query -> Maybe Day #
What start date (or secondary date) does this query specify, if any ? For OR expressions, use the earliest of the dates. NOT is ignored.
queryIsTransactionRelated :: Query -> Bool #
Does this query involve a property of transactions (or their postings), making it inapplicable to account declarations ?
queryIsStartDateOnly :: Bool -> Query -> Bool #
Does this query specify a start date and nothing else (that would filter postings prior to the date) ? When the flag is true, look for a starting secondary date instead.
queryIsSym :: Query -> Bool #
queryIsAmt :: Query -> Bool #
queryIsReal :: Query -> Bool #
queryIsDepth :: Query -> Bool #
queryIsType :: Query -> Bool #
queryIsAcct :: Query -> Bool #
queryIsTag :: Query -> Bool #
queryIsDesc :: Query -> Bool #
queryIsCode :: Query -> Bool #
queryIsStatus :: Query -> Bool #
queryIsDateOrDate2 :: Query -> Bool #
queryIsDate2 :: Query -> Bool #
queryIsDate :: Query -> Bool #
Is this a simple query of this type (date:) ? Does not match a compound query involving andornot. Likewise for the following functions.
queryIsNull :: Query -> Bool #
Does this query match everything ?
matchesQuery :: (Query -> Bool) -> Query -> Bool #
Does this simple query predicate match any part of this possibly compound query ?
filterQueryOrNotQuery :: (Query -> Bool) -> Query -> Query #
Remove query terms (or whole sub-expressions) from this query which match neither the given predicate nor that predicate negated (eg, if predicate is queryIsAcct, this will keep both "acct:" and "not:acct:" terms). Also calls simplifyQuery on the result. (Since 1.24.1, might be merged into filterQuery in future.) XXX Semantics not completely clear.
filterQuery :: (Query -> Bool) -> Query -> Query #
Remove query terms (or whole sub-expressions) from this query which do not match the given predicate. XXX Semantics not completely clear. Also calls simplifyQuery on the result.
simplifyQuery :: Query -> Query #
parseAccountType :: Bool -> Text -> Either String AccountType #
Case-insensitively parse one single-letter code, or one long-form word if permitted, to an account type. On failure, returns the unparseable text.
parseQueryTerm :: Day -> Text -> Either String (Query, [QueryOpt]) #
Parse a single query term as either a query or a query option, or return an error message if parsing fails.
queryprefixes :: [Text] #
words'' :: [Text] -> Text -> [Text] #
Quote-and-prefix-aware version of words - don't split on spaces which are inside quotes, including quotes which may have one of the specified prefixes in front, and maybe an additional not: prefix in front of that.
parseQueryList :: Day -> [Text] -> Either String (Query, [QueryOpt]) #
Convert a list of space-separated queries to a single query
Multiple terms are combined as follows: 1. multiple account patterns are OR'd together 2. multiple description patterns are OR'd together 3. multiple status patterns are OR'd together 4. then all terms are AND'd together
parseQuery :: Day -> Text -> Either String (Query, [QueryOpt]) #
A version of parseQueryList which acts on a single Text of space-separated terms.
The usual shell quoting rules are assumed. When a pattern contains whitespace, it (or the whole term including prefix) should be enclosed in single or double quotes.
A query term is either:
a search pattern, which matches on one or more fields, eg:
acct:REGEXP - match the account name with a regular expression desc:REGEXP - match the transaction description date:PERIODEXP - match the date with a period expression
The prefix indicates the field to match, or if there is no prefix account name is assumed.
a query option, which modifies the reporting behaviour in some way. There is currently one of these, which may appear only once:
inacct:FULLACCTNAME
Period expressions may contain relative dates, so a reference date is required to fully parse these.
>>>parseQuery nulldate "expenses:dining out"Right (Or [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])
>>>parseQuery nulldate "\"expenses:dining out\""Right (Acct (RegexpCI "expenses:dining out"),[])
generatedTransactionTag :: Query #
Construct a generated-transaction tag
A query is a composition of search criteria, which can be used to match postings, transactions, accounts and more.
Constructors
| Not Query | negate this match |
| And [Query] | match if all of these match |
| Or [Query] | match if any of these match no-op queries |
| Any | always match |
| None | never match data queries (in "standard" order, roughly as they appear in a transaction) |
| Date DateSpan | match primary dates in this date span |
| Date2 DateSpan | match secondary dates in this date span |
| StatusQ Status | match this txn/posting status |
| Code Regexp | match txn codes infix-matched by this regexp |
| Desc Regexp | match txn descriptions infix-matched by this regexp |
| Tag Regexp (Maybe Regexp) | match if a tag's name, and optionally its value, is infix-matched by the respective regexps |
| Acct Regexp | match account names infix-matched by this regexp |
| Type [AccountType] | match accounts whose type is one of these (or with no types, any account) |
| Depth Int | match if account depth is less than or equal to this value (or, sometimes used as a display option) |
| Real Bool | match postings with this "realness" value |
| Amt OrdPlus Quantity | match if the amount's numeric quantity is less thangreater thanequal to/unsignedly equal to some value |
| Sym Regexp | match if the commodity symbol is fully-matched by this regexp |
A more expressive Ord, used for amt: queries. The Abs* variants compare with the absolute value of a number, ignoring sign.
A query option changes a query's/report's behaviour and output in some way.
Constructors
| QueryOptInAcctOnly AccountName | show an account register focussed on this account |
| QueryOptInAcct AccountName | as above but include sub-accounts in the account register | QueryOptCostBasis -- ^ show amounts converted to cost where possible | QueryOptDate2 -- ^ show secondary dates instead of primary dates |
annotateErrorWithTransaction :: Transaction -> String -> String #
transactionFile :: Transaction -> FilePath #
The file path from which this transaction was parsed.
transactionAmounts :: Transaction -> [MixedAmount] #
All posting amounts from this transactin, in order.
transactionMapPostingAmounts :: (MixedAmount -> MixedAmount) -> Transaction -> Transaction #
Apply a transformation to a transaction's posting amounts.
transactionMapPostings :: (Posting -> Posting) -> Transaction -> Transaction #
Apply a transformation to a transaction's postings.
transactionApplyAliases :: [AccountAlias] -> Transaction -> Either RegexError Transaction #
Apply some account aliases to all posting account names in the transaction, as described by accountNameApplyAliases. This can fail due to a bad replacement pattern in a regular expression alias.
partitionAndCheckConversionPostings :: Bool -> Map AccountName AccountType -> [IdxPosting] -> Either Text ([(IdxPosting, IdxPosting)], ([IdxPosting], [IdxPosting])) #
transactionInferCostsFromEquity :: Bool -> Map AccountName AccountType -> Transaction -> Either String Transaction #
Add costs inferred from equity postings in this transaction. For every adjacent pair of conversion postings, it will first search the postings with costs to see if any match. If so, it will tag these as matched. If no postings with costs match, it will then search the postings without costs, and will match the first such posting which matches one of the conversion amounts. If it finds a match, it will add a cost and then tag it. If the first argument is true, do a dry run instead: identify and tag the costful and conversion postings, but don't add costs.
transactionAddInferredEquityPostings :: Bool -> AccountName -> Transaction -> Transaction #
Add inferred equity postings to a Transaction using transaction prices.
transactionToCost :: ConversionOp -> Transaction -> Transaction #
Maybe convert this Transactions amounts to cost.
transactionApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Transaction -> Transaction #
Apply a specified valuation to this transaction's amounts, using the provided price oracle, commodity styles, and reference dates. See amountApplyValuation.
transactionTransformPostings :: (Posting -> Posting) -> Transaction -> Transaction #
Apply a transform function to this transaction's amounts.
txnUntieKnot :: Transaction -> Transaction #
Ensure a transaction's postings do not refer back to it, so that eg recursiveSize and GHCI's :sprint work right.
txnTieKnot :: Transaction -> Transaction #
Ensure a transaction's postings refer back to it, so that eg relatedPostings works right.
transactionDateOrDate2 :: WhichDate -> Transaction -> Day #
transactionDate2 :: Transaction -> Day #
transactionsPostings :: [Transaction] -> [Posting] #
balancedVirtualPostings :: Transaction -> [Posting] #
virtualPostings :: Transaction -> [Posting] #
assignmentPostings :: Transaction -> [Posting] #
realPostings :: Transaction -> [Posting] #
hasRealPostings :: Transaction -> Bool #
showTransactionBeancount :: Transaction -> Text #
Like showTransaction, but generates Beancount journal format.
showTransactionOneLineAmounts :: Transaction -> Text #
Like showTransaction, but explicit multi-commodity amounts are shown on one line, comma-separated. In this case the output will not be parseable journal syntax.
showTransaction :: Transaction -> Text #
Render a journal transaction as text similar to the style of Ledger's print command.
Adapted from Ledger 2.x and 3.x standard format:
yyyy-mm-dd[ *][ CODE] description......... [ ; comment...............]
account name 1..................... ...$amount1[ ; comment...............]
account name 2..................... ..$-amount1[ ; comment...............]
pcodewidth = no limit -- 10 -- mimicking ledger layout.
pdescwidth = no limit -- 20 -- I don't remember what these mean,
pacctwidth = 35 minimum, no maximum -- they were important at the time.
pamtwidth = 11
pcommentwidth = no limit -- 22
The output will be parseable journal syntax. To facilitate this, postings with explicit multi-commodity amounts are displayed as multiple similar postings, one per commodity. (Normally does not happen with this function).
transactionNote :: Transaction -> Text #
transactionPayee :: Transaction -> Text #
transaction :: Day -> [Posting] -> Transaction #
Make a simple transaction with the given date and postings.
commentAddTagNextLine :: Text -> Tag -> Text #
Add a tag on its own line to a comment, preserving any prior content. A space is inserted following the colon, before the value.
commentAddTagUnspaced :: Text -> Tag -> Text #
Like commentAddTag, but omits the space after the colon.
commentAddTag :: Text -> Tag -> Text #
Add a tag to a comment, comma-separated from any prior content. A space is inserted following the colon, before the value.
commentJoin :: Text -> Text -> Text #
Join two parts of a comment, eg a tag and another tag, or a tag and a non-tag, on a single line. Interpolates a comma and space unless one of the parts is empty.
postingTransformAmount :: (MixedAmount -> MixedAmount) -> Posting -> Posting #
Apply a transform function to this posting's amount.
postingPriceDirectivesFromCost :: Posting -> [PriceDirective] #
Make a market price equivalent to this posting's amount's unit price, if any.
postingAddInferredEquityPostings :: Bool -> Text -> Posting -> [Posting] #
Generate inferred equity postings from a Posting using transaction prices.
Make sure not to generate equity postings when there are already matched
conversion postings.
postingToCost :: ConversionOp -> Posting -> Maybe Posting #
Maybe convert this Postings amount to cost.
postingApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> ValuationType -> Posting -> Posting #
Apply a specified valuation to this posting's amount, using the provided price oracle, commodity styles, and reference dates. See amountApplyValuation.
postingAddTags :: Posting -> [Tag] -> Posting #
Add tags to a posting, discarding any for which the posting already has a value.
postingApplyAliases :: [AccountAlias] -> Posting -> Either RegexError Posting #
Apply some account aliases to the posting's account name, as described by accountNameApplyAliases. This can fail due to a bad replacement pattern in a regular expression alias.
isEmptyPosting :: Posting -> Bool #
isPostingInDateSpan :: DateSpan -> Posting -> Bool #
Does this posting fall within the given date span ?
relatedPostings :: Posting -> [Posting] #
transactionAllTags :: Transaction -> [Tag] #
Tags for this transaction including any from its postings.
postingAllTags :: Posting -> [Tag] #
Tags for this posting including any inherited from its parent transaction.
postingStatus :: Posting -> Status #
Get a posting's status. This is cleared or pending if those are explicitly set on the posting, otherwise the status of its parent transaction, or unmarked if there is no parent transaction. (Note the ambiguity, unmarked can mean "posting and transaction are both unmarked" or "posting is unmarked and don't know about the transaction".
postingDateOrDate2 :: WhichDate -> Posting -> Day #
Get a posting's primary or secondary date, as specified.
postingDate2 :: Posting -> Day #
Get a posting's secondary (secondary) date, which is the first of: posting's secondary date, transaction's secondary date, posting's primary date, transaction's primary date, or the null date if there is no parent transaction.
postingDate :: Posting -> Day #
Get a posting's (primary) date - it's own primary date if specified, otherwise the parent transaction's primary date, or the null date if there is no parent transaction.
postingStripPrices :: Posting -> Posting #
Strip all prices from a Posting.
sumPostings :: [Posting] -> MixedAmount #
Sum all amounts from a list of postings.
accountNamesFromPostings :: [Posting] -> [AccountName] #
Sorted unique account names referenced by these postings.
hasBalanceAssignment :: Posting -> Bool #
isBalancedVirtual :: Posting -> Bool #
renderCommentLines :: Text -> [Text] #
Render a transaction or posting's comment as indented, semicolon-prefixed comment lines. The first line (unless empty) will have leading space, subsequent lines will have a larger indent.
showAccountNameBeancount :: Maybe Int -> AccountName -> Text #
Like showAccountName for Beancount journal format. Calls accountNameToBeancount first.
postingAsLinesBeancount :: Bool -> Int -> Int -> Posting -> ([Text], Int, Int) #
Like postingAsLines but generates Beancount journal format.
postingsAsLinesBeancount :: [Posting] -> [Text] #
Like postingsAsLines but generates Beancount journal format.
showAccountName :: Maybe Int -> PostingType -> AccountName -> Text #
Show an account name, clipped to the given width if any, and appropriately bracketed/parenthesised for the given posting type.
postingAsLines :: Bool -> Bool -> Int -> Int -> Posting -> ([Text], Int, Int) #
Render one posting, on one or more lines, suitable for print output.
There will be an indented account name, plus one or more of status flag,
posting amount, balance assertion, same-line comment, next-line comments.
If the posting's amount is implicit or if elideamount is true, no amount is shown.
If the posting's amount is explicit and multi-commodity, multiple similar postings are shown, one for each commodity, to help produce parseable journal syntax. Or if onelineamounts is true, such amounts are shown on one line, comma-separated (and the output will not be valid journal syntax).
If an amount is zero, any commodity symbol attached to it is shown (and the corresponding commodity display style is used).
By default, 4 spaces (2 if there's a status flag) are shown between account name and start of amount area, which is typically 12 chars wide and contains a right-aligned amount (so 10-12 visible spaces between account name and amount is typical). When given a list of postings to be aligned with, the whitespace will be increased if needed to match the posting with the longest account name. This is used to align the amounts of a transaction's postings.
Also returns the account width and amount width used.
postingsAsLines :: Bool -> [Posting] -> [Text] #
Given a transaction and its postings, render the postings, suitable
for print output. Normally this output will be valid journal syntax which
hledger can reparse (though it may include no-longer-valid balance assertions).
Explicit amounts are shown, any implicit amounts are not.
Postings with multicommodity explicit amounts are handled as follows: if onelineamounts is true, these amounts are shown on one line, comma-separated, and the output will not be valid journal syntax. Otherwise, they are shown as several similar postings, one per commodity. When the posting has a balance assertion, it is attached to the last of these postings.
The output will appear to be a balanced transaction. Amounts' display precisions, which may have been limited by commodity directives, will be increased if necessary to ensure this.
Posting amounts will be aligned with each other, starting about 4 columns beyond the widest account name (see postingAsLines for details).
showPostingLines :: Posting -> [Text] #
Render a posting, at the appropriate width for aligning with its siblings if any. Used by the rewrite command.
showPosting :: Posting -> String #
originalPosting :: Posting -> Posting #
showBalanceAssertion :: BalanceAssertion -> WideBuilder #
Render a balance assertion, as the =[=][*] symbol and expected amount.
balassertTotInc :: Amount -> Maybe BalanceAssertion #
Make a total, inclusive balance assertion.
balassertParInc :: Amount -> Maybe BalanceAssertion #
Make a partial, inclusive balance assertion.
balassertTot :: Amount -> Maybe BalanceAssertion #
Make a total, exclusive balance assertion.
balassert :: Amount -> Maybe BalanceAssertion #
Make a partial, exclusive balance assertion.
nullsourcepos :: (SourcePos, SourcePos) #
vpost' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting #
Make a virtual (unbalanced) posting to an account, maybe with a balance assertion.
post' :: AccountName -> Amount -> Maybe BalanceAssertion -> Posting #
Make a posting to an account, maybe with a balance assertion.
vpost :: AccountName -> Amount -> Posting #
Make a virtual (unbalanced) posting to an account.
post :: AccountName -> Amount -> Posting #
Make a posting to an account.
nullposting :: Posting #
postingStyleAmounts :: Map CommoditySymbol AmountStyle -> Posting -> Posting #
Like postingApplyCommodityStyles, but neither main amount precisions or cost precisions are set.
postingApplyCommodityStyles :: Map CommoditySymbol AmountStyle -> Posting -> Posting #
Find and apply the appropriate display style to the posting amounts in each commodity (see journalCommodityStyles). Main amount precisions may be set or not according to the styles, but cost precisions are not set.
mixedAmountGainAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount #
Calculate the gain of each component amount, that is the difference between the valued amount and the value of the cost basis.
If the commodity we are valuing in is not the same as the commodity of the cost, this will value the cost at the same date as the primary amount. This may not be what you want; for example you may want the cost valued at the posting date. If so, let us know and we can change this behaviour.
mixedAmountApplyGain :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount #
Calculate the gain of each component amount, that is the difference between the valued amount and the value of the cost basis (see mixedAmountApplyValuation).
If the commodity we are valuing in is not the same as the commodity of the cost, this will value the cost at the same date as the primary amount. This may not be what you want; for example you may want the cost valued at the posting date. If so, let us know and we can change this behaviour.
mixedAmountValueAtDate :: PriceOracle -> Map CommoditySymbol AmountStyle -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount #
Find the market value of each component amount in the given commodity, or its default valuation commodity, at the given valuation date, using the given market price oracle. When market prices available on that date are not sufficient to calculate the value, amounts are left unchanged.
mixedAmountApplyValuation :: PriceOracle -> Map CommoditySymbol AmountStyle -> Day -> Day -> Day -> ValuationType -> MixedAmount -> MixedAmount #
Apply a specified valuation to this mixed amount, using the provided price oracle, commodity styles, and reference dates. See amountApplyValuation.
mixedAmountToCost :: Map CommoditySymbol AmountStyle -> ConversionOp -> MixedAmount -> MixedAmount #
Convert all component amounts to cost/selling price if requested, and style them.
amountPriceDirectiveFromCost :: Day -> Amount -> Maybe PriceDirective #
Infer a market price from the given amount and its cost (if any), and make a corresponding price directive on the given date. The price's display precision will be set to show all significant decimal digits; or if they seem to be infinite, defaultPrecisionLimit.
journalPriceOracle :: Bool -> Journal -> PriceOracle #
Generate a price oracle (memoising price lookup function) from a journal's directive-declared and transaction-inferred market prices. For best performance, generate this only once per journal, reusing it across reports if there are more than one, as compoundBalanceCommand does. The boolean argument is whether to infer market prices from transactions or not.
data ConversionOp #
Which operation to perform on conversion transactions. (There was also an "infer equity postings" operation, but that is now done earlier, in journal finalisation.)
Constructors
| NoConversionOp | |
| ToCost |
Instances
| Show ConversionOp | |
Defined in Hledger.Data.Valuation Methods showsPrec :: Int -> ConversionOp -> ShowS # show :: ConversionOp -> String # showList :: [ConversionOp] -> ShowS # | |
| Eq ConversionOp | |
Defined in Hledger.Data.Valuation | |
data ValuationType #
What kind of value conversion should be done on amounts ? CLI: --value=then|end|now|DATE[,COMM]
Constructors
| AtThen (Maybe CommoditySymbol) | convert to default or given valuation commodity, using market prices at each posting's date |
| AtEnd (Maybe CommoditySymbol) | convert to default or given valuation commodity, using market prices at period end(s) |
| AtNow (Maybe CommoditySymbol) | convert to default or given valuation commodity, using current market prices |
| AtDate Day (Maybe CommoditySymbol) | convert to default or given valuation commodity, using market prices on some date |
Instances
| Show ValuationType | |
Defined in Hledger.Data.Valuation Methods showsPrec :: Int -> ValuationType -> ShowS # show :: ValuationType -> String # showList :: [ValuationType] -> ShowS # | |
| Eq ValuationType | |
Defined in Hledger.Data.Valuation Methods (==) :: ValuationType -> ValuationType -> Bool # (/=) :: ValuationType -> ValuationType -> Bool # | |
type PriceOracle = (Day, CommoditySymbol, Maybe CommoditySymbol) -> Maybe (CommoditySymbol, Quantity) #
A price oracle is a magic memoising function that efficiently looks up market prices (exchange rates) from one commodity to another (or if unspecified, to a default valuation commodity) on a given date.
mixedAmountStripPrices :: MixedAmount -> MixedAmount #
Remove all prices from a MixedAmount.
mixedAmountSetPrecisionMax :: Word8 -> MixedAmount -> MixedAmount #
In each component amount, ensure the display precision is at most the given value. Makes all amounts have an explicit Precision.
mixedAmountSetPrecisionMin :: Word8 -> MixedAmount -> MixedAmount #
In each component amount, ensure the display precision is at least the given value. Makes all amounts have an explicit Precision.
mixedAmountSetFullPrecision :: MixedAmount -> MixedAmount #
In each component amount, increase the display precision sufficiently to render it exactly (showing all significant decimal digits).
mixedAmountSetPrecision :: AmountPrecision -> MixedAmount -> MixedAmount #
Set the display precision in the amount's commodities.
showMixedAmountLinesB :: AmountDisplayOpts -> MixedAmount -> [WideBuilder] #
Helper for showMixedAmountB (and postingAsLines, ...) to show a list of Amounts on multiple lines. This returns the list of WideBuilders: one for each Amount, and padded/elided to the appropriate width. This does not honour displayOneLine; all amounts will be displayed as if displayOneLine were False.
showMixedAmountB :: AmountDisplayOpts -> MixedAmount -> WideBuilder #
General function to generate a WideBuilder for a MixedAmount, according to the supplied AmountDisplayOpts. This is the main function to use for showing MixedAmounts, constructing a builder; it can then be converted to a Text with wbToText, or to a String with wbUnpack.
If a maximum width is given then: - If displayed on one line, it will display as many Amounts as can fit in the given width, and further Amounts will be elided. There will always be at least one amount displayed, even if this will exceed the requested maximum width. - If displayed on multiple lines, any Amounts longer than the maximum width will be elided.
showMixedAmountDebug :: MixedAmount -> String #
Get an unambiguous string representation of a mixed amount for debugging.
showMixedAmountElided :: Int -> Bool -> MixedAmount -> String #
Like showMixedAmountOneLineWithoutPrice, but show at most the given width, with an elision indicator if there are more. With a True argument, adds ANSI codes to show negative amounts in red.
showMixedAmountElided w c = wbUnpack . showMixedAmountB oneLine{displayColour=c, displayMaxWidth=Just w}showMixedAmountOneLineWithoutPrice :: Bool -> MixedAmount -> String #
Get the one-line string representation of a mixed amount, but without any @ prices. With a True argument, adds ANSI codes to show negative amounts in red.
showMixedAmountOneLineWithoutPrice c = wbUnpack . showMixedAmountB oneLine{displayColour=c}showMixedAmountWithoutPrice :: Bool -> MixedAmount -> String #
Get the string representation of a mixed amount, without showing any transaction prices. With a True argument, adds ANSI codes to show negative amounts in red.
showMixedAmountWithoutPrice c = wbUnpack . showMixedAmountB noPrice{displayColour=c}showMixedAmountWithZeroCommodity :: MixedAmount -> String #
Like showMixedAmount, but zero amounts are shown with their commodity if they have one.
showMixedAmountWithZeroCommodity = wbUnpack . showMixedAmountB noColour{displayZeroCommodity=True}showMixedAmountOneLine :: MixedAmount -> String #
Get the one-line string representation of a mixed amount (also showing any costs).
showMixedAmountOneLine = wbUnpack . showMixedAmountB oneLine
showMixedAmount :: MixedAmount -> String #
Get the string representation of a mixed amount, after normalising it to one amount per commodity. Assumes amounts have no or similar prices, otherwise this can show misleading prices.
showMixedAmount = wbUnpack . showMixedAmountB noColour
mixedAmountUnstyled :: MixedAmount -> MixedAmount #
Reset each individual amount's display style to the default.
styleMixedAmount :: Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount #
Given a map of standard commodity display styles, find and apply the appropriate style to each individual amount.
mixedAmountCost :: MixedAmount -> MixedAmount #
Convert all component amounts to cost/selling price where possible (see amountCost).
mapMixedAmount :: (Amount -> Amount) -> MixedAmount -> MixedAmount #
Apply a transform to a mixed amount's component Amounts.
filterMixedAmountByCommodity :: CommoditySymbol -> MixedAmount -> MixedAmount #
Return an unnormalised MixedAmount containing exactly one Amount with the specified commodity and the quantity of that commodity found in the original. NB if Amount's quantity is zero it will be discarded next time the MixedAmount gets normalised.
filterMixedAmount :: (Amount -> Bool) -> MixedAmount -> MixedAmount #
Filter a mixed amount's component amounts by a predicate.
unifyMixedAmount :: MixedAmount -> Maybe Amount #
Unify a MixedAmount to a single commodity value if possible. This consolidates amounts of the same commodity and discards zero amounts; but this one insists on simplifying to a single commodity, and will return Nothing if this is not possible.
maCommodities :: MixedAmount -> Set CommoditySymbol #
Get this mixed amount's commodities as a set. Returns an empty set if there are no amounts.
amountsRaw :: MixedAmount -> [Amount] #
Get a mixed amount's component amounts without normalising zero and missing amounts. This is used for JSON serialisation, so the order is important. In particular, we want the Amounts given in the order of the MixedAmountKeys, i.e. lexicographically first by commodity, then by price commodity, then by unit price from most negative to most positive.
amountsPreservingZeros :: MixedAmount -> [Amount] #
Get a mixed amount's component amounts, with some cleanups.
This is a new version of amounts, with updated descriptions
and optimised for print to show commodityful zeros.
- If it contains the "missing amount" marker, only that is returned (discarding any additional amounts).
- Or if it contains any non-zero amounts, only those are returned (discarding any zeroes).
- Or if it contains any zero amounts (possibly more than one, possibly in different commodities), all of those are returned.
- Otherwise the null amount is returned.
amounts :: MixedAmount -> [Amount] #
Get a mixed amount's component amounts, with some cleanups. The following descriptions are old and possibly wrong:
- amounts in the same commodity are combined unless they have different prices or total prices
- multiple zero amounts, all with the same non-null commodity, are replaced by just the last of them, preserving the commodity and amount style (all but the last zero amount are discarded)
- multiple zero amounts with multiple commodities, or no commodities, are replaced by one commodity-less zero amount
- an empty amount list is replaced by one commodity-less zero amount
- the special "missing" mixed amount remains unchanged
maIsNonZero :: MixedAmount -> Bool #
Is this mixed amount non-zero, ignoring its display precision?
A convenient alias for not . mixedAmountIsZero.
maIsZero :: MixedAmount -> Bool #
Is this mixed amount exactly zero, ignoring its display precision?
A convenient alias for mixedAmountIsZero.
mixedAmountIsZero :: MixedAmount -> Bool #
Is this mixed amount exactly zero, ignoring its display precision? See amountIsZero.
mixedAmountLooksZero :: MixedAmount -> Bool #
Does this mixed amount appear to be zero when rendered with its display precision? See amountLooksZero.
isNegativeMixedAmount :: MixedAmount -> Maybe Bool #
Is this mixed amount negative, if we can tell that unambiguously? Ie when normalised, are all individual commodity amounts negative ?
averageMixedAmounts :: [MixedAmount] -> MixedAmount #
Calculate the average of some mixed amounts.
multiplyMixedAmount :: Quantity -> MixedAmount -> MixedAmount #
Multiply a mixed amount's quantities (and total prices, if any) by a constant.
divideMixedAmount :: Quantity -> MixedAmount -> MixedAmount #
Divide a mixed amount's quantities (and total prices, if any) by a constant.
maSum :: Foldable t => t MixedAmount -> MixedAmount #
Sum a collection of MixedAmounts. Amounts with different costs are kept separate.
maMinus :: MixedAmount -> MixedAmount -> MixedAmount #
Subtract a MixedAmount from another. Amounts with different costs are kept separate.
maPlus :: MixedAmount -> MixedAmount -> MixedAmount #
Sum two MixedAmount, keeping the cost of the first if any. Amounts with different costs are kept separate (since 2021).
maNegate :: MixedAmount -> MixedAmount #
Negate mixed amount's quantities (and total prices, if any).
maAddAmounts :: Foldable t => MixedAmount -> t Amount -> MixedAmount #
Add a collection of Amounts to a MixedAmount, normalising the result. Amounts with different costs are kept separate.
maAddAmount :: MixedAmount -> Amount -> MixedAmount #
Add an Amount to a MixedAmount, normalising the result. Amounts with different costs are kept separate.
mixedAmount :: Amount -> MixedAmount #
Create a MixedAmount from a single Amount.
mixed :: Foldable t => t Amount -> MixedAmount #
Convert amounts in various commodities into a mixed amount.
isMissingMixedAmount :: MixedAmount -> Bool #
Does this MixedAmount include the "missing amount" marker ? Note: currently does not test for equality with missingmixedamt, instead it looks for missingamt among the Amounts. missingamt should always be alone, but detect it even if not.
missingmixedamt :: MixedAmount #
A special mixed amount used as a marker, meaning "no explicit amount provided here, infer it when needed".
The empty mixed amount.
showAmountDebug :: Amount -> String #
Get a string representation of an amount for debugging, appropriate to the current debug level. 9 shows maximum detail.
showAmountWithZeroCommodity :: Amount -> String #
Like showAmount, but show a zero amount's commodity if it has one.
showAmountWithZeroCommodity = wbUnpack . showAmountB noColour{displayZeryCommodity=True}showAmountWithoutPrice :: Amount -> String #
Get the string representation of an amount, without any @ price.
showAmountWithoutPrice = wbUnpack . showAmountB noPrice
cshowAmount :: Amount -> String #
Colour version. For a negative amount, adds ANSI codes to change the colour, currently to hard-coded red.
cshowAmount = wbUnpack . showAmountB def{displayColour=True}showAmountB :: AmountDisplayOpts -> Amount -> WideBuilder #
General function to generate a WideBuilder for an Amount, according the supplied AmountDisplayOpts. This is the main function to use for showing Amounts, constructing a builder; it can then be converted to a Text with wbToText, or to a String with wbUnpack. Some special cases:
- The special "missing" amount is displayed as the empty string.
- If an amount is showing digit group separators but no decimal places, we force showing a decimal mark (with nothing after it) to make it easier to parse correctly.
showAmount :: Amount -> String #
Get the string representation of an amount, based on its commodity's display settings. String representations equivalent to zero are converted to just "0". The special "missing" amount is displayed as the empty string.
showAmount = wbUnpack . showAmountB noColour
showAmountPrice :: Amount -> WideBuilder #
amountStripPrices :: Amount -> Amount #
Strip all prices from an Amount
withDecimalPoint :: Amount -> Maybe Char -> Amount #
Set (or clear) an amount's display decimal point, flipped.
setAmountDecimalPoint :: Maybe Char -> Amount -> Amount #
Set (or clear) an amount's display decimal point.
amountUnstyled :: Amount -> Amount #
Reset this amount's display style to the default.
Default amount style
amountStylesSetRounding :: Rounding -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle #
amountStyleSetRounding :: Rounding -> AmountStyle -> AmountStyle #
Set this amount style's rounding strategy when being applied to amounts.
amountSetStyles :: Map CommoditySymbol AmountStyle -> Amount -> Amount #
styleAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount #
canonicaliseAmount :: Map CommoditySymbol AmountStyle -> Amount -> Amount #
withInternalPrecision :: Amount -> Word8 -> Amount #
setAmountInternalPrecision with arguments flipped.
setAmountInternalPrecision :: Word8 -> Amount -> Amount #
Set an amount's internal decimal precision as well as its display precision. This rounds or pads its Decimal quantity to the specified number of decimal places. Rounding is done with Data.Decimal's default roundTo function: "If the value ends in 5 then it is rounded to the nearest even value (Banker's Rounding)".
amountDisplayPrecision :: Amount -> Word8 #
How many decimal digits will be displayed for this amount ?
amountInternalPrecision :: Amount -> Word8 #
How many internal decimal digits are stored for this amount ?
defaultMaxPrecision :: Word8 #
The fallback display precision used when showing amounts representing an infinite decimal.
amountSetFullPrecisionOr :: Maybe Word8 -> Amount -> Amount #
We often want to display "infinite decimal" amounts rounded to some readable number of digits, while still displaying amounts with a large "non infinite" number of decimal digits (eg, 100 or 200 digits) in full. This helper is like amountSetFullPrecision, but with some refinements: 1. If the internal precision is the maximum (255), indicating an infinite decimal, the display precision is set to a smaller hard-coded default (8). 2. A maximum display precision can be specified, setting a hard upper limit. This function always sets an explicit display precision (ie, Precision n).
amountSetFullPrecision :: Amount -> Amount #
Increase an amount's display precision, if needed, to enough decimal places to show it exactly (showing all significant decimal digits, without trailing zeros). If the amount's display precision is unset, it will be treated as precision 0.
amountSetPrecisionMax :: Word8 -> Amount -> Amount #
Ensure an amount's display precision is at most the given maximum precision. Always sets an explicit Precision.
amountSetPrecisionMin :: Word8 -> Amount -> Amount #
Ensure an amount's display precision is at least the given minimum precision. Always sets an explicit Precision.
amountSetPrecision :: AmountPrecision -> Amount -> Amount #
Set an amount's display precision.
withPrecision :: Amount -> AmountPrecision -> Amount #
Set an amount's display precision, flipped.
amountIsZero :: Amount -> Bool #
Is this Amount (and its total price, if it has one) exactly zero, ignoring its display precision ?
amountLooksZero :: Amount -> Bool #
Do this Amount and (and its total price, if it has one) appear to be zero when rendered with its display precision ? The display precision should usually have a specific value here; if unset, it will be treated like NaturalPrecision.
isNegativeAmount :: Amount -> Bool #
Is this amount negative ? The price is ignored.
invertAmount :: Amount -> Amount #
Invert an amount (replace its quantity q with 1/q). (Its cost if any is not changed, currently.)
multiplyAmount :: Quantity -> Amount -> Amount #
Multiply an amount's quantity (and its total price, if it has one) by a constant.
divideAmount :: Quantity -> Amount -> Amount #
Divide an amount's quantity (and total cost, if any) by some number.
amountCost :: Amount -> Amount #
Convert a amount to its "cost" or "selling price" in another commodity, using its attached transaction price if it has one. Notes:
- price amounts must be MixedAmounts with exactly one component Amount (or there will be a runtime error XXX)
- price amounts should be positive in the Journal (though this is currently not enforced)
amountWithCommodity :: CommoditySymbol -> Amount -> Amount #
Convert an amount to the specified commodity, ignoring and discarding any assigned prices and assuming an exchange rate of 1.
gbp :: DecimalRaw Integer -> Amount #
eur :: DecimalRaw Integer -> Amount #
usd :: DecimalRaw Integer -> Amount #
missingamt :: Amount #
A special amount used as a marker, meaning "no explicit amount provided here, infer it when needed". It is nullamt with commodity symbol AUTO.
The empty simple amount - a zero with no commodity symbol or cost and the default amount display style.
csvDisplay :: AmountDisplayOpts #
Display Amount and MixedAmount in a form suitable for CSV output.
oneLine :: AmountDisplayOpts #
Display Amount and MixedAmount on one line with no prices.
noPrice :: AmountDisplayOpts #
Display Amount and MixedAmount with no prices.
noColour :: AmountDisplayOpts #
Display amounts without colour, and with various other defaults.
isNonsimpleCommodityChar :: Char -> Bool #
showCommoditySymbol :: Text -> Text #
Show space-containing commodity symbols quoted, as they are in a journal.
data AmountDisplayOpts #
Options for the display of Amount and MixedAmount. (ee also Types.AmountStyle.
Constructors
| AmountDisplayOpts | |
Fields
| |
Instances
| Show AmountDisplayOpts | |
Defined in Hledger.Data.Amount Methods showsPrec :: Int -> AmountDisplayOpts -> ShowS # show :: AmountDisplayOpts -> String # showList :: [AmountDisplayOpts] -> ShowS # | |
| Default AmountDisplayOpts | By default, display Amount and MixedAmount using |
Defined in Hledger.Data.Amount Methods | |
parseStringFormat :: Text -> Either String StringFormat #
Parse a string format specification, or return a parse error.
defaultBalanceLineFormat :: StringFormat #
Default line format for balance report: "%20(total) %2(depth_spacer)%-(account)"
data StringFormat #
A format specification/template to use when rendering a report line item as text.
A format is a sequence of components; each is either a literal string, or a hledger report item field with specified width and justification whose value will be interpolated at render time.
A component's value may be a multi-line string (or a multi-commodity amount), in which case the final string will be either single-line or a top or bottom-aligned multi-line string depending on the StringFormat variant used.
Currently this is only used in the balance command's single-column mode, which provides a limited StringFormat renderer.
Constructors
| OneLine [StringFormatComponent] | multi-line values will be rendered on one line, comma-separated |
| TopAligned [StringFormatComponent] | values will be top-aligned (and bottom-padded to the same height) |
| BottomAligned [StringFormatComponent] | values will be bottom-aligned (and top-padded) |
Instances
| Show StringFormat | |
Defined in Hledger.Data.StringFormat Methods showsPrec :: Int -> StringFormat -> ShowS # show :: StringFormat -> String # showList :: [StringFormat] -> ShowS # | |
| Default StringFormat | |
Defined in Hledger.Data.StringFormat Methods def :: StringFormat # | |
| Eq StringFormat | |
Defined in Hledger.Data.StringFormat | |
data StringFormatComponent #
Constructors
| FormatLiteral Text | Literal text to be rendered as-is |
| FormatField Bool (Maybe Int) (Maybe Int) ReportItemField | A data field to be formatted and interpolated. Parameters:
|
Instances
| Show StringFormatComponent | |
Defined in Hledger.Data.StringFormat Methods showsPrec :: Int -> StringFormatComponent -> ShowS # show :: StringFormatComponent -> String # showList :: [StringFormatComponent] -> ShowS # | |
| Eq StringFormatComponent | |
Defined in Hledger.Data.StringFormat Methods (==) :: StringFormatComponent -> StringFormatComponent -> Bool # (/=) :: StringFormatComponent -> StringFormatComponent -> Bool # | |
data ReportItemField #
An id identifying which report item field to interpolate. These are drawn from several hledger report types, so are not all applicable for a given report.
Constructors
| AccountField | A posting or balance report item's account name |
| DefaultDateField | A posting or register or entry report item's date |
| DescriptionField | A posting or register or entry report item's description |
| TotalField | A balance or posting report item's balance or running total. Always rendered right-justified. |
| DepthSpacerField | A balance report item's indent level (which may be different from the account name depth). Rendered as this number of spaces, multiplied by the minimum width spec if any. |
| FieldNo Int | A report item's nth field. May be unimplemented. |
Instances
| Show ReportItemField | |
Defined in Hledger.Data.StringFormat Methods showsPrec :: Int -> ReportItemField -> ShowS # show :: ReportItemField -> String # showList :: [ReportItemField] -> ShowS # | |
| Eq ReportItemField | |
Defined in Hledger.Data.StringFormat Methods (==) :: ReportItemField -> ReportItemField -> Bool # (/=) :: ReportItemField -> ReportItemField -> Bool # | |
beancountTopLevelAccounts :: IsString a => [a] #
accountNameToBeancount :: AccountName -> BeancountAccountName #
accountNameToAccountOnlyRegexCI :: AccountName -> Regexp #
Convert an account name to a regular expression matching it but not its subaccounts, case insensitively.
accountNameToAccountOnlyRegex :: AccountName -> Regexp #
Convert an account name to a regular expression matching it but not its subaccounts.
accountNameToAccountRegexCI :: AccountName -> Regexp #
Convert an account name to a regular expression matching it and its subaccounts, case insensitively.
accountNameToAccountRegex :: AccountName -> Regexp #
Convert an account name to a regular expression matching it and its subaccounts.
escapeName :: AccountName -> Text #
Escape an AccountName for use within a regular expression.
>>> putStr . T.unpack $ escapeName "First?!#$*?$(*) !^#*? %)*!#"
First?!#$*?$(*) !^#*? %)*!#
clipOrEllipsifyAccountName :: Maybe Int -> AccountName -> AccountName #
Keep only the first n components of an account name, where n is a positive integer. If n is Just 0, returns "...", if n is Nothing, return the full name.
clipAccountName :: Maybe Int -> AccountName -> AccountName #
Keep only the first n components of an account name, where n is a positive integer. If n is Just 0, returns the empty string, if n is Nothing, return the full name.
elideAccountName :: Int -> AccountName -> AccountName #
Elide an account name to fit in the specified width. From the ledger 2.6 news:
What Ledger now does is that if an account name is too long, it will
start abbreviating the first parts of the account name down to two
letters in length. If this results in a string that is still too
long, the front will be elided -- not the end. For example:
Expenses:Cash ; OK, not too long
Ex:Wednesday:Cash ; Expenses was abbreviated to fit
Ex:We:Afternoon:Cash ; Expenses and Wednesday abbreviated
; Expenses:Wednesday:Afternoon:Lunch:Snack:Candy:Chocolate:Cash
..:Af:Lu:Sn:Ca:Ch:Cash ; Abbreviated and elided!
accountNameTreeFrom :: [AccountName] -> Tree AccountName #
Convert a list of account names to a tree.
subAccountNamesFrom :: [AccountName] -> AccountName -> [AccountName] #
From a list of account names, select those which are direct subaccounts of the given account name.
isSubAccountNameOf :: AccountName -> AccountName -> Bool #
isAccountNamePrefixOf :: AccountName -> AccountName -> Bool #
Is the first account a parent or other ancestor of (and not the same as) the second ?
parentAccountNames :: AccountName -> [AccountName] #
topAccountNames :: [AccountName] -> [AccountName] #
- "a:b:c","d:e"
- -> ["a","d"]
expandAccountName :: AccountName -> [AccountName] #
"a:b:c" -> ["a","a:b","a:b:c"]
expandAccountNames :: [AccountName] -> [AccountName] #
Sorted unique account names implied by these account names, ie these plus all their parent accounts up to the root. Eg: ["a:b:c","d:e"] -> ["a","a:b","a:b:c","d","d:e"]
accountNameDrop :: Int -> AccountName -> AccountName #
Remove some number of account name components from the front of the account name. If the special "unbudgeted" top-level account is present, it is preserved and dropping affects the rest of the account name.
accountNameApplyAliasesMemo :: [AccountAlias] -> AccountName -> Either RegexError AccountName #
Memoising version of accountNameApplyAliases, maybe overkill.
accountNameApplyAliases :: [AccountAlias] -> AccountName -> Either RegexError AccountName #
Rewrite an account name using all matching aliases from the given list, in sequence. Each alias sees the result of applying the previous aliases. Or, return any error arising from a bad regular expression in the aliases.
concatAccountNames :: [AccountName] -> AccountName #
Join account names into one. If any of them has () or [] posting type indicators, these (the first type encountered) will also be applied to the resulting account name.
joinAccountNames :: AccountName -> AccountName -> AccountName #
Prefix one account name to another, preserving posting type indicators like concatAccountNames.
unbudgetedAccountName :: Text #
A top-level account prefixed to some accounts in budget reports. Defined here so it can be ignored by accountNameDrop.
accountNameLevel :: AccountName -> Int #
accountNameInferType :: AccountName -> Maybe AccountType #
Try to guess an account's type from its name, matching common English top-level account names.
Regular expressions matching common English top-level account names, used as a fallback when account types are not declared.
accountSummarisedName :: AccountName -> Text #
Truncate all account name components but the last to two characters.
accountLeafName :: AccountName -> Text #
accountNameFromComponents :: [Text] -> AccountName #
accountNameComponents :: AccountName -> [Text] #
acctsepchar :: Char #
tests_Dates :: TestTree #
An exact datespan of zero length, that matches no date.
periodexprp :: forall (m :: Type -> Type). Day -> TextParser m (Interval, DateSpan) #
Parse a period expression, specifying a date span and optionally a reporting interval. Requires a reference "today" date for resolving any relative start/end dates (only; it is not needed for parsing the reporting interval).
>>>let p = parsePeriodExpr (fromGregorian 2008 11 26)>>>p "from Aug to Oct"Right (NoInterval,DateSpan 2008-08-01..2008-09-30)>>>p "aug to oct"Right (NoInterval,DateSpan 2008-08-01..2008-09-30)>>>p "2009q2"Right (NoInterval,DateSpan 2009Q2)>>>p "Q3"Right (NoInterval,DateSpan 2008Q3)>>>p "every 3 days in Aug"Right (Days 3,DateSpan 2008-08)>>>p "daily from aug"Right (Days 1,DateSpan 2008-08-01..)>>>p "every week to 2009"Right (Weeks 1,DateSpan ..2008-12-31)>>>p "every 2nd day of month"Right (DayOfMonth 2,DateSpan ..)>>>p "every 2nd day"Right (DayOfMonth 2,DateSpan ..)>>>p "every 2nd day 2009.."Right (DayOfMonth 2,DateSpan 2009-01-01..)>>>p "every 2nd day 2009-"Right (DayOfMonth 2,DateSpan 2009-01-01..)>>>p "every 29th Nov"Right (DayOfYear 11 29,DateSpan ..)>>>p "every 29th nov ..2009"Right (DayOfYear 11 29,DateSpan ..2008-12-31)>>>p "every nov 29th"Right (DayOfYear 11 29,DateSpan ..)>>>p "every Nov 29th 2009.."Right (DayOfYear 11 29,DateSpan 2009-01-01..)>>>p "every 11/29 from 2009"Right (DayOfYear 11 29,DateSpan 2009-01-01..)>>>p "every 11/29 since 2009"Right (DayOfYear 11 29,DateSpan 2009-01-01..)>>>p "every 2nd Thursday of month to 2009"Right (WeekdayOfMonth 2 4,DateSpan ..2008-12-31)>>>p "every 1st monday of month to 2009"Right (WeekdayOfMonth 1 1,DateSpan ..2008-12-31)>>>p "every tue"Right (DaysOfWeek [2],DateSpan ..)>>>p "every 2nd day of week"Right (DaysOfWeek [2],DateSpan ..)>>>p "every 2nd day of month"Right (DayOfMonth 2,DateSpan ..)>>>p "every 2nd day"Right (DayOfMonth 2,DateSpan ..)>>>p "every 2nd day 2009.."Right (DayOfMonth 2,DateSpan 2009-01-01..)>>>p "every 2nd day of month 2009.."Right (DayOfMonth 2,DateSpan 2009-01-01..)
yearp :: forall (m :: Type -> Type). TextParser m Integer #
Parse a year number from a Text, making sure that at least four digits are used.
isDateSepChar :: Char -> Bool #
datesepchar :: forall (m :: Type -> Type). TextParser m Char #
datesepchars :: String #
smartdate :: forall (m :: Type -> Type). TextParser m SmartDate #
Parse a date in any of the formats allowed in Ledger's period expressions, and some others. Assumes any text in the parse stream has been lowercased. Returns a SmartDate, to be converted to a full date later (see fixSmartDate).
Examples:
2004 (start of year, which must have 4+ digits) 2004/10 (start of month, which must be 1-12) 2004/10/1 (exact date, day must be 1-31) 10/1 (month and day in current year) 21 (day in current month) october, oct (start of month in current year) yesterday, today, tomorrow (-1, 0, 1 days from today) last/this/next day/week/month/quarter/year (-1, 0, 1 periods from the current period) in n days/weeks/months/quarters/years (n periods from the current period) n days/weeks/months/quarters/years ago (-n periods from the current period) 20181201 (8 digit YYYYMMDD with valid year month and day) 201812 (6 digit YYYYMM with valid year and month)
Note malformed digit sequences might give surprising results:
201813 (6 digits with an invalid month is parsed as start of 6-digit year) 20181301 (8 digits with an invalid month is parsed as start of 8-digit year) 20181232 (8 digits with an invalid day gives an error) 201801012 (9+ digits beginning with a valid YYYYMMDD gives an error)
Eg:
YYYYMMDD is parsed as year-month-date if those parts are valid (>=4 digits, 1-12, and 1-31 respectively): >>> parsewith (smartdate <* eof) "20181201" Right (SmartCompleteDate 2018-12-01)
YYYYMM is parsed as year-month-01 if year and month are valid: >>> parsewith (smartdate <* eof) "201804" Right (SmartAssumeStart 2018 (Just 4))
With an invalid month, it's parsed as a year: >>> parsewith (smartdate <* eof) "201813" Right (SmartAssumeStart 201813 Nothing)
A 9+ digit number beginning with valid YYYYMMDD gives an error: >>> parsewith (smartdate <* eof) "201801012" Left (...)
Big numbers not beginning with a valid YYYYMMDD are parsed as a year: >>> parsewith (smartdate <* eof) "201813012" Right (SmartAssumeStart 201813012 Nothing)
parsedateM :: String -> Maybe Day #
Try to parse a couple of date string formats:
`YYYY-MM-DD`, `YYYYMMDD` or DD, with leading zeros required.
For internal use, not quite the same as the journal's "simple dates".
>>> parsedateM "20080203"
Just 2008-02-03
>>> parsedateM "20080203/"
Nothing
>>> parsedateM "20080230"
Nothing
intervalBoundaryBefore :: Interval -> Day -> Day #
fixSmartDate :: Day -> SmartDate -> EFDay #
Convert a SmartDate to a specific date using the provided reference date. This date will be exact or flexible depending on whether the day was specified exactly. (Missing least-significant parts produces a flex date.)
Examples:
>>>:set -XOverloadedStrings>>>let t = fixSmartDateStr (fromGregorian 2008 11 26)>>>t "0000-01-01""0000-01-01">>>t "1999-12-02""1999-12-02">>>t "1999.12.02""1999-12-02">>>t "1999/3/2""1999-03-02">>>t "19990302""1999-03-02">>>t "2008/2""2008-02-01">>>t "0020/2""0020-02-01">>>t "1000""1000-01-01">>>t "4/2""2008-04-02">>>t "2""2008-11-02">>>t "January""2008-01-01">>>t "feb""2008-02-01">>>t "today""2008-11-26">>>t "yesterday""2008-11-25">>>t "tomorrow""2008-11-27">>>t "this day""2008-11-26">>>t "last day""2008-11-25">>>t "next day""2008-11-27">>>t "this week" -- last monday"2008-11-24">>>t "last week" -- previous monday"2008-11-17">>>t "next week" -- next monday"2008-12-01">>>t "this month""2008-11-01">>>t "last month""2008-10-01">>>t "next month""2008-12-01">>>t "this quarter""2008-10-01">>>t "last quarter""2008-07-01">>>t "next quarter""2009-01-01">>>t "this year""2008-01-01">>>t "last year""2007-01-01">>>t "next year""2009-01-01"
t "last wed" "2008-11-19" t "next friday" "2008-11-28" t "next january" "2009-01-01"
>>>t "in 5 days""2008-12-01">>>t "in 7 months""2009-06-01">>>t "in -2 weeks""2008-11-10">>>t "1 quarter ago""2008-07-01">>>t "1 week ahead""2008-12-01"
fixSmartDateStrEither' :: Day -> Text -> Either HledgerParseErrors EFDay #
fixSmartDateStrEither :: Day -> Text -> Either HledgerParseErrors Text #
A safe version of fixSmartDateStr.
fixSmartDateStr :: Day -> Text -> Text #
Convert a smart date string to an explicit yyyy/mm/dd string using the provided reference date, or raise an error.
parsePeriodExpr' :: Day -> Text -> (Interval, DateSpan) #
Like parsePeriodExpr, but call error' on failure.
parsePeriodExpr :: Day -> Text -> Either HledgerParseErrors (Interval, DateSpan) #
Parse a period expression to an Interval and overall DateSpan using the provided reference date, or return a parse error.
latestSpanContaining :: [DateSpan] -> Day -> Maybe DateSpan #
Select the DateSpan containing a given Day, if any, from a given list of DateSpans.
If the DateSpans are non-overlapping, this returns the unique containing DateSpan, if it exists. If the DateSpans are overlapping, it will return the containing DateSpan with the latest start date, and then latest end date.
daysSpan :: [Day] -> DateSpan #
Calculate the minimal DateSpan containing all of the given Days (in the usual exclusive-end-date sense: beginning on the earliest, and ending on the day after the latest).
spansUnion :: [DateSpan] -> DateSpan #
Calculate the union of a number of datespans.
spanDefaultsFrom :: DateSpan -> DateSpan -> DateSpan #
Fill any unspecified dates in the first span with the dates from the second one. Sort of a one-way spanIntersect.
spanIntersect :: DateSpan -> DateSpan -> DateSpan #
Calculate the intersection of two datespans.
For non-intersecting spans, gives an empty span beginning on the second's start date:
>>> DateSpan (Just $ Flex $ fromGregorian 2018 01 01) (Just $ Flex $ fromGregorian 2018 01 03) spanIntersect DateSpan (Just $ Flex $ fromGregorian 2018 01 03) (Just $ Flex $ fromGregorian 2018 01 05)
DateSpan 2018-01-03..2018-01-02
spansIntersect :: [DateSpan] -> DateSpan #
Calculate the intersection of a number of datespans.
groupByDateSpan :: Bool -> (a -> Day) -> [DateSpan] -> [a] -> [(DateSpan, [a])] #
Group elements based on where they fall in a list of DateSpans without
gaps. The precondition is not checked.
periodContainsDate :: Period -> Day -> Bool #
Does the period include the given date ? (Here to avoid import cycle).
spanContainsDate :: DateSpan -> Day -> Bool #
Does the span include the given date ?
daysInSpan :: DateSpan -> Maybe Integer #
Count the days in a DateSpan, or if it is open-ended return Nothing.
spansFromBoundaries :: Day -> [Day] -> [DateSpan] #
Construct a list of exact DateSpans from a list of boundaries, which fit within a given range.
splitSpan :: Bool -> Interval -> DateSpan -> [DateSpan] #
Split a DateSpan into consecutive exact spans of the specified Interval. If the first argument is true and the interval is Weeks, Months, Quarters or Years, the start date will be adjusted backward if needed to nearest natural interval boundary (a monday, first of month, first of quarter or first of year). If no interval is specified, the original span is returned. If the original span is the null date span, ie unbounded, the null date span is returned. If the original span is empty, eg if the end date is <= the start date, no spans are returned.
Examples:
>>>let t i y1 m1 d1 y2 m2 d2 = splitSpan True i $ DateSpan (Just $ Flex $ fromGregorian y1 m1 d1) (Just $ Flex $ fromGregorian y2 m2 d2)>>>t NoInterval 2008 01 01 2009 01 01[DateSpan 2008]>>>t (Quarters 1) 2008 01 01 2009 01 01[DateSpan 2008Q1,DateSpan 2008Q2,DateSpan 2008Q3,DateSpan 2008Q4]>>>splitSpan True (Quarters 1) nulldatespan[DateSpan ..]>>>t (Days 1) 2008 01 01 2008 01 01 -- an empty datespan[]>>>t (Quarters 1) 2008 01 01 2008 01 01[]>>>t (Months 1) 2008 01 01 2008 04 01[DateSpan 2008-01,DateSpan 2008-02,DateSpan 2008-03]>>>t (Months 2) 2008 01 01 2008 04 01[DateSpan 2008-01-01..2008-02-29,DateSpan 2008-03-01..2008-04-30]>>>t (Weeks 1) 2008 01 01 2008 01 15[DateSpan 2007-12-31W01,DateSpan 2008-01-07W02,DateSpan 2008-01-14W03]>>>t (Weeks 2) 2008 01 01 2008 01 15[DateSpan 2007-12-31..2008-01-13,DateSpan 2008-01-14..2008-01-27]>>>t (DayOfMonth 2) 2008 01 01 2008 04 01[DateSpan 2007-12-02..2008-01-01,DateSpan 2008-01-02..2008-02-01,DateSpan 2008-02-02..2008-03-01,DateSpan 2008-03-02..2008-04-01]>>>t (WeekdayOfMonth 2 4) 2011 01 01 2011 02 15[DateSpan 2010-12-09..2011-01-12,DateSpan 2011-01-13..2011-02-09,DateSpan 2011-02-10..2011-03-09]>>>t (DaysOfWeek [2]) 2011 01 01 2011 01 15[DateSpan 2010-12-28..2011-01-03,DateSpan 2011-01-04..2011-01-10,DateSpan 2011-01-11..2011-01-17]>>>t (DayOfYear 11 29) 2011 10 01 2011 10 15[DateSpan 2010-11-29..2011-11-28]>>>t (DayOfYear 11 29) 2011 12 01 2012 12 15[DateSpan 2011-11-29..2012-11-28,DateSpan 2012-11-29..2013-11-28]
spansSpan :: [DateSpan] -> DateSpan #
Get overall span enclosing multiple sequentially ordered spans. The start and end date will be exact or flexible depending on the first span's start date and last span's end date.
spanEndYear :: DateSpan -> Maybe Year #
spanStartYear :: DateSpan -> Maybe Year #
elapsedSeconds :: Fractional a => UTCTime -> UTCTime -> a #
getCurrentYear :: IO Integer #
Get the current local year.
getCurrentMonth :: IO Int #
Get the current local month number.
getCurrentDay :: IO Day #
Get the current local date.
showDateSpanMonthAbbrev :: DateSpan -> Text #
Like showDateSpan, but show month spans as just the abbreviated month name in the current locale.
showDateSpanDebug :: DateSpan -> String #
Show a DateSpan with its begin/end dates, exact or flex.
showDateSpan :: DateSpan -> Text #
Render a datespan as a display string, abbreviating into a compact form if possible. Warning, hides whether dates are Exact or Flex.
showEFDate :: EFDay -> Text #
posintopt :: String -> RawOpts -> Int #
Reads the named option's natural-number argument. If not present it will return 0. An argument that is negative or too large will raise an error.
intopt :: String -> RawOpts -> Int #
Reads the named option's Int argument. If not present it will return 0. An argument that is too small or too large will raise an error.
maybeposintopt :: String -> RawOpts -> Maybe Int #
Reads the named option's natural-number argument, if it is present. An argument that is negative or too large will raise an error.
maybeintopt :: String -> RawOpts -> Maybe Int #
Reads the named option's Int argument, if it is present. An argument that is too small or too large will raise an error.
listofstringopt :: String -> RawOpts -> [String] #
collectopts :: ((String, String) -> Maybe a) -> RawOpts -> [a] #
Collects processed and filtered list of options preserving their order
>>>collectopts (const Nothing) (RawOpts [("x","")])[]>>>collectopts Just (RawOpts [("a",""),("b","")])[("a",""),("b","")]
Arguments
| :: (String -> Maybe a) | "parser" that returns |
| -> RawOpts | actual options where to look for flag |
| -> Maybe a | exclusive choice among those returned as |
From a list of RawOpts, get the last one (ie the right-most on the command line) for which the given predicate returns a Just value. Useful for exclusive choice flags like --daily|--weekly|--quarterly...
>>>import Safe (readMay)>>>choiceopt Just (RawOpts [("a",""), ("b",""), ("c","")])Just "c">>>choiceopt (const Nothing) (RawOpts [("a","")])Nothing>>>choiceopt readMay (RawOpts [("LT",""),("EQ",""),("Neither","")]) :: Maybe OrderingJust EQ
toggleopt :: String -> RawOpts -> Bool #
Like boolopt, except if the flag is repeated on the command line it toggles the value. An even number of repetitions is equivalent to none.
unsetboolopt :: String -> RawOpts -> RawOpts #
setboolopt :: String -> RawOpts -> RawOpts #
The result of running cmdargs: an association list of option names to string values.
tests_Utils :: TestTree #
makeHledgerClassyLenses :: Name -> DecsQ #
Make classy lenses for Hledger options fields. This is intended to be used with BalancingOpts, InputOpt, ReportOpts, ReportSpec, and CliOpts. When run on X, it will create a typeclass named HasX (except for ReportOpts, which will be named HasReportOptsNoUpdate) containing all the lenses for that type. If the field name starts with an underscore, the lens name will be created by stripping the underscore from the front on the name. If the field name ends with an underscore, the field name ends with an underscore, the lens name will be mostly created by stripping the underscore, but a few names for which this would create too many conflicts instead have a second underscore appended. ReportOpts fields for which updating them requires updating the query in ReportSpec are instead names by dropping the trailing underscore and appending NoUpdate to the name, e.g. querystring_ -> querystringNoUpdate.
There are a few reasons for the complicated rules. - We have some legacy field names ending in an underscore (e.g. value_) which we want to temporarily accommodate, before eventually switching to a more modern style (e.g. _rsReportOpts) - Certain fields in ReportOpts need to update the enclosing ReportSpec when they are updated, and it is a common programming error to forget to do this. We append NoUpdate to those lenses which will not update the enclosing field, and reserve the shorter name for manually define lenses (or at least something lens-like) which will update the ReportSpec. cf. the lengthy discussion here and in surrounding comments: https://github.com/simonmichael/hledger/pull/1545#issuecomment-881974554
numDigitsInteger :: Integer -> Int #
Find the number of digits of an Integer. The integer should not have more digits than an Int can count. This is probably inefficient.
numDigitsInt :: Integral a => Int -> a #
Find the number of digits of an Int.
multicol :: Int -> [String] -> String #
Convert a list of strings to a multi-line multi-column list fitting within the given width. Not wide character aware.
treeLeaves :: Tree a -> [a] #
Get the leaves of this tree as a list. The topmost node ("root" in hledger account trees) is not counted as a leaf.
splitAtElement :: Eq a => a -> [a] -> [[a]] #
minimumStrict :: Ord a => [a] -> a #
Strict version of minimum that doesn’t leak space
maximumStrict :: Ord a => [a] -> a #
Strict version of maximum that doesn’t leak space
maximum' :: Integral a => [a] -> a #
Total version of maximum, for integral types, giving 0 for an empty list.
sequence' :: Monad f => [f a] -> f [a] #
This is a version of sequence based on difference lists. It is slightly faster but we mostly use it because it uses the heap instead of the stack. This has the advantage that Neil Mitchell’s trick of limiting the stack size to discover space leaks doesn’t show this as a false positive.
applyN :: Int -> (a -> a) -> a -> a #
Apply a function the specified number of times, which should be > 0 (otherwise does nothing). Possibly uses O(n) stack ?
stripAnsi :: String -> String #
Strip ANSI escape sequences from a string.
>>>stripAnsi "\ESC[31m-1\ESC[m""-1"
Alias for realLength.
strWidthAnsi :: String -> Int #
Like strWidth, but also strips ANSI escape sequences before calculating the width.
This is no longer used in code, as widths are calculated before adding ANSI escape sequences, but is being kept around for now.
takeWidth :: Int -> String -> String #
Double-width-character-aware string truncation. Take as many characters as possible from a string without exceeding the specified width. Eg takeWidth 3 "りんご" = "り".
unwords' :: [String] -> String #
Quote-aware version of unwords - single-quote strings which contain whitespace
words' :: String -> [String] #
Quote-aware version of words - don't split on spaces which are inside quotes.
NB correctly handles "a'b" but not "'a'". Can raise an error if parsing fails.
quoteForCommandLine :: String -> String #
Try to single- and backslash-quote a string as needed to make it usable as an argument on a (sh/bash) shell command line. At least, well enough to handle common currency symbols, like $. Probably broken in many ways.
>>>quoteForCommandLine "a""a">>>quoteForCommandLine "\"""'\"'">>>quoteForCommandLine "$""'\\$'"
singleQuoteIfNeeded :: String -> String #
Single-quote this string if it contains whitespace or double-quotes. Does not work for strings containing single quotes.
quoteIfNeeded :: String -> String #
Double-quote this string if it contains whitespace, single quotes or double-quotes, escaping the quotes as needed.
formatString :: Bool -> Maybe Int -> Maybe Int -> String -> String #
Clip and pad a string to a minimum & maximum width, andor leftright justify it. Works on multi-line strings too (but will rewrite non-unix line endings).
elideRight :: Int -> String -> String #
stripbrackets :: String -> String #
singleline :: String -> String #
Remove consecutive line breaks, replacing them with single space
Remove all trailing newline/carriage returns, leaving just one trailing newline.
strip1By :: (Char -> Bool) -> String -> String #
Strip a single balanced enclosing pair of a character matching the predicate from the start and end of a string.
stripBy :: (Char -> Bool) -> String -> String #
Strip a run of zero or more characters matching the predicate from the start and end of a string.
strip1Char :: Char -> Char -> String -> String #
Strip the given starting and ending character from the start and end of a string if both are present.
capitalise :: String -> String #
eolof :: forall (m :: Type -> Type). TextParser m () #
skipNonNewlineSpaces' :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m Bool #
skipNonNewlineSpaces1 :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m () #
skipNonNewlineSpaces :: forall s (m :: Type -> Type). (Stream s, Token s ~ Char) => ParsecT HledgerParseErrorData s m () #
restofline :: forall (m :: Type -> Type). TextParser m String #
spacenonewline :: forall s (m :: Type -> Type). (Stream s, Char ~ Token s) => ParsecT HledgerParseErrorData s m Char #
isNonNewlineSpace :: Char -> Bool #
showDateParseError :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> String #
parseerror :: (Show t, Show (Token t), Show e) => ParseErrorBundle t e -> a #
parseWithState' :: Stream s => st -> StateT st (ParsecT e s Identity) a -> s -> Either (ParseErrorBundle s e) a #
parseWithState :: Monad m => st -> StateT st (ParsecT HledgerParseErrorData Text m) a -> Text -> m (Either HledgerParseErrors a) #
Run a stateful parser with some initial state on a text. See also: runTextParser, runJournalParser.
parsewithString :: Parsec e String a -> String -> Either (ParseErrorBundle String e) a #
rtp :: TextParser Identity a -> Text -> Either HledgerParseErrors a #
Run a text parser in the identity monad. See also: parseWithState.
runTextParser :: TextParser Identity a -> Text -> Either HledgerParseErrors a #
Run a text parser in the identity monad. See also: parseWithState.
surroundedBy :: Applicative m => m openclose -> m a -> m a #
choiceInState :: forall s (m :: Type -> Type) a. [StateT s (ParsecT HledgerParseErrorData Text m) a] -> StateT s (ParsecT HledgerParseErrorData Text m) a #
Backtracking choice, use this when alternatives share a prefix. Consumes no input if all choices fail.
choice' :: forall (m :: Type -> Type) a. [TextParser m a] -> TextParser m a #
Backtracking choice, use this when alternatives share a prefix. Consumes no input if all choices fail.
sourcePosPairPretty :: (SourcePos, SourcePos) -> String #
Render a pair of source positions in human-readable form, only displaying the range of lines.
dbgparse :: forall (m :: Type -> Type). Int -> String -> TextParser m () #
Trace to stderr or log to debug log the provided label (if non-null) and current parser state (position and next input), if the global debug level is at or above the specified level. Uses unsafePerformIO.
traceOrLogParse :: forall (m :: Type -> Type). String -> TextParser m () #
Trace to stderr or log to debug log the provided label (if non-null) and current parser state (position and next input). See also: Hledger.Utils.Debug, megaparsec's dbg. Uses unsafePerformIO. XXX Can be hard to make this evaluate.
type SimpleStringParser a = Parsec HledgerParseErrorData String a #
A parser of string to some type.
type SimpleTextParser = Parsec HledgerParseErrorData Text #
A parser of strict text to some type.
type TextParser (m :: Type -> Type) a = ParsecT HledgerParseErrorData Text m a #
A parser of text that runs in some monad.
lbl_ :: String -> String -> String -> String #
Helper for producing debug messages: concatenates a name (eg a function name), short description of the value being logged, and string representation of the value.
dbg1 :: Show a => String -> a -> a #
Pretty-trace to stderr (or log to debug log) a label and showable value if the --debug level is high enough, then return the value. Uses unsafePerformIO.
dbg0 :: Show a => String -> a -> a #
Pretty-trace to stderr (or log to debug log) a label and showable value, then return it.
traceOrLogAtWith :: Int -> (a -> String) -> a -> a #
ptraceOrLogAt :: Show a => Int -> String -> a -> a #
traceOrLogAt :: Int -> String -> a -> a #
traceOrLog :: String -> a -> a #
ptraceLogAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m () #
Like ptraceAt, but convenient to insert in an IO monad and enforces monadic sequencing.
ptraceLogAt :: Show a => Int -> String -> a -> a #
Pretty-log a label and showable value to the debug log, if the global debug level is at or above the specified level. At level 0, always prints. Otherwise, uses unsafePerformIO.
traceLogAtWith :: Int -> (a -> String) -> a -> a #
Log a string to the debug log before returning the second argument, if the global debug level is at or above the specified level. At level 0, always logs. Otherwise, uses unsafePerformIO.
traceLogWith :: (a -> String) -> a -> a #
Log a value to the debug log with the given show function before returning it.
traceLogAtIO :: MonadIO m => Int -> String -> m () #
Like traceLogAt, but convenient to use in IO.
traceLogIO :: MonadIO m => String -> m () #
Like traceLog but sequences properly in IO.
traceLogAt :: Int -> String -> a -> a #
Log a string to the debug log before returning the second argument, if the global debug level is at or above the specified level. At level 0, always logs. Otherwise, uses unsafePerformIO.
traceLog :: String -> a -> a #
Log a string to the debug log before returning the second argument. Uses unsafePerformIO.
ptraceAtIO :: (MonadIO m, Show a) => Int -> String -> a -> m () #
Like ptraceAt, but convenient to insert in an IO monad and enforces monadic sequencing.
ptraceAt :: Show a => Int -> String -> a -> a #
Pretty-print a label and a showable value to the console if the global debug level is at or above the specified level. At level 0, always prints. Otherwise, uses unsafePerformIO.
traceAtWith :: Int -> (a -> String) -> a -> a #
Trace (print to stderr) a showable value using a custom show function, if the global debug level is at or above the specified level. At level 0, always prints. Otherwise, uses unsafePerformIO.
traceAt :: Int -> String -> a -> a #
Trace (print to stderr) a string if the global debug level is at or above the specified level. At level 0, always prints. Otherwise, uses unsafePerformIO.
Pretty-trace a showable value before returning it. Like Debug.Trace.traceShowId, but pretty-printing and easier to type.
traceWith :: (a -> String) -> a -> a #
Trace a value with the given show function before returning it.
debugLevel :: Int #
The programs debug output verbosity. The default is 0 meaning no debug output.
The --debug command line flag sets it to 1, or --debug=N sets it to
a higher value (the = is required). Uses unsafePerformIO.
When running in GHCI, changing this requires reloading this module.
assertParseErrorE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> String -> Assertion #
assertParseEqE :: (Default st, Eq a, Show a, HasCallStack) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> a -> Assertion #
assertParseE :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO)) a -> Text -> Assertion #
assertParseStateOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (st -> b) -> b -> Assertion #
Run a stateful parser in IO like assertParse, then assert that the final state (the wrapped state, not megaparsec's internal state), transformed by the given function, matches the given expected value.
assertParseError :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> String -> Assertion #
Assert that this stateful parser runnable in IO fails to parse the given input text, with a parse error containing the given string.
assertParseEqOn :: (HasCallStack, Eq b, Show b, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> (a -> b) -> b -> Assertion #
Like assertParseEq, but transform the parse result with the given function before comparing it.
assertParseEq :: (HasCallStack, Eq a, Show a, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> a -> Assertion #
Assert a parser produces an expected value.
assertParse :: (HasCallStack, Default st) => StateT st (ParsecT HledgerParseErrorData Text IO) a -> Text -> Assertion #
Assert that this stateful parser runnable in IO successfully parses all of the given input text, showing the parse error if it fails. Suitable for hledger's JournalParser parsers.
assertRight :: (HasCallStack, Eq a, Show a) => Either a b -> Assertion #
Assert any Right value.
assertLeft :: (HasCallStack, Eq b, Show b) => Either a b -> Assertion #
Assert any Left value.
embedFileRelative :: FilePath -> Q Exp #
Like embedFile, but takes a path relative to the package directory.
readHandlePortably :: Handle -> IO Text #
readFileOrStdinPortably :: String -> IO Text #
Like readFilePortably, but read from standard input if the path is "-".
readFilePortably :: FilePath -> IO Text #
Read text from a file, converting any rn line endings to n,, using the system locale's text encoding, ignoring any utf8 BOM prefix (as seen in paypal's 2018 CSV, eg) if that encoding is utf8.
readFileStrictly :: FilePath -> IO Text #
Like readFilePortably, but read all of the file before proceeding.
sortByModTime :: [FilePath] -> IO [FilePath] #
Given a list of existing file paths, sort them by modification time, most recent first.
expandGlob :: FilePath -> FilePath -> IO [FilePath] #
Like expandPath, but treats the expanded path as a glob, and returns zero or more matched absolute file paths, alphabetically sorted.
expandPath :: FilePath -> FilePath -> IO FilePath #
Given a current directory, convert a possibly relative, possibly tilde-containing file path to an absolute one. ~username is not supported. Leaves "-" unchanged. Can raise an error.
expandHomePath :: FilePath -> IO FilePath #
Expand a tilde (representing home directory) at the start of a file path. ~username is not supported. Can raise an error.
usageError :: String -> a #
A version of errorWithoutStackTrace that adds a usage hint.
terminalFgColor :: Maybe (RGB Float) #
Detect the terminal's current foreground colour, if possible, using unsafePerformIO.
terminalBgColor :: Maybe (RGB Float) #
Detect the terminal's current background colour, if possible, using unsafePerformIO.
terminalLightness :: Maybe Float #
Detect the terminal's current background lightness (0..1), if possible, using unsafePerformIO. If the terminal is transparent, its apparent lightness may be different.
terminalIsLight :: Maybe Bool #
Detect whether the terminal currently has a light background colour, if possible, using unsafePerformIO. If the terminal is transparent, its apparent light/darkness may be different.
bgColorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder #
Wrap a WideBuilder in ANSI codes to set and reset background colour.
colorB :: ColorIntensity -> Color -> WideBuilder -> WideBuilder #
Wrap a WideBuilder in ANSI codes to set and reset foreground colour.
bgColor :: ColorIntensity -> Color -> String -> String #
Wrap a string in ANSI codes to set and reset background colour.
color :: ColorIntensity -> Color -> String -> String #
Wrap a string in ANSI codes to set and reset foreground colour.
ColorIntensity is Dull or Vivid (ie normal and bold).
Color is one of Black, Red, Green, Yellow, Blue, Magenta, Cyan, White.
Eg: color Dull Red "text".
Like useColorOnStdout, but checks for ANSI color support on stderr, and is not affected by -o/--output-file.
Check the IO environment to see if ANSI colour codes should be used on stdout. This is done using unsafePerformIO so it can be used anywhere, eg in low-level debug utilities, which should be ok since we are just reading. The logic is: use color if the program was started with --color=yes|always or ( the program was not started with --color=no|never and a NO_COLOR environment variable is not defined and stdout supports ANSI color and -o/--output-file was not used, or its value is "-" ).
colorOption :: String #
Read the value of the --color or --colour command line option provided at program startup using unsafePerformIO. If this option was not provided, returns the empty string.
brightWhite' :: String -> String #
brightCyan' :: String -> String #
brightMagenta' :: String -> String #
brightBlue' :: String -> String #
brightYellow' :: String -> String #
brightGreen' :: String -> String #
brightRed' :: String -> String #
brightBlack' :: String -> String #
Versions of some of text-ansi's string colors/styles which are more careful to not print junk onscreen. These use our useColorOnStdout.
hasOutputFile :: Bool #
Check whether the -o/--output-file option has been used at program startup with an argument other than "-", using unsafePerformIO.
outputFileOption :: Maybe String #
Read the value of the -o/--output-file command line option provided at program startup, if any, using unsafePerformIO.
The command line arguments that were used at program startup. Uses unsafePerformIO.
setupPager :: IO () #
Make sure our $LESS and $MORE environment variables contain R,
to help ensure the common pager less will show our ANSI output properly.
less uses $LESS by default, and $MORE when it is invoked as more.
What the original more program does, I'm not sure.
If $PAGER is configured to something else, this probably will have no effect.
getTerminalWidth :: IO (Maybe Int) #
getTerminalHeight :: IO (Maybe Int) #
getTerminalHeightWidth :: IO (Maybe (Int, Int)) #
An alternative to ansi-terminal's getTerminalSize, based on the more robust-looking terminal-size package. Tries to get stdout's terminal's current height and width.
Display the given text on the terminal, using the user's $PAGER if the text is taller than the current terminal and stdout is interactive and TERM is not "dumb" (except on Windows, where a pager will not be used). If the text contains ANSI codes, because hledger thinks the current terminal supports those, the pager should be configured to display those, otherwise users will see junk on screen (#2015). We call "setLessR" at hledger startup to make that less likely.
pprint :: Show a => a -> IO () #
Pretty print a showable value. An easier alias for pretty-simple's pPrint. This will print in colour if useColorOnStderr is true.
pshow :: Show a => a -> String #
Pretty show. An easier alias for pretty-simple's pShow. This will probably show in colour if useColorOnStderr is true.
tests_Text :: TestTree #
readDecimal :: Text -> Integer #
Read a decimal number from a Text. Assumes the input consists only of digit characters.
linesPrepend2 :: Text -> Text -> Text -> Text #
Add a prefix to the first line of a string, and a different prefix to the remaining lines.
linesPrepend :: Text -> Text -> Text #
Add a prefix to each line of a string.
textTakeWidth :: Int -> Text -> Text #
Double-width-character-aware string truncation. Take as many characters as possible from a string without exceeding the specified width. Eg textTakeWidth 3 "りんご" = "り".
fitText :: Maybe Int -> Maybe Int -> Bool -> Bool -> Text -> Text #
General-purpose wide-char-aware single-line text layout function. It can left- or right-pad a short string to a minimum width. It can left- or right-clip a long string to a maximum width, optionally inserting an ellipsis (the third argument). It clips and pads on the right when the fourth argument is true, otherwise on the left. It treats wide characters as double width.
textConcatBottomPadded :: [Text] -> Text #
Join several multi-line strings as side-by-side rectangular strings of the same height, bottom-padded. Treats wide characters as double width.
textConcatTopPadded :: [Text] -> Text #
Join several multi-line strings as side-by-side rectangular strings of the same height, top-padded. Treats wide characters as double width.
textUnbracket :: Text -> Text #
Remove all matching pairs of square brackets and parentheses from the text.
stripquotes :: Text -> Text #
Strip one matching pair of single or double quotes on the ends of a string.
escapeBackslash :: Text -> Text #
escapeDoubleQuotes :: Text -> Text #
textQuoteIfNeeded :: Text -> Text #
quoteIfSpaced :: Text -> Text #
Wrap a string in double quotes, and -prefix any embedded single quotes, if it contains whitespace and is not already single- or double-quoted.
formatText :: Bool -> Maybe Int -> Maybe Int -> Text -> Text #
Clip and pad a string to a minimum & maximum width, andor leftright justify it. Works on multi-line strings too (but will rewrite non-unix line endings).
textElideRight :: Int -> Text -> Text #
textCapitalise :: Text -> Text #
wbUnpack :: WideBuilder -> String #
Convert a WideBuilder to a String.
wbFromText :: Text -> WideBuilder #
Convert a strict Text to a WideBuilder.
wbToText :: WideBuilder -> Text #
Convert a WideBuilder to a strict Text.
data WideBuilder #
Helper for constructing Builders while keeping track of text width.
Constructors
| WideBuilder | |
Instances
| Monoid WideBuilder | |
Defined in Text.WideString Methods mempty :: WideBuilder # mappend :: WideBuilder -> WideBuilder -> WideBuilder # mconcat :: [WideBuilder] -> WideBuilder # | |
| Semigroup WideBuilder | |
Defined in Text.WideString Methods (<>) :: WideBuilder -> WideBuilder -> WideBuilder # sconcat :: NonEmpty WideBuilder -> WideBuilder # stimes :: Integral b => b -> WideBuilder -> WideBuilder # | |
| Show WideBuilder | |
Defined in Text.WideString Methods showsPrec :: Int -> WideBuilder -> ShowS # show :: WideBuilder -> String # showList :: [WideBuilder] -> ShowS # | |
customErrorBundlePretty :: HledgerParseErrors -> String #
Pretty-print our custom parse errors. It is necessary to use this
instead of errorBundlePretty when custom parse errors are thrown.
This function intercepts our custom parse errors and applies final
adjustments (finalizeCustomError) before passing them to
errorBundlePretty. These adjustments are part of the implementation
of the behaviour of our custom parse errors.
Note: We must ensure that the offset of the PosState of the provided
ParseErrorBundle is no larger than the offset specified by a
ErrorFailAt constructor. This is guaranteed if this offset is set to
0 (that is, the beginning of the source file), which is the
case for ParseErrorBundles returned from runParserT.
data HledgerParseErrorData #
Custom error data for hledger parsers. Specialised for a Text parse stream.
ReparseableTextParseErrorData ?
Instances
type HledgerParseErrors = ParseErrorBundle Text HledgerParseErrorData #
A specialised version of ParseErrorBundle:
a non-empty collection of hledger parse errors,
equipped with PosState to help pretty-print them.
Specialised for a Text parse stream.
startOfFirstWeekInMonth :: Year -> MonthOfYear -> Day #
firstMonthOfQuarter :: Num a => a -> a #
quarterContainingMonth :: Integral a => a -> a #
yearMonthContainingWeekStarting :: Day -> (Year, MonthOfYear) #
mondayBefore :: Day -> Day #
periodShrink :: Day -> Period -> Period #
Shrink a period to the next smaller standard period inside it, choosing the subperiod which contains today's date if possible, otherwise the first subperiod. It goes like this: unbounded periods and nonstandard periods (between two arbitrary dates) -> current year -> current quarter if it's in selected year, otherwise first quarter of selected year -> current month if it's in selected quarter, otherwise first month of selected quarter -> current week if it's in selected month, otherwise first week of selected month -> today if it's in selected week, otherwise first day of selected week, unless that's in previous month, in which case first day of month containing selected week. Shrinking a day has no effect.
periodGrow :: Period -> Period #
Enlarge a standard period to the next larger enclosing standard period, if there is one. Eg, a day becomes the enclosing week. A week becomes whichever month the week's thursday falls into. A year becomes all (unlimited). Non-standard periods (arbitrary dates, or open-ended) are unaffected.
periodMoveTo :: Day -> Period -> Period #
Move a standard period stepwise so that it encloses the given date. Non-standard periods are unaffected.
periodPreviousIn :: DateSpan -> Period -> Period #
Move a standard period to the preceding period of same duration, staying within enclosing dates. Non-standard periods are unaffected.
periodNextIn :: DateSpan -> Period -> Period #
Move a standard period to the following period of same duration, staying within enclosing dates. Non-standard periods are unaffected.
periodPrevious :: Period -> Period #
Move a standard period to the preceding period of same duration. Non-standard periods are unaffected.
periodNext :: Period -> Period #
Move a standard period to the following period of same duration. Non-standard periods are unaffected.
periodStart :: Period -> Maybe Day #
showPeriodMonthAbbrev :: Period -> Text #
Like showPeriod, but if it's a month period show just the 3 letter month name abbreviation for the current locale.
showPeriod :: Period -> Text #
Render a period as a compact display string suitable for user output.
>>>showPeriod (WeekPeriod (fromGregorian 2016 7 25))"2016-07-25W30"
periodTextWidth :: Period -> Int #
The width of a period of this type when displayed.
isStandardPeriod :: Period -> Bool #
Is this period a "standard" period, referencing a particular day, week, month, quarter, or year ? Periods of other durations, or infinite duration, or not starting on a standard period boundary, are not.
simplifyPeriod :: Period -> Period #
Convert PeriodBetweens to a more abstract period where possible.
>>>simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1)YearPeriod 1>>>simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1)QuarterPeriod 2000 4>>>simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1)MonthPeriod 2000 2>>>simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1)WeekPeriod 2016-07-25>>>simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2)DayPeriod 2000-01-01>>>simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1)PeriodBetween 2000-02-28 2000-03-01>>>simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1)DayPeriod 2000-02-29>>>simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1)DayPeriod 2000-12-31
dateSpanAsPeriod :: DateSpan -> Period #
Convert DateSpans to Periods.
>>>dateSpanAsPeriod $ DateSpan (Just $ Exact $ fromGregorian 2000 1 1) (Just $ Exact $ fromGregorian 2000 2 1)MonthPeriod 2000 1
periodAsDateSpan :: Period -> DateSpan #
Convert Periods to exact DateSpans.
>>>periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ Flex $ fromGregorian 2000 1 1) (Just $ Flex $ fromGregorian 2000 2 1)True
maCompare :: MixedAmount -> MixedAmount -> Ordering #
Compare two MixedAmounts, substituting 0 for the quantity of any missing commodities in either.
isDecimalMark :: Char -> Bool #
isAccountSubtypeOf :: AccountType -> AccountType -> Bool #
Check whether the first argument is a subtype of the second: either equal or one of the defined subtypes.
A possibly incomplete year-month-day date provided by the user, to be
interpreted as either a date or a date span depending on context. Missing
parts "on the left" will be filled from the provided reference date, e.g. if
the year and month are missing, the reference date's year and month are used.
Missing parts "on the right" are assumed, when interpreting as a date, to be
1, (e.g. if the year and month are present but the day is missing, it means
first day of that month); or when interpreting as a date span, to be a
wildcard (so it would mean all days of that month). See the smartdate
parser for more examples.
Or, one of the standard periods and an offset relative to the reference date: (last|this|next) (day|week|month|quarter|year), where "this" means the period containing the reference date.
data SmartInterval #
Instances
| Show SmartInterval | |
Defined in Hledger.Data.Types Methods showsPrec :: Int -> SmartInterval -> ShowS # show :: SmartInterval -> String # showList :: [SmartInterval] -> ShowS # | |
Constructors
| PrimaryDate | |
| SecondaryDate |
A date which is either exact or flexible. Flexible dates are allowed to be adjusted in certain situations.
Instances
| Generic EFDay | |
| Show EFDay | |
| Eq EFDay | |
| Ord EFDay | |
| type Rep EFDay | |
Defined in Hledger.Data.Types type Rep EFDay = D1 ('MetaData "EFDay" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "Exact" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Day)) :+: C1 ('MetaCons "Flex" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Day))) | |
A possibly open-ended span of time, from an optional inclusive start date to an optional exclusive end date. Each date can be either exact or flexible. An "exact date span" is a Datepan with exact start and end dates.
Instances
| Generic DateSpan | |
| Default DateSpan | |
Defined in Hledger.Data.Types | |
| Eq DateSpan | |
| Ord DateSpan | |
Defined in Hledger.Data.Types | |
| type Rep DateSpan | |
Defined in Hledger.Data.Types type Rep DateSpan = D1 ('MetaData "DateSpan" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "DateSpan" 'PrefixI 'False) (S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe EFDay)) :*: S1 ('MetaSel ('Nothing :: Maybe Symbol) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe EFDay)))) | |
Constructors
| DayPeriod Day | |
| WeekPeriod Day | |
| MonthPeriod Year Month | |
| QuarterPeriod Year Quarter | |
| YearPeriod Year | |
| PeriodBetween Day Day | |
| PeriodFrom Day | |
| PeriodTo Day | |
| PeriodAll |
Instances
Constructors
| NoInterval | |
| Days Int | |
| Weeks Int | |
| Months Int | |
| Quarters Int | |
| Years Int | |
| DayOfMonth Int | |
| WeekdayOfMonth Int Int | |
| DaysOfWeek [Int] | |
| DayOfYear Int Int |
Instances
type AccountName = Text #
data AccountType #
Constructors
| Asset | |
| Liability | |
| Equity | |
| Revenue | |
| Expense | |
| Cash | a subtype of Asset - liquid assets to show in cashflow report |
| Conversion | a subtype of Equity - account in which to generate conversion postings for transaction prices |
Instances
data AccountAlias #
Constructors
| BasicAlias AccountName AccountName | |
| RegexAlias Regexp Replacement |
Instances
type DecimalMark = Char #
One of the decimal marks we support: either period or comma.
data AmountPrice #
An amount's per-unit or total cost/selling price in another
commodity, as recorded in the journal entry eg with or @.
Cost, formerly AKA "transaction price". The amount is always positive.
Constructors
| UnitPrice !Amount | |
| TotalPrice !Amount |
Instances
data AmountStyle #
Every Amount has one of these, influencing how the amount is displayed. Also, each Commodity can have one, which can be applied to its amounts for consistent display. See also Amount.AmountDisplayOpts.
Constructors
| AmountStyle | |
Fields
| |
Instances
data AmountPrecision #
The "display precision" for a hledger amount, by which we mean the number of decimal digits to display to the right of the decimal mark.
Constructors
| Precision !Word8 | show this many decimal digits (0..255) |
| NaturalPrecision | show all significant decimal digits stored internally |
Instances
"Rounding strategy" - how to apply an AmountStyle's display precision to a posting amount (and its cost, if any). Mainly used to customise print's output, with --round=none|soft|hard|all.
Constructors
| NoRounding | keep display precisions unchanged in amt and cost |
| SoftRounding | do soft rounding of amt and cost amounts (show more or fewer decimal zeros to approximate the target precision, but don't hide significant digits) |
| HardRounding | do hard rounding of amt (use the exact target precision, possibly hiding significant digits), and soft rounding of cost |
| AllRounding | do hard rounding of amt and cost |
Instances
| Generic Rounding | |
| Read Rounding | |
| Show Rounding | |
| Eq Rounding | |
| Ord Rounding | |
Defined in Hledger.Data.Types | |
| type Rep Rounding | |
Defined in Hledger.Data.Types type Rep Rounding = D1 ('MetaData "Rounding" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) ((C1 ('MetaCons "NoRounding" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "SoftRounding" 'PrefixI 'False) (U1 :: Type -> Type)) :+: (C1 ('MetaCons "HardRounding" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "AllRounding" 'PrefixI 'False) (U1 :: Type -> Type))) | |
data DigitGroupStyle #
A style for displaying digit groups in the integer part of a floating point number. It consists of the character used to separate groups (comma or period, whichever is not used as decimal point), and the size of each group, starting with the one nearest the decimal point. The last group size is assumed to repeat. Eg, comma between thousands is DigitGroups ',' [3].
Constructors
| DigitGroups !Char ![Word8] |
Instances
type CommoditySymbol = Text #
Constructors
| Commodity | |
Fields | |
Instances
| Generic Commodity | |
| Show Commodity | |
| Eq Commodity | |
| type Rep Commodity | |
Defined in Hledger.Data.Types type Rep Commodity = D1 ('MetaData "Commodity" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "Commodity" 'PrefixI 'True) (S1 ('MetaSel ('Just "csymbol") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 CommoditySymbol) :*: S1 ('MetaSel ('Just "cformat") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe AmountStyle)))) | |
Constructors
| Amount | |
Fields
| |
Instances
| Generic Amount | |
| Show Amount | |
| Eq Amount | |
| Ord Amount | |
| type Rep Amount | |
Defined in Hledger.Data.Types type Rep Amount = D1 ('MetaData "Amount" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "Amount" 'PrefixI 'True) ((S1 ('MetaSel ('Just "acommodity") 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 CommoditySymbol) :*: S1 ('MetaSel ('Just "aquantity") 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Quantity)) :*: (S1 ('MetaSel ('Just "astyle") 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 AmountStyle) :*: S1 ('MetaSel ('Just "aprice") 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 (Maybe AmountPrice))))) | |
class HasAmounts a where #
Types with this class have one or more amounts, which can have display styles applied to them.
Methods
styleAmounts :: Map CommoditySymbol AmountStyle -> a -> a #
Instances
data MixedAmount #
Instances
pattern MixedAmountKeyUnitPrice :: !CommoditySymbol -> !CommoditySymbol -> !Quantity -> MixedAmountKey #
pattern MixedAmountKeyNoPrice :: !CommoditySymbol -> MixedAmountKey #
pattern MixedAmountKeyTotalPrice :: !CommoditySymbol -> !CommoditySymbol -> MixedAmountKey #
data PostingType #
Constructors
| RegularPosting | |
| VirtualPosting | |
| BalancedVirtualPosting |
Instances
| Generic PostingType | |
Defined in Hledger.Data.Types Associated Types type Rep PostingType :: Type -> Type # | |
| Show PostingType | |
Defined in Hledger.Data.Types Methods showsPrec :: Int -> PostingType -> ShowS # show :: PostingType -> String # showList :: [PostingType] -> ShowS # | |
| Eq PostingType | |
Defined in Hledger.Data.Types | |
| type Rep PostingType | |
Defined in Hledger.Data.Types type Rep PostingType = D1 ('MetaData "PostingType" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "RegularPosting" 'PrefixI 'False) (U1 :: Type -> Type) :+: (C1 ('MetaCons "VirtualPosting" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "BalancedVirtualPosting" 'PrefixI 'False) (U1 :: Type -> Type))) | |
The status of a transaction or posting, recorded with a status mark (nothing, !, or *). What these mean is ultimately user defined.
Instances
| Bounded Status | |
| Enum Status | |
Defined in Hledger.Data.Types | |
| Generic Status | |
| Show Status | |
| Eq Status | |
| Ord Status | |
| type Rep Status | |
Defined in Hledger.Data.Types type Rep Status = D1 ('MetaData "Status" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "Unmarked" 'PrefixI 'False) (U1 :: Type -> Type) :+: (C1 ('MetaCons "Pending" 'PrefixI 'False) (U1 :: Type -> Type) :+: C1 ('MetaCons "Cleared" 'PrefixI 'False) (U1 :: Type -> Type))) | |
data BalanceAssertion #
A balance assertion is a declaration about an account's expected balance at a certain point (posting date and parse order). They provide additional error checking and readability to a journal file.
A balance assignments is an instruction to hledger to adjust an account's balance to a certain amount at a certain point.
The BalanceAssertion type is used for representing both of these.
hledger supports multiple kinds of balance assertions/assignments, which differ in whether they refer to a single commodity or all commodities, and the (subaccount-)inclusive or exclusive account balance.
Constructors
| BalanceAssertion | |
Fields
| |
Instances
Constructors
| Posting | |
Fields
| |
Instances
data Transaction #
Constructors
| Transaction | |
Fields
| |
Instances
data TransactionModifier #
A transaction modifier rule. This has a query which matches postings in the journal, and a list of transformations to apply to those postings or their transactions. Currently there is one kind of transformation: the TMPostingRule, which adds a posting ("auto posting") to the transaction, optionally setting its amount to the matched posting's amount multiplied by a constant.
Constructors
| TransactionModifier | |
Fields
| |
Instances
data TMPostingRule #
A transaction modifier transformation, which adds an extra posting to the matched posting's transaction. Can be like a regular posting, or can have the tmprIsMultiplier flag set, indicating that it's a multiplier for the matched posting's amount.
Constructors
| TMPostingRule | |
Fields | |
Instances
| Generic TMPostingRule | |
Defined in Hledger.Data.Types Associated Types type Rep TMPostingRule :: Type -> Type # | |
| Show TMPostingRule | |
Defined in Hledger.Data.Types Methods showsPrec :: Int -> TMPostingRule -> ShowS # show :: TMPostingRule -> String # showList :: [TMPostingRule] -> ShowS # | |
| Eq TMPostingRule | |
Defined in Hledger.Data.Types Methods (==) :: TMPostingRule -> TMPostingRule -> Bool # (/=) :: TMPostingRule -> TMPostingRule -> Bool # | |
| type Rep TMPostingRule | |
Defined in Hledger.Data.Types type Rep TMPostingRule = D1 ('MetaData "TMPostingRule" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "TMPostingRule" 'PrefixI 'True) (S1 ('MetaSel ('Just "tmprPosting") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Posting) :*: S1 ('MetaSel ('Just "tmprIsMultiplier") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Bool))) | |
data PeriodicTransaction #
A periodic transaction rule, describing a transaction that recurs.
Constructors
| PeriodicTransaction | |
Fields
| |
Instances
data TimeclockCode #
Constructors
| SetBalance | |
| SetRequiredHours | |
| In | |
| Out | |
| FinalOut |
Instances
data TimeclockEntry #
Constructors
| TimeclockEntry | |
Fields
| |
Instances
data PriceDirective #
A market price declaration made by the journal format's P directive. It declares two things: a historical exchange rate between two commodities, and an amount display style for the second commodity.
Constructors
| PriceDirective | |
Fields
| |
Instances
data MarketPrice #
A historical market price (exchange rate) from one commodity to another. A more concise form of a PriceDirective, without the amount display info.
Constructors
| MarketPrice | |
Fields
| |
Instances
A Journal, containing transactions and various other things. The basic data model for hledger.
This is used during parsing (as the type alias ParsedJournal), and then finalised/validated for use as a Journal. Some extra parsing-related fields are included for convenience, at least for now. In a ParsedJournal these are updated as parsing proceeds, in a Journal they represent the final state at end of parsing (used eg by the add command).
Constructors
| Journal | |
Fields
| |
Instances
type ParsedJournal = Journal #
A journal in the process of being parsed, not yet finalised. The data is partial, and list fields are in reverse order.
type StorageFormat = String #
The id of a data format understood by hledger, eg journal or csv.
The --output-format option selects one of these for output.
data PayeeDeclarationInfo #
Extra information found in a payee directive.
Constructors
| PayeeDeclarationInfo | |
Fields
| |
Instances
newtype TagDeclarationInfo #
Extra information found in a tag directive.
Constructors
| TagDeclarationInfo | |
Fields
| |
Instances
| Generic TagDeclarationInfo | |
Defined in Hledger.Data.Types Associated Types type Rep TagDeclarationInfo :: Type -> Type # Methods from :: TagDeclarationInfo -> Rep TagDeclarationInfo x # to :: Rep TagDeclarationInfo x -> TagDeclarationInfo # | |
| Show TagDeclarationInfo | |
Defined in Hledger.Data.Types Methods showsPrec :: Int -> TagDeclarationInfo -> ShowS # show :: TagDeclarationInfo -> String # showList :: [TagDeclarationInfo] -> ShowS # | |
| Eq TagDeclarationInfo | |
Defined in Hledger.Data.Types Methods (==) :: TagDeclarationInfo -> TagDeclarationInfo -> Bool # (/=) :: TagDeclarationInfo -> TagDeclarationInfo -> Bool # | |
| type Rep TagDeclarationInfo | |
Defined in Hledger.Data.Types type Rep TagDeclarationInfo = D1 ('MetaData "TagDeclarationInfo" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'True) (C1 ('MetaCons "TagDeclarationInfo" 'PrefixI 'True) (S1 ('MetaSel ('Just "tdicomment") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Text))) | |
data AccountDeclarationInfo #
Extra information about an account that can be derived from its account directive (and the other account directives).
Constructors
| AccountDeclarationInfo | |
Fields
| |
Instances
An account, with its balances, parent/subaccount relationships, etc. Only the name is required; the other fields are added when needed.
Constructors
| Account | |
Fields
| |
Instances
data NormalSign #
Whether an account's balance is normally a positive number (in accounting terms, a debit balance) or a negative number (credit balance). Assets and expenses are normally positive (debit), while liabilities, equity and income are normally negative (credit). https://en.wikipedia.org/wiki/Normal_balance
Constructors
| NormallyPositive | |
| NormallyNegative |
Instances
| Show NormalSign | |
Defined in Hledger.Data.Types Methods showsPrec :: Int -> NormalSign -> ShowS # show :: NormalSign -> String # showList :: [NormalSign] -> ShowS # | |
| Eq NormalSign | |
Defined in Hledger.Data.Types | |
A Ledger has the journal it derives from, and the accounts derived from that. Accounts are accessible both list-wise and tree-wise, since each one knows its parent and subs; the first account is the root of the tree and always exists.
Instances
| Generic Ledger | |
| type Rep Ledger | |
Defined in Hledger.Data.Types type Rep Ledger = D1 ('MetaData "Ledger" "Hledger.Data.Types" "hledger-lib-1.32.1-DNcsZ2sR6vCELWa5ggJvzA" 'False) (C1 ('MetaCons "Ledger" 'PrefixI 'True) (S1 ('MetaSel ('Just "ljournal") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Journal) :*: S1 ('MetaSel ('Just "laccounts") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 [Account]))) | |
regexReplaceUnmemo :: Regexp -> Replacement -> String -> Either RegexError String #
regexReplace :: Regexp -> Replacement -> String -> Either RegexError String #
A memoising version of regexReplace. Caches the result for each search pattern, replacement pattern, target string tuple. This won't generate a regular expression parsing error since that is pre-compiled nowadays, but there can still be a runtime error from the replacement pattern, eg with a backreference referring to a nonexistent match group.
regexMatchTextGroups :: Regexp -> Text -> [Text] #
Return a (possibly empty) list of match groups derived by applying the Regex to a Text.
regexMatchText :: Regexp -> Text -> Bool #
Tests whether a Regexp matches a Text.
This currently unpacks the Text to a String an works on that. This is due to a performance bug in regex-tdfa (#9), which may or may not be relevant here.
regexMatch :: Regexp -> String -> Bool #
Test whether a Regexp matches a String. This is an alias for matchTest for consistent
naming.
toRegexCI' :: Text -> Regexp #
Regular expression. Extended regular expression-ish syntax ? But does not support eg (?i) syntax.
Instances
| ToJSON Regexp | |
| Read Regexp | |
| Show Regexp | |
| Eq Regexp | |
| Ord Regexp | |
| RegexLike Regexp String | |
Defined in Hledger.Utils.Regex Methods matchOnce :: Regexp -> String -> Maybe MatchArray # matchAll :: Regexp -> String -> [MatchArray] # matchCount :: Regexp -> String -> Int # matchTest :: Regexp -> String -> Bool # matchAllText :: Regexp -> String -> [MatchText String] # matchOnceText :: Regexp -> String -> Maybe (String, MatchText String, String) # | |
| RegexContext Regexp String String | |
type Replacement = String #
A replacement pattern. May include numeric backreferences (N).
type RegexError = String #
An error message arising during a regular expression operation. Eg: trying to compile a malformed regular expression, or trying to apply a malformed replacement pattern.
Timeout to be applied to individual tests.
Since: tasty-0.8
Constructors
| Timeout Integer String |
|
| NoTimeout |
Instances
| Show Timeout | |
| IsOption Timeout | |
Defined in Test.Tasty.Options.Core Methods defaultValue :: Timeout # parseValue :: String -> Maybe Timeout # optionName :: Tagged Timeout String # optionHelp :: Tagged Timeout String # showDefaultValue :: Timeout -> Maybe String # | |
A shortcut for creating Timeout values.
Since: tasty-0.8
The main data structure defining a test suite.
It consists of individual test cases and properties, organized in named groups which form a tree-like hierarchy.
There is no generic way to create a test case. Instead, every test
provider (tasty-hunit, tasty-smallcheck etc.) provides a function to
turn a test case into a TestTree.
Groups can be created using testGroup.
Since: tasty-0.1
data DependencyType #
These are the two ways in which one test may depend on the others.
This is the same distinction as the hard vs soft dependencies in TestNG.
Since: tasty-1.2
Constructors
| AllSucceed | The current test tree will be executed after its dependencies finish, and only if all of the dependencies succeed. |
| AllFinish | The current test tree will be executed after its dependencies finish, regardless of whether they succeed or not. |
Instances
| Read DependencyType | Since: tasty-1.5 |
Defined in Test.Tasty.Core Methods readsPrec :: Int -> ReadS DependencyType # readList :: ReadS [DependencyType] # | |
| Show DependencyType | |
Defined in Test.Tasty.Core Methods showsPrec :: Int -> DependencyType -> ShowS # show :: DependencyType -> String # showList :: [DependencyType] -> ShowS # | |
| Eq DependencyType | |
Defined in Test.Tasty.Core Methods (==) :: DependencyType -> DependencyType -> Bool # (/=) :: DependencyType -> DependencyType -> Bool # | |
testGroup :: TestName -> [TestTree] -> TestTree #
Create a named group of test cases or other groups. Tests are executed in
parallel. For sequential execution, see sequentialTestGroup.
Since: tasty-0.1
sequentialTestGroup :: TestName -> DependencyType -> [TestTree] -> TestTree #
Create a named group of test cases or other groups. Tests are executed in
order. For parallel execution, see testGroup.
Arguments
| :: DependencyType | whether to run the tests even if some of the dependencies fail |
| -> Expr | the pattern |
| -> TestTree | the subtree that depends on other tests |
| -> TestTree | the subtree annotated with dependency information |
Like after, but accepts the pattern as a syntax tree instead
of a string. Useful for generating a test tree programmatically.
Examples
Only match on the test's own name, ignoring the group names:
after_AllFinish(EQ(FieldNF) (StringLit"Bar")) $
testCase "A test that depends on Foo.Bar" $ ...
Since: tasty-1.2
Arguments
| :: DependencyType | whether to run the tests even if some of the dependencies fail |
| -> String | the pattern |
| -> TestTree | the subtree that depends on other tests |
| -> TestTree | the subtree annotated with dependency information |
The after combinator declares dependencies between tests.
If a TestTree is wrapped in after, the tests in this tree will not run
until certain other tests («dependencies») have finished. These
dependencies are specified using an AWK pattern (see the «Patterns» section
in the README).
Moreover, if the DependencyType argument is set to AllSucceed and
at least one dependency has failed, this test tree will not run at all.
Tasty does not check that the pattern matches any tests (let alone the correct set of tests), so it is on you to supply the right pattern.
Examples
The following test will be executed only after all tests that contain
Foo anywhere in their path finish.
afterAllFinish"Foo" $
testCase "A test that depends on Foo.Bar" $ ...
Note, however, that our test also happens to contain Foo as part of its name,
so it also matches the pattern and becomes a dependency of itself. This
will result in a DependencyLoop exception. To avoid this, either
change the test name so that it doesn't mention Foo or make the
pattern more specific.
You can use AWK patterns, for instance, to specify the full path to the dependency.
afterAllFinish"$0 == \"Tests.Foo.Bar\"" $
testCase "A test that depends on Foo.Bar" $ ...
Or only specify the dependency's own name, ignoring the group names:
afterAllFinish"$NF == \"Bar\"" $
testCase "A test that depends on Foo.Bar" $ ...
Since: tasty-1.2
includingOptions :: [OptionDescription] -> Ingredient #
This ingredient doesn't do anything apart from registering additional options.
The option values can be accessed using askOption.
Since: tasty-0.6
defaultMainWithIngredients :: [Ingredient] -> TestTree -> IO () #
Parse the command line arguments and run the tests using the provided ingredient list.
When the tests finish, this function calls exitWith with the exit code
that indicates whether any tests have failed. See defaultMain for
details.
Since: tasty-0.4
defaultIngredients :: [Ingredient] #
List of the default ingredients. This is what defaultMain uses.
At the moment it consists of listingTests and consoleTestReporter.
Since: tasty-0.4.2
adjustOption :: IsOption v => (v -> v) -> TestTree -> TestTree #
Locally adjust the option value for the given test subtree.
Since: tasty-0.1
localOption :: IsOption v => v -> TestTree -> TestTree #
Locally set the option value for the given test subtree.
Since: tasty-0.1
askOption :: IsOption v => (v -> TestTree) -> TestTree #
Customize the test tree based on the run-time options.
Since: tasty-0.6
Arguments
| :: IO a | initialize the resource |
| -> (a -> IO ()) | free the resource |
| -> (IO a -> TestTree) |
|
| -> TestTree |
Acquire the resource to run this test (sub)tree and release it afterwards.
Since: tasty-0.5
runExceptT :: ExceptT e m a -> m (Either e a) #
The inverse of ExceptT.
The data type SourcePos represents source positions. It contains the
name of the source file, a line number, and a column number. Source line
and column positions change intensively during parsing, so we need to
make them strict to avoid memory leaks.
Constructors
| SourcePos | |
Fields
| |
Instances
| Data SourcePos | |
Defined in Text.Megaparsec.Pos Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> SourcePos -> c SourcePos # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c SourcePos # toConstr :: SourcePos -> Constr # dataTypeOf :: SourcePos -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c SourcePos) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c SourcePos) # gmapT :: (forall b. Data b => b -> b) -> SourcePos -> SourcePos # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> SourcePos -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> SourcePos -> r # gmapQ :: (forall d. Data d => d -> u) -> SourcePos -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> SourcePos -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> SourcePos -> m SourcePos # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> SourcePos -> m SourcePos # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> SourcePos -> m SourcePos # | |
| Generic SourcePos | |
| Read SourcePos | |
| Show SourcePos | |
| NFData SourcePos | |
Defined in Text.Megaparsec.Pos | |
| Eq SourcePos | |
| Ord SourcePos | |
| type Rep SourcePos | |
Defined in Text.Megaparsec.Pos type Rep SourcePos = D1 ('MetaData "SourcePos" "Text.Megaparsec.Pos" "megaparsec-9.5.0-Bqj3lyPLshK3HUIJudgLYB" 'False) (C1 ('MetaCons "SourcePos" 'PrefixI 'True) (S1 ('MetaSel ('Just "sourceName") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 FilePath) :*: (S1 ('MetaSel ('Just "sourceLine") 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Pos) :*: S1 ('MetaSel ('Just "sourceColumn") 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 Pos)))) | |
Construction of Pos from Int. The function throws
InvalidPosException when given a non-positive argument.
Since: megaparsec-6.0.0
initialPos :: FilePath -> SourcePos #
Construct initial position (line 1, column 1) given name of source file.
sourcePosPretty :: SourcePos -> String #
Pretty-print a SourcePos.
Since: megaparsec-5.0.0
foldl1Def' :: a -> (a -> a -> a) -> [a] -> a #
maximumByDef :: a -> (a -> a -> Ordering) -> [a] -> a #
New users are recommended to use minimumBoundBy or maximumBoundBy instead.
minimumByDef :: a -> (a -> a -> Ordering) -> [a] -> a #
New users are recommended to use minimumBoundBy or maximumBoundBy instead.
maximumDef :: Ord a => a -> [a] -> a #
New users are recommended to use minimumBound or maximumBound instead.
minimumDef :: Ord a => a -> [a] -> a #
New users are recommended to use minimumBound or maximumBound instead.
toEnumSafe :: (Enum a, Bounded a) => Int -> a #
findIndexJustDef :: Int -> (a -> Bool) -> [a] -> Int #
findIndexJust :: (a -> Bool) -> [a] -> Int #
findIndexJust op = fromJust . findIndex op
elemIndexJustDef :: Eq a => Int -> a -> [a] -> Int #
elemIndexJust :: (Partial, Eq a) => a -> [a] -> Int #
elemIndexJust op = fromJust . elemIndex op
findJustNote :: Partial => String -> (a -> Bool) -> [a] -> a #
findJustDef :: a -> (a -> Bool) -> [a] -> a #
lookupJustNote :: (Partial, Eq a) => String -> a -> [(a, b)] -> b #
lookupJustDef :: Eq a => b -> a -> [(a, b)] -> b #
lookupJust :: (Eq a, Partial) => a -> [(a, b)] -> b #
lookupJust key = fromJust . lookup key
readNote :: (Partial, Read a) => String -> String -> a #
readNote uses readEitherSafe for the error message.
readEitherSafe :: Read a => String -> Either String a #
This function provides a more precise error message than readEither from base.
assertNote :: Partial => String -> Bool -> a -> a #
fromJustNote :: Partial => String -> Maybe a -> a #
fromJustDef :: a -> Maybe a -> a #
scanl1Note :: Partial => String -> (a -> a -> a) -> [a] -> [a] #
scanr1Note :: Partial => String -> (a -> a -> a) -> [a] -> [a] #
foldl1Note' :: Partial => String -> (a -> a -> a) -> [a] -> a #
foldl1Note :: Partial => String -> (a -> a -> a) -> [a] -> a #
foldr1Note :: Partial => String -> (a -> a -> a) -> [a] -> a #
foldl1May' :: (a -> a -> a) -> [a] -> Maybe a #
minimumBounded :: (Ord a, Bounded a) => [a] -> a #
The largest element of a list.
The result is bounded by maxBound.
maximumBounded :: (Ord a, Bounded a) => [a] -> a #
The largest element of a list.
The result is bounded by minBound.
minimumBound :: Ord a => a -> [a] -> a #
The smallest element of a list. The result is bounded by the value given as the first argument.
maximumBound :: Ord a => a -> [a] -> a #
The largest element of a list. The result is bounded by the value given as the first argument.
minimumBoundBy :: a -> (a -> a -> Ordering) -> [a] -> a #
The smallest element of a list with respect to the given comparison function. The result is bounded by the value given as the first argument.
maximumBoundBy :: a -> (a -> a -> Ordering) -> [a] -> a #
The largest element of a list with respect to the given comparison function. The result is bounded by the value given as the first argument.
maximumByNote :: Partial => String -> (a -> a -> Ordering) -> [a] -> a #
minimumByNote :: Partial => String -> (a -> a -> Ordering) -> [a] -> a #
maximumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a #
minimumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a #
maximumNote :: (Partial, Ord a) => String -> [a] -> a #
minimumNote :: (Partial, Ord a) => String -> [a] -> a #
maximumMay :: Ord a => [a] -> Maybe a #
minimumMay :: Ord a => [a] -> Maybe a #
tailNote :: Partial => String -> [a] -> [a] #
tailNote "help me" [] = error "Safe.tailNote [], help me" tailNote "help me" [1,3,4] = [3,4]
Arguments
| :: ParseTime t | |
| => Bool | Accept leading whitespace? |
| -> TimeLocale | Time locale. |
| -> String | Format string |
| -> ReadS t |
Parse a time value given a format string. See parseTimeM for details.
Arguments
| :: ParseTime t | |
| => Bool | Accept leading whitespace? |
| -> TimeLocale | Time locale. |
| -> String | Format string |
| -> ReadP t |
Parse a time value given a format string. See parseTimeM for details.
Arguments
| :: ParseTime t | |
| => Bool | Accept leading and trailing whitespace? |
| -> TimeLocale | Time locale. |
| -> String | Format string. |
| -> String | Input string. |
| -> t | The time value. |
Parse a time value given a format string. Fails if the input could
not be parsed using the given format. See parseTimeM for details.
Arguments
| :: (MonadFail m, ParseTime t) | |
| => Bool | Accept leading and trailing whitespace? |
| -> TimeLocale | Time locale. |
| -> [(String, String)] | Pairs of (format string, input string). |
| -> m t | Return the time value, or fail if the input could not be parsed using the given format. |
Parses a time value given a list of pairs of format and input. Resulting value is constructed from all provided specifiers.
Arguments
| :: (MonadFail m, ParseTime t) | |
| => Bool | Accept leading and trailing whitespace? |
| -> TimeLocale | Time locale. |
| -> String | Format string. |
| -> String | Input string. |
| -> m t | Return the time value, or fail if the input could not be parsed using the given format. |
Parses a time value given a format string.
Missing information will be derived from 1970-01-01 00:00 UTC (which was a Thursday).
Supports the same %-codes as formatTime, including %-, %_ and %0 modifiers, however padding widths are not supported.
Case is not significant in the input string.
Some variations in the input are accepted:
%z%Ez- accepts any of
±HHMMor±HH:MM. %Z%EZ- accepts any string of letters, or any of the formats accepted by
%z. %0Y- accepts exactly four digits.
%0G- accepts exactly four digits.
%0C- accepts exactly two digits.
%0f- accepts exactly two digits.
For example, to parse a date in YYYY-MM-DD format, while allowing the month
and date to have optional leading zeros (notice the - modifier used for %m
and %d):
Prelude Data.Time> parseTimeM True defaultTimeLocale "%Y-%-m-%-d" "2010-3-04" :: Maybe Day Just 2010-03-04
A local time together with a time zone.
There is no Eq instance for ZonedTime.
If you want to compare local times, use zonedTimeToLocalTime.
If you want to compare absolute times, use zonedTimeToUTC.
Constructors
| ZonedTime | |
Fields | |
Instances
| FromJSON ZonedTime | Supported string formats:
The first space may instead be a |
Defined in Data.Aeson.Types.FromJSON | |
| FromJSONKey ZonedTime | |
Defined in Data.Aeson.Types.FromJSON Methods | |
| ToJSON ZonedTime | |
| ToJSONKey ZonedTime | |
Defined in Data.Aeson.Types.ToJSON | |
| Data ZonedTime | |
Defined in Data.Time.LocalTime.Internal.ZonedTime Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> ZonedTime -> c ZonedTime # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c ZonedTime # toConstr :: ZonedTime -> Constr # dataTypeOf :: ZonedTime -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c ZonedTime) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c ZonedTime) # gmapT :: (forall b. Data b => b -> b) -> ZonedTime -> ZonedTime # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> ZonedTime -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> ZonedTime -> r # gmapQ :: (forall d. Data d => d -> u) -> ZonedTime -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> ZonedTime -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> ZonedTime -> m ZonedTime # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> ZonedTime -> m ZonedTime # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> ZonedTime -> m ZonedTime # | |
| Show ZonedTime | |
| NFData ZonedTime | |
Defined in Data.Time.LocalTime.Internal.ZonedTime | |
zonedTimeToUTC :: ZonedTime -> UTCTime #
utcToZonedTime :: TimeZone -> UTCTime -> ZonedTime #
utcToLocalZonedTime :: UTCTime -> IO ZonedTime #
getZonedTime :: IO ZonedTime #
class FormatTime t #
Minimal complete definition
Instances
| FormatTime DotNetTime | |
Defined in Data.Aeson.Types.Internal Methods formatCharacter :: Bool -> Char -> Maybe (FormatOptions -> DotNetTime -> String) # | |
formatTime :: FormatTime t => TimeLocale -> String -> t -> String #
Substitute various time-related information for each %-code in the string, as per formatCharacter.
The general form is %<modifier><width><alternate><specifier>, where <modifier>, <width>, and <alternate> are optional.
<modifier>
glibc-style modifiers can be used before the specifier (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)
<width>
Width digits can also be used after any modifiers and before the specifier (here marked as z), for example:
%4z- pad to 4 characters (with default padding character)
%_12z- pad with spaces to 12 characters
<alternate>
An optional E character indicates an alternate formatting. Currently this only affects %Z and %z.
%Ez- alternate formatting
<specifier>
For all types (note these three are done by formatTime, not by formatCharacter):
%%%%t- tab
%n- newline
TimeZone
For TimeZone (and ZonedTime and UTCTime):
%z- timezone offset in the format
±HHMM %Ez- timezone offset in the format
±HH:MM %Z- timezone name (or else offset in the format
±HHMM) %EZ- timezone name (or else offset in the format
±HH:MM)
LocalTime
For LocalTime (and ZonedTime and UTCTime and UniversalTime):
%c- as
dateTimeFmtlocale(e.g.%a %b %e %H:%M:%S %Z %Y)
TimeOfDay
For TimeOfDay (and LocalTime and ZonedTime and UTCTime and UniversalTime):
%R- same as
%H:%M %T- same as
%H:%M:%S %X- as
timeFmtlocale(e.g.%H:%M:%S) %r- as
time12Fmtlocale(e.g.%I:%M:%S %p) %P- day-half of day from (
amPmlocale), converted to lowercase,am,pm %p- day-half of day from (
amPmlocale),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,
%Qomits the decimal point unless padding is specified.
UTCTime and ZonedTime
For UTCTime and ZonedTime:
%s- number of whole seconds since the Unix epoch. For times before
the Unix epoch, this is a negative number. Note that in
%s.%qand%s%Qthe decimals are positive, not negative. For example, 0.9 seconds before the Unix epoch is formatted as-1.1with%s%Q.
DayOfWeek
For DayOfWeek (and Day and LocalTime and ZonedTime and UTCTime and UniversalTime):
%u- day of week number for Week Date format,
1(= Monday) -7(= Sunday) %w- day of week number,
0(= Sunday) -6(= Saturday) %a- day of week, short form (
sndfromwDayslocale),Sun-Sat %A- day of week, long form (
fstfromwDayslocale),Sunday-Saturday
Month
For Month (and Day and LocalTime and ZonedTime and UTCTime and UniversalTime):
%Y- year, no padding. Note
%0Yand%_Ypad to four chars %y- year of century, 0-padded to two chars,
00-99 %C- century, no padding. Note
%0Cand%_Cpad to two chars %B- month name, long form (
fstfrommonthslocale),January-December %b,%h- month name, short form (
sndfrommonthslocale),Jan-Dec %m- month of year, 0-padded to two chars,
01-12
Day
For Day (and LocalTime and ZonedTime and UTCTime and UniversalTime):
%D- same as
%m/%d/%y %F- same as
%Y-%m-%d %x- as
dateFmtlocale(e.g.%m/%d/%y) %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 %f- century for Week Date format, no padding. Note
%0fand%_fpad to two chars %V- week of year for Week Date format, 0-padded to two chars,
01-53 %U- week of year where weeks start on Sunday (as
sundayStartWeek), 0-padded to two chars,00-53 %W- week of year where weeks start on Monday (as
mondayStartWeek), 0-padded to two chars,00-53
Duration types
The specifiers for DiffTime, NominalDiffTime, CalendarDiffDays, and CalendarDiffTime are semantically
separate from the other types.
Specifiers on negative time differences will generally be negative (think rem rather than mod).
NominalDiffTime and DiffTime
Note that a "minute" of DiffTime is simply 60 SI seconds, rather than a minute of civil time.
Use NominalDiffTime to work with civil time, ignoring any leap seconds.
For NominalDiffTime and DiffTime:
%w- total whole weeks
%d- total whole days
%D- whole days of week
%h- total whole hours
%H- whole hours of day
%m- total whole minutes
%M- whole minutes of hour
%s- total whole seconds
%Es- total seconds, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%Esomits the decimal point unless padding is specified. %0Es- total seconds, with decimal point and <width> (default 12) decimal places.
%S- whole seconds of minute
%ES- seconds of minute, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%ESomits the decimal point unless padding is specified. %0ES- seconds of minute as two digits, with decimal point and <width> (default 12) decimal places.
CalendarDiffDays
For CalendarDiffDays (and CalendarDiffTime):
%y- total years
%b- total months
%B- months of year
%w- total weeks, not including months
%d- total days, not including months
%D- days of week
CalendarDiffTime
For CalendarDiffTime:
%h- total hours, not including months
%H- hours of day
%m- total minutes, not including months
%M- minutes of hour
%s- total whole seconds, not including months
%Es- total seconds, not including months, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%Esomits the decimal point unless padding is specified. %0Es- total seconds, not including months, with decimal point and <width> (default 12) decimal places.
%S- whole seconds of minute
%ES- seconds of minute, with decimal point and up to <width> (default 12) decimal places, without trailing zeros.
For a whole number of seconds,
%ESomits the decimal point unless padding is specified. %0ES- seconds of minute as two digits, with decimal point and <width> (default 12) decimal places.
The class of types which can be parsed given a UNIX-style time format string.
Minimal complete definition
data TimeLocale #
Constructors
| TimeLocale | |
Fields
| |
Instances
| Show TimeLocale | |
Defined in Data.Time.Format.Locale Methods showsPrec :: Int -> TimeLocale -> ShowS # show :: TimeLocale -> String # showList :: [TimeLocale] -> ShowS # | |
| Eq TimeLocale | |
Defined in Data.Time.Format.Locale | |
| Ord TimeLocale | |
Defined in Data.Time.Format.Locale Methods compare :: TimeLocale -> TimeLocale -> Ordering # (<) :: TimeLocale -> TimeLocale -> Bool # (<=) :: TimeLocale -> TimeLocale -> Bool # (>) :: TimeLocale -> TimeLocale -> Bool # (>=) :: TimeLocale -> TimeLocale -> Bool # max :: TimeLocale -> TimeLocale -> TimeLocale # min :: TimeLocale -> TimeLocale -> TimeLocale # | |
Format string according to RFC822.
iso8601DateFormat :: Maybe String -> String #
Construct format string according to ISO-8601.
The Maybe String argument allows to supply an optional time specification. E.g.:
iso8601DateFormatNothing == "%Y-%m-%d" -- i.e.YYYY-MM-DDiso8601DateFormat(Just "%H:%M:%S") == "%Y-%m-%dT%H:%M:%S" -- i.e.YYYY-MM-DDTHH:MM:SS
defaultTimeLocale :: TimeLocale #
Locale representing American usage.
knownTimeZones contains only the ten time-zones mentioned in RFC 802 sec. 5:
"UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT".
Note that the parsing functions will regardless parse "UTC", single-letter military time-zones, and +HHMM format.
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.
Constructors
| LocalTime | |
Fields
| |
Instances
| FromJSON LocalTime | |
Defined in Data.Aeson.Types.FromJSON | |
| FromJSONKey LocalTime | |
Defined in Data.Aeson.Types.FromJSON Methods | |
| ToJSON LocalTime | |
| ToJSONKey LocalTime | |
Defined in Data.Aeson.Types.ToJSON | |
| Data LocalTime | |
Defined in Data.Time.LocalTime.Internal.LocalTime Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> LocalTime -> c LocalTime # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c LocalTime # toConstr :: LocalTime -> Constr # dataTypeOf :: LocalTime -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c LocalTime) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c LocalTime) # gmapT :: (forall b. Data b => b -> b) -> LocalTime -> LocalTime # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> LocalTime -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> LocalTime -> r # gmapQ :: (forall d. Data d => d -> u) -> LocalTime -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> LocalTime -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> LocalTime -> m LocalTime # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> LocalTime -> m LocalTime # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> LocalTime -> m LocalTime # | |
| Show LocalTime | |
| NFData LocalTime | |
Defined in Data.Time.LocalTime.Internal.LocalTime | |
| Eq LocalTime | |
| Ord LocalTime | |
Defined in Data.Time.LocalTime.Internal.LocalTime | |
utcToLocalTime :: TimeZone -> UTCTime -> LocalTime #
Get the local time of a UTC time in a time zone.
ut1ToLocalTime :: Rational -> UniversalTime -> LocalTime #
Get the local time of a UT1 time on a particular meridian (in degrees, positive is East).
localTimeToUTC :: TimeZone -> LocalTime -> UTCTime #
Get the UTC time of a local time in a time zone.
localTimeToUT1 :: Rational -> LocalTime -> UniversalTime #
Get the UT1 time of a local time on a particular meridian (in degrees, positive is East).
diffLocalTime :: LocalTime -> LocalTime -> NominalDiffTime #
diffLocalTime a b = a - b
addLocalTime :: NominalDiffTime -> LocalTime -> LocalTime #
addLocalTime a b = a + b
Time of day as represented in hour, minute and second (with picoseconds), typically used to express local time of day.
Constructors
| TimeOfDay | |
Instances
| FromJSON TimeOfDay | |
Defined in Data.Aeson.Types.FromJSON | |
| FromJSONKey TimeOfDay | |
Defined in Data.Aeson.Types.FromJSON Methods | |
| ToJSON TimeOfDay | |
| ToJSONKey TimeOfDay | |
Defined in Data.Aeson.Types.ToJSON | |
| Data TimeOfDay | |
Defined in Data.Time.LocalTime.Internal.TimeOfDay Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> TimeOfDay -> c TimeOfDay # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c TimeOfDay # toConstr :: TimeOfDay -> Constr # dataTypeOf :: TimeOfDay -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c TimeOfDay) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c TimeOfDay) # gmapT :: (forall b. Data b => b -> b) -> TimeOfDay -> TimeOfDay # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> TimeOfDay -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> TimeOfDay -> r # gmapQ :: (forall d. Data d => d -> u) -> TimeOfDay -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> TimeOfDay -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> TimeOfDay -> m TimeOfDay # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> TimeOfDay -> m TimeOfDay # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> TimeOfDay -> m TimeOfDay # | |
| Show TimeOfDay | |
| NFData TimeOfDay | |
Defined in Data.Time.LocalTime.Internal.TimeOfDay | |
| Eq TimeOfDay | |
| Ord TimeOfDay | |
Defined in Data.Time.LocalTime.Internal.TimeOfDay | |
utcToLocalTimeOfDay :: TimeZone -> TimeOfDay -> (Integer, TimeOfDay) #
Convert a time of day in UTC to a time of day in some timezone, together with a day adjustment.
timeToTimeOfDay :: DiffTime -> TimeOfDay #
Get the time of day given a time since midnight. Time more than 24h will be converted to leap-seconds.
timeToDaysAndTimeOfDay :: NominalDiffTime -> (Integer, TimeOfDay) #
Convert a period of time into a count of days and a time of day since midnight. The time of day will never have a leap second.
timeOfDayToTime :: TimeOfDay -> DiffTime #
Get the time since midnight for a given time of day.
timeOfDayToDayFraction :: TimeOfDay -> Rational #
Get the fraction of a day since midnight given a time of day.
sinceMidnight :: TimeOfDay -> DiffTime #
Same as timeOfDayToTime.
pastMidnight :: DiffTime -> TimeOfDay #
Same as timeToTimeOfDay.
localToUTCTimeOfDay :: TimeZone -> TimeOfDay -> (Integer, TimeOfDay) #
Convert a time of day in some timezone to a time of day in UTC, together with a day adjustment.
daysAndTimeOfDayToTime :: Integer -> TimeOfDay -> NominalDiffTime #
Convert a count of days and a time of day since midnight into a period of time.
dayFractionToTimeOfDay :: Rational -> TimeOfDay #
Get the time of day given the fraction of a day since midnight.
A TimeZone is a whole number of minutes offset from UTC, together with a name and a "just for summer" flag.
Constructors
| TimeZone | |
Fields
| |
Instances
| Data TimeZone | |
Defined in Data.Time.LocalTime.Internal.TimeZone Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> TimeZone -> c TimeZone # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c TimeZone # toConstr :: TimeZone -> Constr # dataTypeOf :: TimeZone -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c TimeZone) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c TimeZone) # gmapT :: (forall b. Data b => b -> b) -> TimeZone -> TimeZone # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> TimeZone -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> TimeZone -> r # gmapQ :: (forall d. Data d => d -> u) -> TimeZone -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> TimeZone -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> TimeZone -> m TimeZone # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> TimeZone -> m TimeZone # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> TimeZone -> m TimeZone # | |
| Show TimeZone | This only shows the time zone name, or offset if the name is empty. |
| NFData TimeZone | |
Defined in Data.Time.LocalTime.Internal.TimeZone | |
| Eq TimeZone | |
| Ord TimeZone | |
Defined in Data.Time.LocalTime.Internal.TimeZone | |
timeZoneOffsetString' :: Maybe Char -> TimeZone -> String #
Text representing the offset of this timezone, such as "-0800" or "+0400" (like %z in formatTime), with arbitrary padding.
timeZoneOffsetString :: TimeZone -> String #
Text representing the offset of this timezone, such as "-0800" or "+0400" (like %z in formatTime).
minutesToTimeZone :: Int -> TimeZone #
Create a nameless non-summer timezone for this number of minutes.
hoursToTimeZone :: Int -> TimeZone #
Create a nameless non-summer timezone for this number of hours.
getTimeZone :: UTCTime -> IO TimeZone #
Get the local time-zone for a given time (varying as per summertime adjustments).
getCurrentTimeZone :: IO TimeZone #
Get the current time-zone.
data CalendarDiffTime #
Constructors
| CalendarDiffTime | |
Fields
| |
Instances
scaleCalendarDiffTime :: Integer -> CalendarDiffTime -> CalendarDiffTime #
Scale by a factor. Note that scaleCalendarDiffTime (-1) will not perfectly invert a duration, due to variable month lengths.
diffUTCTime :: UTCTime -> UTCTime -> NominalDiffTime #
diffUTCTime a b = a - b
addUTCTime :: NominalDiffTime -> UTCTime -> UTCTime #
addUTCTime a b = a + b
getCurrentTime :: IO UTCTime #
Get the current UTCTime from the system clock.
newtype UniversalTime #
The Modified Julian Date is the day with the fraction of the day, measured from UT midnight. It's used to represent UT1, which is time as measured by the earth's rotation, adjusted for various wobbles.
Constructors
| ModJulianDate | |
Fields | |
Instances
getTime_resolution :: DiffTime #
The resolution of getSystemTime, getCurrentTime, getPOSIXTime.
On UNIX systems this uses clock_getres, which may be wrong on WSL2.
data NominalDiffTime #
This is a length of time, as measured by UTC. It has a precision of 10^-12 s.
Conversion functions such as fromInteger and realToFrac will treat it as seconds.
For example, (0.010 :: NominalDiffTime) corresponds to 10 milliseconds.
It has a precision of one picosecond (= 10^-12 s). Enumeration functions will treat it as picoseconds.
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.
Instances
secondsToNominalDiffTime :: Pico -> NominalDiffTime #
Create a NominalDiffTime from a number of seconds.
Since: time-1.9.1
nominalDiffTimeToSeconds :: NominalDiffTime -> Pico #
Get the seconds in a NominalDiffTime.
Since: time-1.9.1
nominalDay :: NominalDiffTime #
One day in NominalDiffTime.
This is a length of time, as measured by a clock.
Conversion functions such as fromInteger and realToFrac will treat it as seconds.
For example, (0.010 :: DiffTime) corresponds to 10 milliseconds.
It has a precision of one picosecond (= 10^-12 s). Enumeration functions will treat it as picoseconds.
Instances
| FromJSON DiffTime | This instance includes a bounds check to prevent maliciously
large inputs to fill up the memory of the target system. You can
newtype |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON DiffTime | |
| Data DiffTime | |
Defined in Data.Time.Clock.Internal.DiffTime Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> DiffTime -> c DiffTime # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c DiffTime # toConstr :: DiffTime -> Constr # dataTypeOf :: DiffTime -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c DiffTime) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c DiffTime) # gmapT :: (forall b. Data b => b -> b) -> DiffTime -> DiffTime # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> DiffTime -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> DiffTime -> r # gmapQ :: (forall d. Data d => d -> u) -> DiffTime -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> DiffTime -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> DiffTime -> m DiffTime # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> DiffTime -> m DiffTime # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> DiffTime -> m DiffTime # | |
| Enum DiffTime | |
Defined in Data.Time.Clock.Internal.DiffTime | |
| Num DiffTime | |
Defined in Data.Time.Clock.Internal.DiffTime | |
| Read DiffTime | |
| Fractional DiffTime | |
| Real DiffTime | |
Defined in Data.Time.Clock.Internal.DiffTime Methods toRational :: DiffTime -> Rational # | |
| RealFrac DiffTime | |
| Show DiffTime | |
| NFData DiffTime | |
Defined in Data.Time.Clock.Internal.DiffTime | |
| Eq DiffTime | |
| Ord DiffTime | |
Defined in Data.Time.Clock.Internal.DiffTime | |
secondsToDiffTime :: Integer -> DiffTime #
Create a DiffTime which represents an integral number of seconds.
picosecondsToDiffTime :: Integer -> DiffTime #
Create a DiffTime from a number of picoseconds.
diffTimeToPicoseconds :: DiffTime -> Integer #
Get the number of picoseconds in a DiffTime.
Instances
firstDayOfWeekOnAfter :: DayOfWeek -> Day -> Day #
The first day-of-week on or after some day
dayOfWeekDiff :: DayOfWeek -> DayOfWeek -> Int #
dayOfWeekDiff a b = a - b in range 0 to 6.
The number of days from b to the next a.
toGregorian :: Day -> (Year, MonthOfYear, DayOfMonth) #
Convert to proleptic Gregorian calendar.
showGregorian :: Day -> String #
Show in ISO 8601 format (yyyy-mm-dd)
gregorianMonthLength :: Year -> MonthOfYear -> DayOfMonth #
The number of days in a given month according to the proleptic Gregorian calendar.
fromGregorianValid :: Year -> MonthOfYear -> DayOfMonth -> Maybe Day #
Convert from proleptic Gregorian calendar. Invalid values will return Nothing
fromGregorian :: Year -> MonthOfYear -> DayOfMonth -> Day #
Convert from proleptic Gregorian calendar. Invalid values will be clipped to the correct range, month first, then day.
diffGregorianDurationRollOver :: Day -> Day -> CalendarDiffDays #
Calendrical difference, with as many whole months as possible.
Same as diffGregorianDurationClip for positive durations.
diffGregorianDurationClip :: Day -> Day -> CalendarDiffDays #
Calendrical difference, with as many whole months as possible
addGregorianYearsRollOver :: Integer -> Day -> Day #
Add years, matching month and day, with Feb 29th rolled over to Mar 1st if necessary. For instance, 2004-02-29 + 2 years = 2006-03-01.
addGregorianYearsClip :: Integer -> Day -> Day #
Add years, matching month and day, with Feb 29th clipped to Feb 28th if necessary. For instance, 2004-02-29 + 2 years = 2006-02-28.
addGregorianMonthsRollOver :: Integer -> Day -> Day #
Add months, with days past the last day of the month rolling over to the next month. For instance, 2005-01-30 + 1 month = 2005-03-02.
addGregorianMonthsClip :: Integer -> Day -> Day #
Add months, with days past the last day of the month clipped to the last day. For instance, 2005-01-30 + 1 month = 2005-02-28.
addGregorianDurationRollOver :: CalendarDiffDays -> Day -> Day #
Add months (rolling over to next month), then add days
addGregorianDurationClip :: CalendarDiffDays -> Day -> Day #
Add months (clipped to last day), then add days
pattern YearMonthDay :: Year -> MonthOfYear -> DayOfMonth -> Day #
Bidirectional abstract constructor for the proleptic Gregorian calendar. Invalid values will be clipped to the correct range, month first, then day.
isLeapYear :: Year -> Bool #
Is this year a leap year according to the proleptic Gregorian calendar?
type MonthOfYear = Int #
Month of year, in range 1 (January) to 12 (December).
type DayOfMonth = Int #
Day of month, in range 1 to 31.
The Modified Julian Day is a standard count of days, with zero being the day 1858-11-17.
Constructors
| ModifiedJulianDay | |
Fields | |
Instances
| FromJSON Day | |
Defined in Data.Aeson.Types.FromJSON | |
| FromJSONKey Day | |
Defined in Data.Aeson.Types.FromJSON | |
| ToJSON Day | |
| ToJSONKey Day | |
Defined in Data.Aeson.Types.ToJSON | |
| Data Day | |
Defined in Data.Time.Calendar.Days Methods gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b) -> (forall g. g -> c g) -> Day -> c Day # gunfold :: (forall b r. Data b => c (b -> r) -> c r) -> (forall r. r -> c r) -> Constr -> c Day # dataTypeOf :: Day -> DataType # dataCast1 :: Typeable t => (forall d. Data d => c (t d)) -> Maybe (c Day) # dataCast2 :: Typeable t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c Day) # gmapT :: (forall b. Data b => b -> b) -> Day -> Day # gmapQl :: (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> Day -> r # gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> Day -> r # gmapQ :: (forall d. Data d => d -> u) -> Day -> [u] # gmapQi :: Int -> (forall d. Data d => d -> u) -> Day -> u # gmapM :: Monad m => (forall d. Data d => d -> m d) -> Day -> m Day # gmapMp :: MonadPlus m => (forall d. Data d => d -> m d) -> Day -> m Day # gmapMo :: MonadPlus m => (forall d. Data d => d -> m d) -> Day -> m Day # | |
| Enum Day | |
| Ix Day | |
| NFData Day | |
Defined in Data.Time.Calendar.Days | |
| Eq Day | |
| Ord Day | |
data CalendarDiffDays #
Constructors
| CalendarDiffDays | |
Instances
scaleCalendarDiffDays :: Integer -> CalendarDiffDays -> CalendarDiffDays #
Scale by a factor. Note that scaleCalendarDiffDays (-1) will not perfectly invert a duration, due to variable month lengths.
printHelpForTopic :: Tool -> Maybe Topic -> IO () Source #
Print plain text help for this tool. Takes an optional topic argument for convenience but it is currently ignored.
runPagerForTopic :: Tool -> Maybe Topic -> IO () Source #
Display plain text help for this tool, scrolled to the given topic if provided, using the given pager executable. Note when a topic is provided we ignore the provided pager and use the "less" executable in $PATH.
runManForTopic :: Tool -> Maybe Topic -> IO () Source #
Display a man page for this tool, scrolled to the given topic if provided, using the "man" executable in $PATH. Note when a topic is provided we force man to use the "less" executable in $PATH, ignoring $MANPAGER and $PAGER.
runInfoForTopic :: Tool -> Maybe Topic -> IO () Source #
Display an info manual for this topic, opened at the given topic if provided, using the "info" executable in $PATH.
type VersionString = String Source #
type PackageVersion = String Source #
type ProgramName = String Source #
packageversion :: PackageVersion Source #
The "1.32.1" string defined with -D in this package's package.yaml/.cabal file (by Shake setversion), if any. Normally a dotted number string with 1-3 components.
packagemajorversion :: PackageVersion Source #
Just the first 1-2 components of packageversion.
progname :: ProgramName Source #
The name of this package's main executable.
versionStringWith :: Either String GitInfo -> ProgramName -> PackageVersion -> VersionString Source #
Given possible git state info from the build directory (or an error message, which is ignored), the name of a program (executable) in the currently building package, and the package's version, make a complete version string. Here is the logic:
- Program name, OS and architecture are always shown.
- The package version is always shown.
- If there is git info at build time, the latest commit hash and commit date are shown, and (TODO, requires githash to use -uno for giDirty): if the working copy has uncommitted changes a + sign is appended.
- (TODO, requires adding --match support to githash: If there are tags matching THISPKG-[0-9]*, the latest one is used to calculate patch level (number of commits since tag), and if non-zero, it and the branch name are shown.)
Some example outputs:
- A homebrew binary, not built in git repo: hledger-ui 1.24, mac-aarch64
- A CI release build, built in git repo at release tag: hledger-ui 1.24.1-g455b35293-20211210, mac-x86_64
- (TODO) A dev build, built in git repo: hledger-ui 1.24.1+1-g4abd8ef10-20211210 (1.24-branch), mac-x86_64
This function requires git log to show the default (rfc2822-style) date format, so that must not be overridden by a log.date git config variable.
Command line options, used in the hledger package and above.
This is the "opts" used throughout hledger CLI code.
representing the options and arguments that were provided at
startup on the command-line.
Constructors
| CliOpts | |
Fields
| |
Instances
type CommandDoc = String Source #
A command's documentation. Used both as part of CLI help, and as part of the hledger manual. See parseCommandDoc.
detailedversionflag :: Flag RawOpts Source #
A hidden flag just for the hledger executable.
inputflags :: [Flag RawOpts] Source #
Common input-related flags: --file, --rules-file, --alias...
reportflags :: [Flag RawOpts] Source #
Common report-related flags: --period, --cost, etc.
flattreeflags :: Bool -> [Flag RawOpts] Source #
Flags for selecting flat/tree mode, used for reports organised by account. With a True argument, shows some extra help about inclusive/exclusive amounts.
Common flags that are accepted but not shown in --help, such as --effective, --aux-date.
outputFormatFlag :: [String] -> Flag RawOpts Source #
Common output-related flags: --output-file, --output-format...
defMode :: Mode RawOpts Source #
An empty cmdargs mode to use as a template. Modes describe the top-level command, ie the program, or a subcommand, telling cmdargs how to parse a command line and how to generate the command's usage text.
defCommandMode :: [Name] -> Mode RawOpts Source #
A cmdargs mode suitable for a hledger built-in command with the given names (primary name + optional aliases). The usage message shows [QUERY] as argument.
addonCommandMode :: Name -> Mode RawOpts Source #
A cmdargs mode representing the hledger add-on command with the given name, providing hledger's common inputreportinghelp flags. Just used when invoking addons.
hledgerCommandMode :: CommandDoc -> [Flag RawOpts] -> [(String, [Flag RawOpts])] -> [Flag RawOpts] -> ([Arg RawOpts], Maybe (Arg RawOpts)) -> Mode RawOpts Source #
Build a cmdarg mode for a hledger command, from a help template and flag/argument specifications. Reduces boilerplate a little, though the complicated cmdargs flag and argument specs are still required.
showModeUsage :: Mode a -> String Source #
Get a mode's usage message as a nicely wrapped string.
topicForMode :: Mode a -> Topic Source #
Get the most appropriate documentation topic for a mode. Currently, that is either the hledger, hledger-ui or hledger-web manual.
withAliases :: String -> [String] -> String Source #
Add command aliases to the command's help string.
defcliopts :: CliOpts Source #
defaultWidth :: Int Source #
Default width for hledger console output, when not otherwise specified.
replaceNumericFlags :: [String] -> [String] Source #
Replace any numeric flags (eg -2) with their long form (--depth 2), as I'm guessing cmdargs doesn't support this directly.
rawOptsToCliOpts :: RawOpts -> IO CliOpts Source #
Parse raw option string values to the desired final data types. Any relative smart dates will be converted to fixed dates based on today's date. Parsing failures will raise an error. Also records the terminal width, if supported.
getHledgerCliOpts' :: Mode RawOpts -> [String] -> IO CliOpts Source #
A helper for addon commands: this parses options and arguments from the current command line using the given hledger-style cmdargs mode, and returns a CliOpts. Or, with --help or -h present, it prints long or short help, and exits the program. When --debug is present, also prints some debug output. Note this is not used by the main hledger executable.
The help texts are generated from the mode. Long help includes the full usage description generated by cmdargs (including all supported options), framed by whatever pre- and postamble text the mode specifies. It's intended that this forms a complete help document or manual.
Short help is a truncated version of the above: the preamble and the first part of the usage, up to the first line containing "flags:" (normally this marks the start of the common hledger flags); plus a mention of --help and the (presumed supported) common hledger options not displayed.
Tips: Empty lines in the pre/postamble are removed by cmdargs; add a space character to preserve them.
journalFilePathFromOpts :: CliOpts -> IO [String] Source #
Get the (tilde-expanded, absolute) journal file path from 1. options, 2. an environment variable, or 3. the default. Actually, returns one or more file paths. There will be more than one if multiple -f options were provided. File paths can have a READER: prefix naming a reader/data format.
outputFileFromOpts :: CliOpts -> IO (Maybe FilePath) Source #
Get the expanded, absolute output file path specified by an -o/--output-file options, or nothing, meaning stdout.
outputFormats :: [String] Source #
All the output formats known by any command, for outputFormatFromOpts. To automatically infer it from -o/--output-file, it needs to be listed here.
outputFormatFromOpts :: CliOpts -> String Source #
Get the output format from the --output-format option, otherwise from a recognised file extension in the --output-file option, otherwise the default (txt).
rulesFilePathFromOpts :: CliOpts -> IO (Maybe FilePath) Source #
Get the (tilde-expanded) rules file path from options, if any.
registerWidthsFromOpts :: CliOpts -> (Int, Maybe Int) Source #
Get the width in characters to use for the register command's console output,
and also the description column width if specified (following the main width, comma-separated).
The widths will be as follows:
no --width flag - overall width is the available width (COLUMNS, or posix terminal width, or 80); description width is unspecified (auto)
--width W - overall width is W, description width is auto
--width W,D - overall width is W, description width is D
Will raise a parse error for a malformed --width argument.
hledgerAddons :: IO [String] Source #
Get the sorted unique canonical names of hledger addon commands found in the current user's PATH. These are used in command line parsing and to display the commands list.
Canonical addon names are the filenames of hledger-* executables in PATH, without the "hledger-" prefix, and without the file extension except when it's needed for disambiguation (see below).
When there are exactly two versions of an executable (same base name, different extensions) that look like a source and compiled pair (one has .exe, .com, or no extension), the source version will be excluded (even if it happens to be newer). When there are three or more versions (or two versions that don't look like a source/compiled pair), they are all included, with file extensions intact.
hledgerExecutablesInPath :: IO [String] Source #
Get the sorted unique filenames of all hledger-* executables in the current user's PATH. These are files in any of the PATH directories, named hledger-*, with either no extension (and no periods in the name) or one of the addonExtensions. We do not currently filter out non-file objects or files without execute permission.
likelyExecutablesInPath :: IO [String] Source #
Get all sorted unique filenames in the current user's PATH. We do not currently filter out non-file objects or files without execute permission.
class HasCliOpts c where Source #
Minimal complete definition
Methods
cliOpts :: Lens' c CliOpts Source #
available_width :: Lens' c Int Source #
command :: Lens' c String Source #
debug__ :: Lens' c Int Source #
file__ :: Lens' c [FilePath] Source #
inputopts :: Lens' c InputOpts Source #
no_new_accounts :: Lens' c Bool Source #
output_file :: Lens' c (Maybe FilePath) Source #
output_format :: Lens' c (Maybe String) Source #
progstarttime :: Lens' c POSIXTime Source #
rawopts__ :: Lens' c RawOpts Source #
reportspec :: Lens' c ReportSpec Source #
Instances
| HasCliOpts CliOpts Source # | |
Defined in Hledger.Cli.CliOptions Methods cliOpts :: Lens' CliOpts CliOpts Source # available_width :: Lens' CliOpts Int Source # command :: Lens' CliOpts String Source # debug__ :: Lens' CliOpts Int Source # file__ :: Lens' CliOpts [FilePath] Source # inputopts :: Lens' CliOpts InputOpts Source # no_new_accounts :: Lens' CliOpts Bool Source # output_file :: Lens' CliOpts (Maybe FilePath) Source # output_format :: Lens' CliOpts (Maybe String) Source # progstarttime :: Lens' CliOpts POSIXTime Source # rawopts__ :: Lens' CliOpts RawOpts Source # | |
ensureDebugHasArg :: (Eq (t Char), IsString (t Char), Foldable t) => [t Char] -> [t Char] Source #
Convert an argument-less --debug flag to --debug=1 in the given arguments list. Used by hledgeruiweb to make their command line parsing easier somehow.
unsupportedOutputFormatError :: String -> String Source #
Standard error message for a bad output format specified with -O/-o.
withJournalDo :: CliOpts -> (Journal -> IO a) -> IO a Source #
Parse the user's specified journal file(s) as a Journal, maybe apply some transformations according to options, and run a hledger command with it. Or, throw an error.
journalTransform :: CliOpts -> Journal -> Journal Source #
Apply some extra post-parse transformations to the journal, if specified by options. These happen after journal validation, but before report calculation. They include:
- adding forecast transactions (--forecast)
- pivoting account names (--pivot)
- anonymising (--anonymise).
This will return an error message if the query in any auto posting rule fails to parse, or the generated transactions are not balanced.
pivotByOpts :: CliOpts -> Journal -> Journal Source #
Apply the pivot transformation on a journal, if option is present.
anonymiseByOpts :: CliOpts -> Journal -> Journal Source #
Apply the anonymisation transformation on a journal, if option is present
writeOutput :: CliOpts -> String -> IO () Source #
Write some output to stdout or to a file selected by --output-file. If the file exists it will be overwritten.
writeOutputLazyText :: CliOpts -> Text -> IO () Source #
Write some output to stdout or to a file selected by --output-file. If the file exists it will be overwritten. This function operates on Lazy Text values.
journalReloadIfChanged :: CliOpts -> Day -> Journal -> ExceptT String IO (Journal, Bool) Source #
Re-read the option-specified journal file(s), but only if any of them has changed since last read. (If the file is standard input, this will either do nothing or give an error, not tested yet). Returns a journal or error message, and a flag indicating whether it was re-read or not. Like withJournalDo and journalReload, reads the full journal, without filtering.
journalReload :: CliOpts -> ExceptT String IO Journal Source #
Re-read the journal file(s) specified by options, applying any transformations specified by options. Or return an error string. Reads the full journal, without filtering.
journalFileIsNewer :: Journal -> FilePath -> IO Bool Source #
Has the specified file changed since the journal was last read ? Typically this is one of the journal's journalFilePaths. These are not always real files, so the file's existence is tested first; for non-files the answer is always no.
openBrowserOn :: String -> IO ExitCode Source #
Attempt to open a web browser on the given url, all platforms.
writeFileWithBackupIfChanged :: FilePath -> Text -> IO Bool Source #
Back up this file with a (incrementing) numbered suffix then overwrite it with this new text, or give an error, but only if the text is different from the current file contents, and return a flag indicating whether we did anything.
The given text should have unix line endings (n); the existing file content will be normalised to unix line endings before comparing the two. If the file is overwritten, the new file will have the current system's native line endings (n on unix, rn on windows). This could be different from the file's previous line endings, if working with a DOS file on unix or vice-versa.
writeFileWithBackup :: FilePath -> String -> IO () Source #
Back up this file with a (incrementing) numbered suffix, then overwrite it with this new text, or give an error.
journalSimilarTransaction :: CliOpts -> Journal -> Text -> Maybe Transaction Source #
postingsOrTransactionsReportAsText :: Bool -> CliOpts -> (Int -> Int -> (a, [WideBuilder], [WideBuilder]) -> Builder) -> (a -> MixedAmount) -> (a -> MixedAmount) -> [a] -> Builder Source #
Render a PostingsReport or AccountTransactionsReport as Text,
determining the appropriate starting widths and increasing as necessary.
postingsReportAsText :: CliOpts -> PostingsReport -> Text Source #
Render a register report as plain text suitable for console output.
postingsReportItemAsText :: CliOpts -> Int -> Int -> (PostingsReportItem, [WideBuilder], [WideBuilder]) -> Builder Source #
Render one register report line item as plain text. Layout is like so:
width (specified, terminal width, or 80) --------------------
date (10) description account amount (12) balance (12)
DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA
If description's width is specified, account will use the remaining space.
Otherwise, description and account divide up the space equally.
With a report interval, the layout is like so:
width (specified, terminal width, or 80) --------------------
date (21) account amount (12) balance (12)
DDDDDDDDDDDDDDDDDDDDD aaaaaaaaaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA
date and description are shown for the first posting of a transaction only.
Returns a string which can be multi-line, eg if the running balance has multiple commodities. Does not yet support formatting control like balance reports.
Also returns the natural width (without padding) of the amount and balance fields.
transactionWithMostlyOriginalPostings :: Transaction -> Transaction Source #
Replace this transaction's postings with the original postings if any, but keep the current possibly rewritten account names, and the inferred values of any auto postings. This is mainly for showing transactions with the amounts in their original journal format.
pricesmode :: Mode RawOpts Source #
payeesmode :: Mode RawOpts Source #
Command line options for this command.
help' :: CliOpts -> Journal -> IO () Source #
Display the hledger manual in various formats. You can select a docs viewer with one of the `--info`, `--man`, `--pager` flags. Otherwise it will use the first available of: info, man, $PAGER, less, stdout (and always stdout if output is non-interactive).
descriptionsmode :: Mode RawOpts Source #
Command line options for this command.
commoditiesmode :: Mode RawOpts Source #
Command line options for this command.
balancemode :: Mode RawOpts Source #
Command line options for this command.
balanceReportAsCsv :: ReportOpts -> BalanceReport -> CSV Source #
Render a single-column balance report as CSV.
balanceReportAsText :: ReportOpts -> BalanceReport -> Builder Source #
Render a single-column balance report as plain text.
balanceReportItemAsText :: ReportOpts -> BalanceReportItem -> (Builder, [Int]) Source #
Render one balance report line item as plain text suitable for console output (or whatever string format is specified). Note, prices will not be rendered, and differently-priced quantities of the same commodity will appear merged. The output will be one or more lines depending on the format and number of commodities.
multiBalanceReportAsCsv :: ReportOpts -> MultiBalanceReport -> CSV Source #
Render a multi-column balance report as CSV. The CSV will always include the initial headings row, and will include the final totals row unless --no-total is set.
multiBalanceReportAsHtml :: ReportOpts -> MultiBalanceReport -> Html () Source #
Render a multi-column balance report as HTML.
multiBalanceReportHtmlRows :: ReportOpts -> MultiBalanceReport -> (Html (), [Html ()], [Html ()]) Source #
Render the HTML table rows for a MultiBalanceReport. Returns the heading row, 0 or more body rows, and the totals row if enabled.
multiBalanceReportHtmlFootRow :: ReportOpts -> [Text] -> Html () Source #
Render one MultiBalanceReport totals row as a HTML table row.
multiBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> Text Source #
Render a multi-column balance report as plain text suitable for console output.
balanceReportAsTable :: ReportOpts -> MultiBalanceReport -> Table Text Text WideBuilder Source #
Build a Table from a multi-column balance report.
multiBalanceRowAsCsvText :: ReportOpts -> [DateSpan] -> PeriodicReportRow a MixedAmount -> [[Text]] Source #
multiBalanceRowAsTableText :: ReportOpts -> PeriodicReportRow a MixedAmount -> [[WideBuilder]] Source #
data CompoundBalanceCommandSpec Source #
Description of a compound balance report command, from which we generate the command's cmdargs mode and IO action. A compound balance report command shows one or more sections/subreports, each with its own title and subtotals row, in a certain order, plus a grand totals row if there's more than one section. Examples are the balancesheet, cashflow and incomestatement commands.
Compound balance reports do sign normalisation: they show all account balances as normally positive, unlike the ordinary BalanceReport and most hledger commands which show incomeliabilityequity balances as normally negative. Each subreport specifies the normal sign of its amounts, and whether it should be added to or subtracted from the grand total.
Constructors
| CompoundBalanceCommandSpec | |
Fields
| |
compoundBalanceCommandMode :: CompoundBalanceCommandSpec -> Mode RawOpts Source #
Generate a cmdargs option-parsing mode from a compound balance command specification.
compoundBalanceCommand :: CompoundBalanceCommandSpec -> CliOpts -> Journal -> IO () Source #
Generate a runnable command from a compound balance command specification.
aregister :: CliOpts -> Journal -> IO () Source #
Print an account register report for a specified account.
add :: CliOpts -> Journal -> IO () Source #
Read multiple transactions from the console, prompting for each field, and append them to the journal file. If the journal came from stdin, this command has no effect.
journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal Source #
Append this transaction to the journal's file and transaction list.
appendToJournalFileOrStdout :: FilePath -> Text -> IO () Source #
Append a string, typically one or more transactions, to a journal file, or if the file is "-", dump it to stdout. Tries to avoid excess whitespace.
XXX This writes unix line endings (n), some at least, even if the file uses dos line endings (rn), which could leave mixed line endings in the file. See also writeFileWithBackupIfChanged.
importmode :: Mode RawOpts Source #
activity :: CliOpts -> Journal -> IO () Source #
Print a bar chart of number of postings per report interval.
showHistogram :: ReportSpec -> Journal -> String Source #
printDayWith :: (PrintfArg t1, PrintfType t2) => (t3 -> t1) -> (DateSpan, t3) -> t2 Source #
accountsmode :: Mode RawOpts Source #
Command line options for this command.
builtinCommands :: [(Mode RawOpts, CliOpts -> Journal -> IO ())] Source #
The cmdargs subcommand mode (for command-line parsing) and IO action (for doing the command's work) for each builtin command. Command actions take parsed CLI options and a (lazy) finalised journal.
knownCommands :: [String] Source #
Canonical names of all commands which have a slot in the commands list, in alphabetical order. These include the builtin commands and the known addon commands.
knownAddonCommands :: [String] Source #
Canonical names of the known addon commands which have a slot in the commands list, in alphabetical order.
builtinCommandNames :: [String] Source #
All names and aliases of the builtin commands.
findBuiltinCommand :: String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()) Source #
Look up a builtin command's mode and action by exact command name or alias.
printCommandsList :: String -> [String] -> IO () Source #
Print the commands list, with a pager if appropriate, customising the commandsList template above with the given version string and the installed addons. Uninstalled known addons will be removed from the list, installed known addons will have the + prefix removed, and installed unknown addons will be added under Misc.
testcmd :: CliOpts -> Journal -> IO () Source #
The test command, which runs the hledger and hledger-lib packages' unit tests. This command also accepts tasty test runner options, written after a -- (double hyphen).
Unlike most hledger commands, this one does not read the user's journal.
A Journal argument remains in the type signature, but it should
not be used (and would raise an error).