HORIZON HASKELLDocslts/ghc-10.0.x8c2f8e82026-10-19Search names, modules, packages, or :: a typeCtrl K

GHC 10.0.0.20260917 · lts/ghc-10.0.x · 8c2f8e8 · 2026-10-19

Modulehledger-1.52.4GHC2021

Hledger.Cli.Script

A convenient module to import in hledger scripts, aiming to provide the most useful imports and reduce boilerplate. |

  • 210 types
  • 23 classes
  • 1909 values
  • Packagehledger-1.52.4
  • Exports2179
  • LanguageGHC2021
  • LicenceGPL-3.0-or-later
  • SourceScript.hs
valueoptional :: 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:

Example1 expression
import Control.Monad.Except
Example2 expressions
canFail = throwError "it failed" :: Except String Intfinal = return 42                :: Except String Int

Can be combined by allowing the first function to fail:

Example1 expression
runExcept $ canFail *> finalLeft "it failed"
Example1 expression
runExcept $ optional canFail *> finalRight 42
valueforkFinally :: 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_then

This function is useful for informing the parent when a child terminates, for example.

valuethreadWaitRead :: 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.

valuethreadWaitReadSTM :: 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.

valuethreadWaitWrite :: 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.

valuethreadWaitWriteSTM :: 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.

valuedupChan :: 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.)

valuegetChanContents :: Chan a -> IO [a]
#

Return a lazy list representing the contents of the supplied Chan, much like GHC.Internal.System.IO.hGetContents.

valuereadChan :: Chan a -> IO a
#

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.

valuenewQSem :: Int -> IO QSem
#

Build a new QSem with a supplied initial quantity. The initial quantity must be at least 0.

valuenewQSemN :: Int -> IO QSemN
#

Build a new QSemN with a supplied initial quantity. The initial quantity must be at least 0.

valuedigitToInt :: 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:

Example1 expression
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.

Example2 expressions
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:

Example2 expressions
digitToInt 'G'*** Exception: Char.digitToInt: not a digit 'G'digitToInt '♥'*** Exception: Char.digitToInt: not a digit '\9829'
valueisLetter :: Char -> Bool
#

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:

Example7 expressions
isLetter 'a'TrueisLetter 'A'TrueisLetter 'λ'TrueisLetter '0'FalseisLetter '%'FalseisLetter '♥'FalseisLetter '\31'False

Ensure that isLetter and isAlpha are equivalent.

Example4 expressions
let chars = [(chr 0)..]let letters = map isLetter charslet alphas = map isAlpha charsletters == alphasTrue
valueisMark :: Char -> Bool
#

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:

Example2 expressions
isMark 'a'FalseisMark '0'False

Combining marks such as accent characters usually need to follow another character before they become printable:

Example1 expression
map isMark "ò"[False,True]

Puns are not necessarily supported:

Example1 expression
isMark '✓'False
valueisNumber :: Char -> Bool
#

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:

Example3 expressions
isNumber 'a'FalseisNumber '%'FalseisNumber '3'True

ASCII '0' through '9' are all numbers:

Example1 expression
and $ map isNumber ['0'..'9']True

Unicode Roman numerals are "numbers" as well:

Example1 expression
isNumber 'Ⅸ'True
valueisSeparator :: 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:

Example3 expressions
isSeparator 'a'FalseisSeparator '6'FalseisSeparator ' 'True

Warning: newlines and tab characters are not considered separators.

Example2 expressions
isSeparator '\n'FalseisSeparator '\t'False

But some more exotic characters are (like HTML's  ):

Example1 expression
isSeparator '\160'True
valuecompareLength :: [a] -> Int -> Ordering
#

Use compareLength xs n as a safer and faster alternative to compare (length xs) n. Similarly, it's better to write compareLength xs 10 == LT instead of length xs < 10.

While length would force and traverse the entire spine of xs (which could even diverge if xs is infinite), compareLength traverses at most n elements to determine its result.

Example7 expressions
compareLength [] 0EQcompareLength [] 1LTcompareLength ['a'] 1EQcompareLength ['a', 'b'] 1GTcompareLength [0..] 100GTcompareLength undefined (-1)GTcompareLength ('a' : undefined) 0GT
valueinits1 :: [a] -> [NonEmpty a]
#

The inits1 function returns all non-empty initial segments of the argument, shortest first.

Laziness

Note that inits1 has the following strictness property: inits1 (xs ++ _|_) = inits1 xs ++ _|_

In particular, inits1 _|_ = _|_

Examples
Example1 expression
inits1 "abc"['a' :| "",'a' :| "b",'a' :| "bc"]
Example1 expression
inits1 [][]

inits1 is productive on infinite lists:

Example1 expression
take 3 $ inits1 [1..][1 :| [],1 :| [2],1 :| [2,3]]
valuenubOrd :: Ord a => [a] -> [a]
#

Same as nub, but asymptotically faster, taking only O(n log d) time, where d is the number of distinct elements in the list.

valuenubOrdBy :: (a -> a -> Ordering) -> [a] -> [a]
#

Overloaded version of nubOrd.

The supplied comparison relation is supposed to be reflexive, transitive and antisymmetric, same as for sortBy.

valuetails1 :: [a] -> [NonEmpty a]
#

\mathcal{O}(n). The tails1 function returns all non-empty final segments of the argument, longest first.

Laziness

Note that tails1 has the following strictness property: tails1 _|_ = _|_

Example1 expression
tails1 undefined*** Exception: Prelude.undefined
Example1 expression
drop 1 (tails1 [undefined, 1, 2])[1 :| [2],2 :| []]
Examples
Example1 expression
tails1 "abc"['a' :| "bc",'b' :| "c",'c' :| ""]
Example1 expression
tails1 [1, 2, 3][1 :| [2,3],2 :| [3],3 :| []]
Example1 expression
tails1 [][]
valueexitWith :: 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 an Exception, it 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 ExitCode as normal, but the exception will not cause the process itself to exit.

valueerrorBadArgument :: a
#

Calls perror to indicate that there is a type error or similar in the given argument.

valueperror :: String -> a
#

Raises an error with a printf-specific prefix on the message string.

valueprintf :: PrintfType r => String -> r
#

Format a variable number of arguments with the C-style formatting string.

Example1 expression
printf "%s, %d, %.4f" "hello" 123 pihello, 123, 3.1416

The return value is either String or (IO a) (which should be (IO ()), but Haskell's type system makes this hard).

The format string consists of ordinary characters and conversion specifications, which specify how to format one of the arguments to printf in the output string. A format specification is introduced by the % character; this character can be self-escaped into the format string using %%. A format specification ends with a format character that provides the primary information about how to format the value. The rest of the conversion specification is optional. In order, one may have flag characters, a width specifier, a precision specifier, and type-specific modifier characters.

Unlike C printf(3), the formatting of this printf is driven by the argument type; formatting is type specific. The types formatted by printf "out of the box" are:

printf is also extensible to support other types: see below.

A conversion specification begins with the character %, followed by zero or more of the following flags:

-      left adjust (default is right adjust)
+      always use a sign (+ or -) for signed conversions
space  leading space for positive numbers in signed conversions
0      pad with zeros rather than spaces
#      use an \"alternate form\": see below

When both flags are given, - overrides 0 and + overrides space. A negative width specifier in a * conversion is treated as positive but implies the left adjust flag.

The "alternate form" for unsigned radix conversions is as in C printf(3):

%o           prefix with a leading 0 if needed
%x           prefix with a leading 0x if nonzero
%X           prefix with a leading 0X if nonzero
%b           prefix with a leading 0b if nonzero
%[eEfFgG]    ensure that the number contains a decimal point

Any flags are followed optionally by a field width:

num    field width
*      as num, but taken from argument list

The field width is a minimum, not a maximum: it will be expanded as needed to avoid mutilating a value.

Any field width is followed optionally by a precision:

.num   precision
.      same as .0
.*     as num, but taken from argument list

Negative precision is taken as 0. The meaning of the precision depends on the conversion type.

Integral    minimum number of digits to show
RealFloat   number of digits after the decimal point
String      maximum number of characters

The precision for Integral types is accomplished by zero-padding. If both precision and zero-pad are given for an Integral field, the zero-pad is ignored.

Any precision is followed optionally for Integral types by a width modifier; the only use of this modifier being to set the implicit size of the operand for conversion of a negative operand to unsigned:

hh     Int8
h      Int16
l      Int32
ll     Int64
L      Int64

The specification ends with a format character:

c      character               Integral
d      decimal                 Integral
o      octal                   Integral
x      hexadecimal             Integral
X      hexadecimal             Integral
b      binary                  Integral
u      unsigned decimal        Integral
f      floating point          RealFloat
F      floating point          RealFloat
g      general format float    RealFloat
G      general format float    RealFloat
e      exponent format float   RealFloat
E      exponent format float   RealFloat
s      string                  String
v      default format          any type

The "%v" specifier is provided for all built-in types, and should be provided for user-defined type formatters as well. It picks a "best" representation for the given type. For the built-in types the "%v" specifier is converted as follows:

c      Char
u      other unsigned Integral
d      other signed Integral
g      RealFloat
s      String

Mismatch between the argument types and the format string, as well as any other syntactic or semantic errors in the format string, will cause an exception to be thrown at runtime.

Note that the formatting for RealFloat types is currently a bit different from that of C printf(3), conforming instead to showEFloat, showFFloat and showGFloat (and their alternate versions showFFloatAlt and showGFloatAlt). This is hard to fix: the fixed versions would format in a backward-incompatible way. In any case the Haskell behavior is generally more sensible than the C behavior. A brief summary of some key differences:

  • Haskell printf never uses the default "6-digit" precision used by C printf.

  • Haskell printf treats the "precision" specifier as indicating the number of digits after the decimal point.

  • Haskell printf prints the exponent of e-format numbers without a gratuitous plus sign, and with the minimum possible number of digits.

  • Haskell printf will place a zero after a decimal point when possible.

valuevFmt :: 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".

valueflagHelpFormat :: (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
valueflagVersion :: (a -> a) -> Flag a
#

Create a version flag triggered by -V/--version.

valueprocessArgs :: Mode a -> IO a
#

Process the flags obtained by getArgs and expandArgsAt 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 process. This function makes use of the following environment variables:

  • $CMDARGS_COMPLETE - causes the program to produce completions using complete, then exit. Completions are based on the result of getArgs, 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.

valueprocessValue :: Mode a -> [String] -> a
#

Process a list of flags (usually obtained from getArgs and expandArgsAt) with a mode. Throws an error if the command line fails to parse, or returns the associated value. Implemeneted in terms of process. 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.

valuecomplete
  1. :: Mode a

    Mode specifying which arguments are allowed

  2. -> [String]

    Arguments the user has already typed

  3. -> (Int, Int)

    0-based index of the argument they are currently on, and the position in that argument

  4. -> [Complete]
#

Given a current state, return the set of commands you could type now, in preference order.

valueexpandArgsAt :: [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 --.

valueprocess :: 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.

valuejoinArgs :: [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"

valueflagArg :: Update a -> FlagHelp -> Arg a
#

Create an argument flag, with an update function and the type of the argument.

valueflagBool :: [Name] -> (Bool -> a -> a) -> Help -> Flag a
#

Create a boolean flag, with a list of flag names, an update function and some help text.

valueflagNone :: [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.

valueflagOpt :: 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.

valueflagReq :: [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.

valuemode :: 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.

valuemodeEmpty :: a -> Mode a
#

Create an empty mode specifying only modeValue. All other fields will usually be populated using record updates.

valuemodes :: 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.

valueremap2 :: Remap m => (a -> b) -> (b -> a) -> m a -> m b
#

Restricted version of remap where the values are isomorphic.

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 System.FilePath.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.

valuecopyFile
  1. :: FilePath

    Source filename

  2. -> FilePath

    Destination filename

  3. -> IO ()
#

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.

valuecopyFileWithMetadata
  1. :: FilePath

    Source file

  2. -> FilePath

    Destination file

  3. -> IO ()
#

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.

valuecopyPermissions :: 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.

valuecreateDirectory :: FilePath -> IO ()
#

createDirectory dir creates a new directory dir which is initially empty, or as near to empty as the operating system allows.

The operation may fail with:

  • isPermissionError The process has insufficient privileges to perform the operation. [EROFS, EACCES]

  • isAlreadyExistsError The operand refers to a directory that already exists. [EEXIST]

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument The operand is not a valid directory name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError There is no path to the directory. [ENOENT, ENOTDIR]

  • System.IO.isFullError Insufficient resources (virtual memory, process file descriptors, physical disk space, etc.) are available to perform the operation. [EDQUOT, ENOSPC, ENOMEM, EMLINK]

  • InappropriateType The path refers to an existing non-directory object. [EEXIST]

valuedoesPathExist :: 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.

valueexeExtension :: String
#

Filename extension for executable files (including the dot if any) (usually "" on POSIX systems and ".exe" on Windows or OS/2).

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 findExecutable name corresponds to the program that would be executed by createProcess 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.

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.

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.

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.

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 </> name exists and satisfies the predicate. If so, dir </> name 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.

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.

Obtain the time at which the file or directory was last accessed.

The operation may fail with:

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.

valuegetAppUserDataDirectory
  1. :: FilePath

    a relative path that is appended to the path

  2. -> IO FilePath
#

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:

  • UnsupportedOperation The operating system has no notion of application-specific data directory.

  • isDoesNotExistError The home directory for the current user does not exist, or cannot be found.

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:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • isDoesNotExistError There is no path referring to the working directory. [EPERM, ENOENT, ESTALE...]

  • isPermissionError The process has insufficient privileges to perform the operation. [EACCES]

  • System.IO.isFullError Insufficient resources are available to perform the operation.

  • UnsupportedOperation The operating system has no notion of current working directory.

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_r using the UID of the current process' user. This basically reads the /etc/passwd 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:

  • UnsupportedOperation The operating system has no notion of home directory.

  • isDoesNotExistError The home directory for the current user does not exist, or cannot be found.

Obtain the time at which the file or directory was last modified.

The operation may fail with:

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.

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:

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.

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:

  • UnsupportedOperation The operating system has no notion of temporary directory.

The function doesn't verify whether the path exists.

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:

  • UnsupportedOperation The operating system has no notion of document directory.

  • isDoesNotExistError The document directory for the current user does not exist, or cannot be found.

valuegetXdgDirectory
  1. :: XdgDirectory

    which special directory

  2. -> FilePath

    a relative path that is appended to the path; if empty, the base path is returned

  3. -> 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.

listDirectory dir returns a list of all entries in dir without the special entries (. and ..).

The operation may fail with:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument The operand is not a valid directory name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError The directory does not exist. [ENOENT, ENOTDIR]

  • isPermissionError The process has insufficient privileges to perform the operation. [EACCES]

  • System.IO.isFullError Insufficient resources are available to perform the operation. [EMFILE, ENFILE]

  • InappropriateType The path refers to an existing non-directory object. [ENOTDIR]

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.

valueremoveDirectory :: FilePath -> IO ()
#

removeDirectory dir 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).

The operation may fail with:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument The operand is not a valid directory name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError The directory does not exist. [ENOENT, ENOTDIR]

  • isPermissionError The process has insufficient privileges to perform the operation. [EROFS, EACCES, EPERM]

  • UnsatisfiedConstraints Implementation-dependent constraints are not satisfied. [EBUSY, ENOTEMPTY, EEXIST]

  • UnsupportedOperation The implementation does not support removal in this situation. [EINVAL]

  • InappropriateType The operand refers to an existing non-directory object. [ENOTDIR]

valueremoveFile :: 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:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument The operand is not a valid file name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError The file does not exist. [ENOENT, ENOTDIR]

  • isPermissionError The process has insufficient privileges to perform the operation. [EROFS, EACCES, EPERM]

  • UnsatisfiedConstraints Implementation-dependent constraints are not satisfied. [EBUSY]

  • InappropriateType The operand refers to an existing directory. [EPERM, EINVAL]

valueremovePathForcibly :: 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.

valuerenameDirectory :: FilePath -> FilePath -> IO ()
#

renameDirectory old new 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 removeDirectory. 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:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument Either operand is not a valid directory name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError The original directory does not exist, or there is no path to the target. [ENOENT, ENOTDIR]

  • isPermissionError The process has insufficient privileges to perform the operation. [EROFS, EACCES, EPERM]

  • System.IO.isFullError Insufficient resources are available to perform the operation. [EDQUOT, ENOSPC, ENOMEM, EMLINK]

  • UnsatisfiedConstraints Implementation-dependent constraints are not satisfied. [EBUSY, ENOTEMPTY, EEXIST]

  • UnsupportedOperation The implementation does not support renaming in this situation. [EINVAL, EXDEV]

  • InappropriateType Either path refers to an existing non-directory object. [ENOTDIR, EISDIR]

valuerenameFile :: FilePath -> FilePath -> IO ()
#

renameFile old new 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. On Windows, this does not support renaming across different physical devices; if you are looking to do so, consider using copyFileWithMetadata and removeFile.

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:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument Either operand is not a valid file name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError The original file does not exist, or there is no path to the target. [ENOENT, ENOTDIR]

  • isPermissionError The process has insufficient privileges to perform the operation. [EROFS, EACCES, EPERM]

  • System.IO.isFullError Insufficient resources are available to perform the operation. [EDQUOT, ENOSPC, ENOMEM, EMLINK]

  • UnsatisfiedConstraints Implementation-dependent constraints are not satisfied. [EBUSY]

  • UnsupportedOperation The implementation does not support renaming in this situation. [EXDEV]

  • InappropriateType Either path refers to an existing directory. [ENOTDIR, EISDIR, EINVAL, EEXIST, ENOTEMPTY]

valuerenamePath
  1. :: FilePath

    Old path

  2. -> FilePath

    New path

  3. -> IO ()
#

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:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument Either operand is not a valid file name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError The original file does not exist, or there is no path to the target. [ENOENT, ENOTDIR]

  • isPermissionError The process has insufficient privileges to perform the operation. [EROFS, EACCES, EPERM]

  • System.IO.isFullError Insufficient resources are available to perform the operation. [EDQUOT, ENOSPC, ENOMEM, EMLINK]

  • UnsatisfiedConstraints Implementation-dependent constraints are not satisfied. [EBUSY]

  • UnsupportedOperation The implementation does not support renaming in this situation. [EXDEV]

  • InappropriateType Either 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]

valuesetAccessTime :: FilePath -> UTCTime -> IO ()
#

Change the time at which the file or directory was last accessed.

The operation may fail with:

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 where utimensat is supported, the access time is set atomically with nanosecond precision.

  • If compiled against a version of unix prior to 2.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.

valuesetCurrentDirectory :: 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:

  • HardwareFault A physical I/O error has occurred. [EIO]

  • InvalidArgument The operand is not a valid directory name. [ENAMETOOLONG, ELOOP]

  • isDoesNotExistError The directory does not exist. [ENOENT, ENOTDIR]

  • isPermissionError The process has insufficient privileges to perform the operation. [EACCES]

  • UnsupportedOperation The operating system has no notion of current working directory, or the working directory cannot be dynamically changed.

  • InappropriateType The path refers to an existing non-directory object. [ENOTDIR]

valuesetModificationTime :: FilePath -> UTCTime -> IO ()
#

Change the time at which the file or directory was last modified.

The operation may fail with:

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 where utimensat is supported, the modification time is set atomically with nanosecond precision.

  • If compiled against a version of unix prior to 2.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.

valuesetPermissions :: 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:

valuecharWidth :: Char -> Int
#

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.

value(-<.>) :: FilePath -> String -> FilePath
#

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"
value(<.>) :: FilePath -> String -> FilePath
#

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"
value(</>) :: FilePath -> FilePath -> FilePath
#

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 </> file) will access the same file as 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` x

Combined:

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"

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"

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/"

Remove last extension, and the "." preceding it.

dropExtension "/directory/path.ext" == "/directory/path"
dropExtension x == fst (splitExtension x)

Drop all extensions.

dropExtensions "/directory/path.ext" == "/directory/path"
dropExtensions "file.tar.gz" == "file"
not $ hasExtension $ dropExtensions x
not $ any isExtSeparator $ takeFileName $ dropExtensions x

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)
isPrefixOf (takeDrive x) (dropFileName x)

Remove any trailing path separators

dropTrailingPathSeparator "file/test/" == "file/test"
          dropTrailingPathSeparator "/" == "/"
Windows:  dropTrailingPathSeparator "\\" == "\\"
Posix:    not (hasTrailingPathSeparator (dropTrailingPathSeparator x)) || isDrive x

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:/")
valuehasDrive :: 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 "" == False
valuehasExtension :: FilePath -> Bool
#

Does the given filename have an extension?

hasExtension "/directory/path.ext" == True
hasExtension "/directory/path" == False
null (takeExtension x) == not (hasExtension x)

Is an item either a directory or the last character a path separator?

hasTrailingPathSeparator "test" == False
hasTrailingPathSeparator "test/" == True
valueisDrive :: FilePath -> Bool
#

Is an element a drive

Posix:   isDrive "/" == True
Posix:   isDrive "/foo" == False
Windows: isDrive "C:\\" == True
Windows: isDrive "C:\\foo" == False
         isDrive "" == False
valueisExtSeparator :: Char -> Bool
#

Is the character an extension character?

isExtSeparator a == (a == extSeparator)
valueisExtensionOf :: 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
valueisRelative :: 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."

valueisValid :: FilePath -> Bool
#

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" == True

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"
valuejoinPath :: [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"

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"
valuemakeValid :: 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"
valuenormalise :: 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"
valuepathSeparator :: 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
valuepathSeparators :: [Char]
#

The list of all possible separators.

Windows: pathSeparators == ['\\', '/']
Posix:   pathSeparators == ['/']
pathSeparator `elem` pathSeparators

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

Set the directory, keeping the filename the same.

replaceDirectory "root/file.ext" "/directory/" == "/directory/file.ext"
Valid x => replaceDirectory x (takeDirectory x) `equalFilePath` x

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

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"

Set the filename.

replaceFileName "/directory/other.txt" "file.ext" == "/directory/file.ext"
Valid x => replaceFileName x (takeFileName x) == x

The character that is used to separate the entries in the $PATH environment variable.

Windows: searchPathSeparator == ';'
Posix:   searchPathSeparator == ':'

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"]

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")

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/","")

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

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")
Windows: splitFileName "\\\\?\\A:" == ("\\\\?\\A:","")
valuesplitPath :: 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"]
valuesplitSearchPath :: 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"]

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
valuetakeBaseName :: 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"

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:\\"

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"

Get all extensions.

takeExtensions "/directory/path.ext" == ".ext"
takeExtensions "file.tar.gz" == ".tar.gz"

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)
value(++) :: [a] -> [a] -> [a]
#

(++) appends 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.

Performance considerations

This function takes linear time in the number of elements of the first list. Thus it is better to associate repeated applications of (++) to the right (which is the default behaviour): xs ++ (ys ++ zs) or simply xs ++ ys ++ zs, but not (xs ++ ys) ++ zs. For the same reason GHC.Internal.Data.List.concat = GHC.Internal.Data.List.foldr (++) [] has linear performance, while GHC.Internal.Data.List.foldl (++) [] is prone to quadratic slowdown

Examples
Example1 expression
[1, 2, 3] ++ [4, 5, 6][1,2,3,4,5,6]
Example1 expression
[] ++ [1, 2, 3][1,2,3]
Example1 expression
[3, 2, 1] ++ [][3,2,1]
value(<**>) :: Applicative f => f a -> f (a -> b) -> f b
#

A variant of <*> with the types of the arguments reversed. It differs from flip (<*>) in that the effects are resolved in the order the arguments are presented.

Examples
Example1 expression
(<**>) (print 1) (id <$ print 2)12
Example1 expression
flip (<*>) (print 1) (id <$ print 2)21
Example1 expression
ZipList [4, 5, 6] <**> ZipList [(+1), (*2), (/3)]ZipList {getZipList = [5.0,10.0,2.0]}
value(=<<) :: Monad m => (a -> m b) -> m a -> m b
#

Same as >>=, but with the arguments interchanged.

as >>= f == f =<< as
valueap :: Monad m => m (a -> b) -> m a -> m b
#

In many situations, the liftM operations can be replaced by uses of ap, which promotes function application.

return f `ap` x1 `ap` ... `ap` xn

is equivalent to

liftM<n> f x1 x2 ... xn

This function can be used to define `(*) = ap`, if Monad is already defined for a data type.

Examples
Example1 expression
pure (\x y z -> x + y * z) `ap` Just 1 `ap` Just 5 `ap` Just 10Just 51
valuejoin :: 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.

'join bss' can be understood as the do expression

do bs <- bss
   bs
Examples
Example1 expression
join [[1, 2, 3], [4, 5, 6], [7, 8, 9]][1,2,3,4,5,6,7,8,9]
Example1 expression
join (Just (Just 3))Just 3

A common use of join is to run an IO computation returned from an GHC.Conc.STM transaction, since GHC.Conc.STM transactions can't perform IO directly. Recall that

GHC.Internal.Conc.atomically :: STM a -> IO a

is used to run GHC.Conc.STM transactions atomically. So, by specializing the types of GHC.Internal.Conc.atomically and join to

GHC.Internal.Conc.atomically :: STM (IO b) -> IO (IO b)
join       :: IO (IO b)  -> IO b

we can compose them as

join . GHC.Internal.Conc.atomically :: STM (IO b) -> IO b

to run an GHC.Conc.STM transaction and the IO action it returns.

valueliftA :: 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.

This function can be used to define `fmap = liftA`, if Applicative is already defined for a data type.

Examples

Using the Applicative instance for Lists:

Example1 expression
liftA (+1) [1, 2][2,3]

Or the Applicative instance for Maybe

Example1 expression
liftA (+1) (Just 3)Just 4
valueliftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
#

Lift a ternary function to actions.

valueliftM :: Monad m => (a1 -> r) -> m a1 -> m r
#

Promote a function to a monad. This is equivalent to fmap but specialised to Monads.

This function can be used to define `fmap = liftM`, if Monad is already defined for a data type.

valueliftM2 :: 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.

This function can be used to define `liftA2 = liftM2`, if Monad is already defined for a data type.

Examples
Example1 expression
liftM2 (+) [0,1] [0,2][0,2,1,3]
Example1 expression
liftM2 (+) (Just 1) NothingNothing
Example1 expression
liftM2 (+) (+ 3) (* 2) 518
valueliftM3 :: 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).

valueliftM4
  1. :: Monad m
  2. => a1 -> a2 -> a3 -> a4 -> r
  3. -> m a1
  4. -> m a2
  5. -> m a3
  6. -> m a4
  7. -> m r
#

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

valueliftM5
  1. :: Monad m
  2. => a1 -> a2 -> a3 -> a4 -> a5 -> r
  3. -> m a1
  4. -> m a2
  5. -> m a3
  6. -> m a4
  7. -> m a5
  8. -> m r
#

Promote a function to a monad, scanning the monadic arguments from left to right (cf. liftM2).

valuemap :: (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, ...]

this means that map id == id

Examples
Example1 expression
map (+1) [1, 2, 3][2,3,4]
Example1 expression
map id [1, 2, 3][1,2,3]
Example1 expression
map (\n -> 3 * n + 1) [1, 2, 3][4,7,10]
valueord :: Char -> Int
#

The Prelude.fromEnum method restricted to the type Char.

valuethenA :: Applicative f => f a -> f b -> f b
#

Sequence two Applicative actions, discarding the result of the first one.

Defined as `thenA fa fb = (id fa) <* fb`.

This can be used to explicitly define `(*>) = thenA`, which is the default definition.

valuethenM :: Monad m => m a -> m b -> m b
#

Sequence two monadic actions, discarding the result of the first one.

Defined as `thenM ma mb = ma >>= const mb`.

This can be used to define `(*>) = thenM`.

valuewhen :: Applicative f => Bool -> f () -> f ()
#

Conditional execution of Applicative expressions. For example,

Examples
when debug (putStrLn "Debugging")

will output the string Debugging if the Boolean value debug is True, and otherwise do nothing.

Example1 expression
putStr "pi:" >> when False (print 3.14159)pi:
valuechr :: Int -> Char
#

The Prelude.toEnum method restricted to the type Char.

valueforkOS :: IO () -> IO ThreadId
#

Like forkIO, this sparks off a new thread to run the IO computation passed as the first argument, and returns the ThreadId of the newly created thread.

However, forkOS creates a bound thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see Control.Concurrent#boundthreads).

Using forkOS instead of forkIO makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use forkOS instead of forkIO to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the -threaded option when linking your program, and to make sure the foreign import is not marked unsafe.

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.

valuerunInBoundThread :: 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.

valuerunInUnboundThread :: 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.

valuethreadDelay :: 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.

Be careful not to exceed maxBound :: Int, which on 32-bit machines is only 2147483647 μs, less than 36 minutes. Consider using Control.Concurrent.Thread.Delay.delay from unbounded-delays package.

valueforkIO :: 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 GHC.Control.Exception.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.

WARNING: Exceptions in the new thread will not be rethrown in the thread that created it. This means that you might be completely unaware of the problem if/when this happens. You may want to use the async library instead.

valueforkIOWithUnmask :: ((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 ...) handler

so 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.

valueforkOn :: 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).

valuelabelThread :: ThreadId -> String -> IO ()
#

labelThread stores a string as identifier for this thread. This identifier will be used in the debugging output to make distinction of different threads easier (otherwise you only have the thread state object's address in the heap). It also emits an event to the RTS eventlog.

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.

valuesetNumCapabilities :: 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.

valuethreadCapability :: 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.

valuethrowTo :: 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.

valueyield :: IO ()
#

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.

valuemodifyMVar :: 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.

valuemodifyMVar_ :: 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. In other words, it cannot guarantee that, by the time modifyMVar_ gets the chance to write to the MVar, the value of the MVar has not been altered by a write operation from another thread.

valueswapMVar :: MVar a -> a -> IO a
#

Take a value from an MVar, put a new value into the MVar and return the value taken. This function is atomic only if there are no other producers for this MVar. In other words, it cannot guarantee that, by the time swapMVar gets the chance to write to the MVar, the value of the MVar has not been altered by a write operation from another thread.

valuewithMVar :: 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. In other words, it cannot guarantee that, by the time withMVar gets the chance to write to the MVar, the value of the MVar has not been altered by a write operation from another thread.

valuewithMVarMasked :: MVar a -> (a -> IO b) -> IO b
#

Like withMVar, but the IO action in the second argument is executed with asynchronous exceptions masked.

value(<$!>) :: Monad m => (a -> b) -> m a -> m b
#

Strict version of <$>.

value(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
#

Right-to-left composition of Kleisli arrows. (>=>), with the arguments flipped.

Note how this operator resembles function composition (.):

(.)   ::            (b ->   c) -> (a ->   b) -> a ->   c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
value(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
#

Left-to-right composition of Kleisli arrows.

'(bs >=> cs) a' can be understood as the do expression

do b <- bs a
   cs b

or in terms of (>>=) as

bs a >>= cs
valuefilterM :: Applicative m => (a -> m Bool) -> [a] -> m [a]
#

This generalizes the list-based Data.List.filter function.

runIdentity (filterM (Identity . p) xs) == filter p xs
Examples
Example1 expression
filterM (\x -> do      putStrLn ("Keep: " ++ show x ++ "?")      answer <- getLine      pure (answer == "y"))    [1, 2, 3]Keep: 1?yKeep: 2?nKeep: 3?y[1,3]
Example1 expression
filterM (\x -> do      putStr (show x)      x' <- readLn      pure (x == x'))    [1, 2, 3]122233[2,3]
valuefoldM :: (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.

Note: foldM is the same as foldlM

valueforever :: Applicative f => f a -> f b
#

Repeat an action indefinitely.

Examples

A common use of forever is to process input from network sockets, System.IO.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 socket
  forkFinally (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 MonadPlus and short-circuits after some number of iterations. then forever actually returns mzero, effectively short-circuiting its caller.

valueguard :: Alternative f => Bool -> f ()
#

Conditional failure of Alternative computations. Defined by

guard True  = pure ()
guard False = empty
Examples

Common uses of guard include conditionally signalling an error in an error monad and conditionally rejecting the current choice in an Alternative-based parser.

As an example of signalling 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 Just (x `div` y) otherwise. For example:

Example1 expression
safeDiv 4 0Nothing
Example1 expression
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)
valuemapAndUnzipM :: 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.

valuemfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
#

Direct MonadPlus equivalent of Data.List.filter.

Examples

The Data.List.filter function is just mfilter specialized to the list monad:

Data.List.filter = ( mfilter :: (a -> Bool) -> [a] -> [a] )

An example using mfilter with the Maybe monad:

Example2 expressions
mfilter odd (Just 1)Just 1mfilter odd (Just 2)Nothing
valuereplicateM :: Applicative m => Int -> m a -> m [a]
#

replicateM n act performs the action act n times, and then returns the list of results.

replicateM n (pure x) == pure (replicate n x)
Examples
Example1 expression
replicateM 3 getLinehiheyahiya["hi","heya","hiya"]
Example2 expressions
import Control.Monad.StaterunState (replicateM 3 $ state $ \s -> (s, s + 1)) 1([1,2,3],4)
valueunless :: Applicative f => Bool -> f () -> f ()
#

The reverse of when.

Examples
Example1 expression
do x <- getLine       unless (x == "hi") (putStrLn "hi!")comingupwithexamplesisdifficulthi!
Example1 expression
unless (pi > exp 1) NothingJust ()
valuefixIO :: (a -> IO a) -> IO a
#

The implementation of mfix for IO.

This operation may fail with:

Examples

the IO-action is only executed once. The recursion is only on the values.

Example1 expression
take 3 <$> fixIO (\x -> putStr ":D" >> (:x) <$> readLn @Int):D2[2,2,2]

If we are strict in the value, just as with Data.Function.fix, we do not get termination:

Example1 expression
fixIO (\x -> putStr x >> pure ('x' : x))* hangs forever *

We can tie the knot of a structure within IO using fixIO:

data Node = MkNode Int (IORef Node)

foo :: IO ()
foo = do
  p <- fixIO (p -> newIORef (MkNode 0 p))
  q <- output p
  r <- output q
  _ <- output r
  pure ()

output :: IORef Node -> IO (IORef Node)
output ref = do
  MkNode x p <- readIORef ref
  print x
  pure p
Example1 expression
foo000
valueeither :: (a -> c) -> (b -> c) -> Either a b -> c
#

Case analysis for the Either type. If the value is Left a, apply the first function to a; if it is Right b, apply the second function to b.

Examples

We create two values of type Either String Int, one using the Left constructor and another using the Right constructor. Then we apply "either" the Prelude.length function (if we have a String) or the "times-two" function (if we have an Int):

Example4 expressions
let s = Left "foo" :: Either String Intlet n = Right 3 :: Either String Inteither length (*2) s3either length (*2) n6
valuefromLeft :: a -> Either a b -> a
#

Return the contents of a Left-value or a default value otherwise.

Examples

Basic usage:

Example2 expressions
fromLeft 1 (Left 3)3fromLeft 1 (Right "foo")1
valuefromRight :: b -> Either a b -> b
#

Return the contents of a Right-value or a default value otherwise.

Examples

Basic usage:

Example2 expressions
fromRight 1 (Right 3)3fromRight 1 (Left "foo")1
valueisLeft :: Either a b -> Bool
#

Return True if the given value is a Left-value, False otherwise.

Examples

Basic usage:

Example2 expressions
isLeft (Left "foo")TrueisLeft (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:

Example4 expressions
import Control.Monad ( when )let report e = when (isLeft e) $ putStrLn "ERROR"report (Right 1)report (Left "parse error")ERROR
valueisRight :: Either a b -> Bool
#

Return True if the given value is a Right-value, False otherwise.

Examples

Basic usage:

Example2 expressions
isRight (Left "foo")FalseisRight (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:

Example4 expressions
import Control.Monad ( when )let report e = when (isRight e) $ putStrLn "SUCCESS"report (Left "parse error")report (Right 1)SUCCESS
valuelefts :: [Either a b] -> [a]
#

Extracts from a list of Either all the Left elements. All the Left elements are extracted in order.

Examples

Basic usage:

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]lefts list["foo","bar","baz"]
valuepartitionEithers :: [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:

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]partitionEithers list(["foo","bar","baz"],[3,7])

The pair returned by partitionEithers x should be the same pair as (lefts x, rights x):

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]partitionEithers list == (lefts list, rights list)True
valuerights :: [Either a b] -> [b]
#

Extracts from a list of Either all the Right elements. All the Right elements are extracted in order.

Examples

Basic usage:

Example2 expressions
let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]rights list[3,7]
valueall :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether all elements of the structure satisfy the predicate.

Examples

Basic usage:

Example1 expression
all (> 3) []True
Example1 expression
all (> 3) [1,2]False
Example1 expression
all (> 3) [1,2,3,4,5]False
Example1 expression
all (> 3) [1..]False
Example1 expression
all (> 3) [4..]* Hangs forever *
valueand :: 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:

Example1 expression
and []True
Example1 expression
and [True]True
Example1 expression
and [False]False
Example1 expression
and [True, True, False]False
Example1 expression
and (False : repeat True) -- Infinite list [False,True,True,True,...False
Example1 expression
and (repeat True)* Hangs forever *
valueany :: Foldable t => (a -> Bool) -> t a -> Bool
#

Determines whether any element of the structure satisfies the predicate.

Examples

Basic usage:

Example1 expression
any (> 3) []False
Example1 expression
any (> 3) [1,2]False
Example1 expression
any (> 3) [1,2,3,4,5]True
Example1 expression
any (> 3) [1..]True
Example1 expression
any (> 3) [0, -1..]* Hangs forever *
valueasum :: (Foldable t, Alternative f) => t (f a) -> f a
#

The sum of a collection of actions using (<|>), generalizing concat.

asum is just like msum, but generalised to Alternative.

Examples

Basic usage:

Example1 expression
asum [Just "Hello", Nothing, Just "World"]Just "Hello"
valueconcat :: Foldable t => t [a] -> [a]
#

The concatenation of all the elements of a container of lists.

Examples

Basic usage:

Example1 expression
concat (Just [1, 2, 3])[1,2,3]
Example1 expression
concat (Left 42)[]
Example1 expression
concat [[1, 2, 3], [4, 5], [6], []][1,2,3,4,5,6]
valueconcatMap :: 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:

Example1 expression
concatMap (take 3) [[1..], [10..], [100..], [1000..]][1,2,3,10,11,12,100,101,102,1000,1001,1002]
Example1 expression
concatMap (take 3) (Just [1..])[1,2,3]
valuefind :: Foldable t => (a -> Bool) -> t a -> Maybe a
#

The find function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or Nothing if there is no such element.

Examples

Basic usage:

Example1 expression
find (> 42) [0, 5..]Just 45
Example1 expression
find (> 12) [1..7]Nothing
valueforM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
#

forM_ is mapM_ with its arguments flipped. For a version that doesn't ignore the results see Data.Traversable.forM.

forM_ is just like for_, but specialised to monadic actions.

valuemapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()
#

Map each element of a structure to a monadic action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see Data.Traversable.mapM.

mapM_ is just like traverse_, but specialised to monadic actions.

valuemaximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
#

The largest element of a non-empty structure with respect to the given comparison function. Structure order is used as a tie-breaker: if there are multiple largest elements, the rightmost of them is chosen.

Examples

Basic usage:

Example1 expression
maximumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"Longest"

WARNING: This function is partial for possibly-empty structures like lists.

valueminimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
#

The least element of a non-empty structure with respect to the given comparison function. Structure order is used as a tie-breaker: if there are multiple least elements, the leftmost of them is chosen.

Examples

Basic usage:

Example1 expression
minimumBy (compare `on` length) ["Hello", "World", "!", "Longest", "bar"]"!"

WARNING: This function is partial for possibly-empty structures like lists.

valuemsum :: (Foldable t, MonadPlus m) => t (m a) -> m a
#

The sum of a collection of actions using (<|>), generalizing concat.

msum is just like asum, but specialised to MonadPlus.

Examples

Basic usage, using the MonadPlus instance for Maybe:

Example1 expression
msum [Just "Hello", Nothing, Just "World"]Just "Hello"
valuenotElem :: (Foldable t, Eq a) => a -> t a -> Bool
#

notElem is the negation of elem.

Examples

Basic usage:

Example1 expression
3 `notElem` []True
Example1 expression
3 `notElem` [1,2]True
Example1 expression
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:

Example1 expression
3 `notElem` [1..]False
Example1 expression
3 `notElem` ([4..] ++ [3])* Hangs forever *
valueor :: 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:

Example1 expression
or []False
Example1 expression
or [True]True
Example1 expression
or [False]False
Example1 expression
or [True, True, False]True
Example1 expression
or (True : repeat False) -- Infinite list [True,False,False,False,...True
Example1 expression
or (repeat False)* Hangs forever *
valuesequence_ :: (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 Data.Traversable.sequence.

sequence_ is just like sequenceA_, but specialised to monadic actions.

value($>) :: Functor f => f a -> b -> f b
#

Flipped version of <$.

Examples

Replace the contents of a Maybe Int with a constant String:

Example1 expression
Nothing $> "foo"Nothing
Example1 expression
Just 90210 $> "foo"Just "foo"

Replace the contents of an Either Int Int with a constant String, resulting in an Either Int String:

Example1 expression
Left 8675309 $> "foo"Left 8675309
Example1 expression
Right 8675309 $> "foo"Right "foo"

Replace each element of a list with a constant String:

Example1 expression
[1,2,3] $> "foo"["foo","foo","foo"]

Replace the second element of a pair with a constant String:

Example1 expression
(1,2) $> "foo"(1,"foo")
value(<$>) :: Functor f => (a -> b) -> f a -> f b
#

An infix synonym for fmap.

The name of this operator is an allusion to Prelude.$. Note the similarities between their types:

 ($)  ::              (a -> b) ->   a ->   b
(<$>) :: Functor f => (a -> b) -> f a -> f b

Whereas Prelude.$ is function application, <$> is function application lifted over a Functor.

Examples

Convert from a Maybe Int to a Maybe String using show:

Example1 expression
show <$> NothingNothing
Example1 expression
show <$> Just 3Just "3"

Convert from an Either Int Int to an Either Int String using show:

Example1 expression
show <$> Left 17Left 17
Example1 expression
show <$> Right 17Right "17"

Double each element of a list:

Example1 expression
(*2) <$> [1,2,3][2,4,6]

Apply even to the second element of a pair:

Example1 expression
even <$> (2,2)(2,True)
value(<&>) :: Functor f => f a -> (a -> b) -> f b
#

Flipped version of <$>.

(<&>) = flip fmap
Examples

Apply (+1) to a list, a Just and a Right:

Example1 expression
Just 2 <&> (+1)Just 3
Example1 expression
[1,2,3] <&> (+1)[2,3,4]
Example1 expression
Right 3 <&> (+1)Right 4
valuevoid :: Functor f => f a -> f ()
#

void value discards or ignores the result of evaluation, such as the return value of an System.IO.IO action.

Examples

Replace the contents of a Maybe Int with unit:

Example1 expression
void NothingNothing
Example1 expression
void (Just 3)Just ()

Replace the contents of an Either Int Int with unit, resulting in an Either Int ():

Example1 expression
void (Left 8675309)Left 8675309
Example1 expression
void (Right 8675309)Right ()

Replace every element of a list with unit:

Example1 expression
void [1,2,3][(),(),()]

Replace the second element of a pair with unit:

Example1 expression
void (1,2)(1,())

Discard the result of an System.IO.IO action:

Example1 expression
mapM print [1,2]12[(),()]
Example1 expression
void $ mapM print [1,2]12
valueisSubsequenceOf :: 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.

isSubsequenceOf x y is equivalent to x `elem` (subsequences y).

Note: isSubsequenceOf is often used in infix form.

Examples
Example1 expression
"GHC" `isSubsequenceOf` "The Glorious Haskell Compiler"True
Example1 expression
['a','d'..'z'] `isSubsequenceOf` ['a'..'z']True
Example1 expression
[1..10] `isSubsequenceOf` [10,9..0]False

For the result to be True, the first list must be finite; for the result to be False, the second list must be finite:

Example1 expression
[0,2..10] `isSubsequenceOf` [0..]True
Example1 expression
[0..] `isSubsequenceOf` [0,2..10]False
Example1 expression
[0,2..] `isSubsequenceOf` [0..]* Hangs forever*
valuecatMaybes :: [Maybe a] -> [a]
#

The catMaybes function takes a list of Maybes and returns a list of all the Just values.

Examples

Basic usage:

Example1 expression
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):

Example3 expressions
import GHC.Internal.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]
valuefromJust :: HasCallStack => Maybe a -> a
#

The fromJust function extracts the element out of a Just and throws an error if its argument is Nothing.

Examples

Basic usage:

Example1 expression
fromJust (Just 1)1
Example1 expression
2 * (fromJust (Just 10))20
Example1 expression
2 * (fromJust Nothing)*** Exception: Maybe.fromJust: Nothing...

WARNING: This function is partial. You can use case-matching instead.

valuefromMaybe :: 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:

Example1 expression
fromMaybe "" (Just "Hello, World!")"Hello, World!"
Example1 expression
fromMaybe "" Nothing""

Read an integer from a string using readMaybe. If we fail to parse an integer, we want to return 0 by default:

Example3 expressions
import GHC.Internal.Text.Read ( readMaybe )fromMaybe 0 (readMaybe "5")5fromMaybe 0 (readMaybe "")0
valueisJust :: Maybe a -> Bool
#

isJust x returns True when x is of the form Just _ and False otherwise.

Examples

Basic usage:

Example1 expression
isJust (Just 3)True
Example1 expression
isJust (Just ())True
Example1 expression
isJust NothingFalse

Only the outer constructor is taken into consideration:

Example1 expression
isJust (Just Nothing)True
valueisNothing :: Maybe a -> Bool
#

isNothing x returns True when x is Nothing and False otherwise.

Examples

Basic usage:

Example1 expression
isNothing (Just 3)False
Example1 expression
isNothing (Just ())False
Example1 expression
isNothing NothingTrue

Only the outer constructor is taken into consideration:

Example1 expression
isNothing (Just Nothing)False
valuelistToMaybe :: [a] -> Maybe a
#

The listToMaybe function returns Nothing on an empty list or Just a where a is the first element of the list.

Examples

Basic usage:

Example1 expression
listToMaybe []Nothing
Example1 expression
listToMaybe [9]Just 9
Example1 expression
listToMaybe [1,2,3]Just 1

Composing maybeToList with listToMaybe should be the identity on singleton/empty lists:

Example2 expressions
maybeToList $ listToMaybe [5][5]maybeToList $ listToMaybe [][]

But not on lists with more than one element:

Example1 expression
maybeToList $ listToMaybe [1,2,3][1]
valuemapMaybe :: (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 Maybe b. If this is Nothing, no element is added on to the result list. If it is Just b, then b is included in the result list.

Examples

Using mapMaybe f x is a shortcut for catMaybes $ map f x in most cases:

Example4 expressions
import GHC.Internal.Text.Read ( readMaybe )let readMaybeInt = readMaybe :: String -> Maybe IntmapMaybe 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:

Example1 expression
mapMaybe Just [1,2,3][1,2,3]
valuemaybe :: 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:

Example1 expression
maybe False odd (Just 3)True
Example1 expression
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:

Example3 expressions
import GHC.Internal.Text.Read ( readMaybe )maybe 0 (*2) (readMaybe "5")10maybe 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":

Example2 expressions
maybe "" show (Just 5)"5"maybe "" show Nothing""
valuemaybeToList :: Maybe a -> [a]
#

The maybeToList function returns an empty list when given Nothing or a singleton list when given Just.

Examples

Basic usage:

Example1 expression
maybeToList (Just 7)[7]
Example1 expression
maybeToList Nothing[]

One can use maybeToList to avoid pattern matching when combined with a function that (safely) works on lists:

Example3 expressions
import GHC.Internal.Text.Read ( readMaybe )sum $ maybeToList (readMaybe "3")3sum $ maybeToList (readMaybe "")0
value(\\) :: Eq a => [a] -> [a] -> [a]
#

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.

It is a special case of deleteFirstsBy, which allows the programmer to supply their own equality test.

Examples
Example1 expression
"Hello World!" \\ "ell W""Hoorld!"

The second list must be finite, but the first may be infinite.

Example1 expression
take 5 ([0..] \\ [2..4])[0,1,5,6,7]
Example1 expression
take 5 ([0..] \\ [2..])* Hangs forever *
valuedelete :: Eq a => a -> [a] -> [a]
#

\mathcal{O}(n). delete x removes the first occurrence of x from its list argument.

It is a special case of deleteBy, which allows the programmer to supply their own equality test.

Examples
Example1 expression
delete 'a' "banana""bnana"
Example1 expression
delete "not" ["haskell", "is", "not", "awesome"]["haskell","is","awesome"]
valuedeleteBy :: (a -> b -> Bool) -> a -> [b] -> [b]
#

\mathcal{O}(n). The deleteBy function behaves like delete, but takes a user-supplied equality predicate.

Examples
Example1 expression
deleteBy (<=) 4 [1..10][1,2,3,5,6,7,8,9,10]
Example1 expression
deleteBy (/=) 5 [5, 5, 4, 3, 5, 2][5,5,3,5,2]
valuedeleteFirstsBy :: (a -> b -> Bool) -> [b] -> [a] -> [b]
#

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. This is the non-overloaded version of (\\).

(\\) == deleteFirstsBy (==)

The second list must be finite, but the first may be infinite.

Examples
Example1 expression
deleteFirstsBy (>) [1..10] [3, 4, 5][4,5,6,7,8,9,10]
Example1 expression
deleteFirstsBy (/=) [1..10] [1, 3, 5][4,5,6,7,8,9,10]
valuedropWhileEnd :: (a -> Bool) -> [a] -> [a]
#

The dropWhileEnd function drops the largest suffix of a list in which the given predicate holds for all elements.

Laziness

This function is lazy in spine, but strict in elements, which makes it different from reverse . dropWhile p . reverse, which is strict in spine, but lazy in elements. For instance:

Example1 expression
take 1 (dropWhileEnd (< 0) (1 : undefined))[1]
Example1 expression
take 1 (reverse $ dropWhile (< 0) $ reverse (1 : undefined))*** Exception: Prelude.undefined

but on the other hand

Example1 expression
last (dropWhileEnd (< 0) [undefined, 1])*** Exception: Prelude.undefined
Example1 expression
last (reverse $ dropWhile (< 0) $ reverse [undefined, 1])1
Examples
Example1 expression
dropWhileEnd isSpace "foo\n""foo"
Example2 expressions
dropWhileEnd isSpace "foo bar""foo bar"dropWhileEnd (> 10) [1..20][1,2,3,4,5,6,7,8,9,10]
valueelemIndex :: Eq a => a -> [a] -> Maybe Int
#

The elemIndex function returns the index of the first element in the given list which is equal (by ==) to the query element, or Nothing if there is no such element. For the result to be Nothing, the list must be finite.

Examples
Example1 expression
elemIndex 4 [0..]Just 4
Example1 expression
elemIndex 'o' "haskell"Nothing
Example1 expression
elemIndex 0 [1..]* hangs forever *
valueelemIndices :: 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.

Examples
Example1 expression
elemIndices 'o' "Hello World"[4,7]
Example1 expression
elemIndices 1 [1, 2, 3, 1, 2, 3][0,3]
valuefindIndex :: (a -> Bool) -> [a] -> Maybe Int
#

The findIndex function takes a predicate and a list and returns the index of the first element in the list satisfying the predicate, or Nothing if there is no such element. For the result to be Nothing, the list must be finite.

Examples
Example1 expression
findIndex isSpace "Hello World!"Just 5
Example1 expression
findIndex odd [0, 2, 4, 6]Nothing
Example1 expression
findIndex even [1..]Just 1
Example1 expression
findIndex odd [0, 2 ..]* hangs forever *
valuefindIndices :: (a -> Bool) -> [a] -> [Int]
#

The findIndices function extends findIndex, by returning the indices of all elements satisfying the predicate, in ascending order.

Examples
Example1 expression
findIndices (`elem` "aeiou") "Hello World!"[1,4,7]
Example1 expression
findIndices (\l -> length l > 3) ["a", "bcde", "fgh", "ijklmnop"][1,3]
valuegenericLength :: 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.

Examples
Example2 expressions
genericLength [1, 2, 3] :: Int3genericLength [1, 2, 3] :: Float3.0

Users should take care to pick a return type that is wide enough to contain the full length of the list. If the width is insufficient, the overflow behaviour will depend on the (+) implementation in the selected Num instance. The following example overflows because the actual list length of 200 lies outside of the Int8 range of -128..127.

Example1 expression
genericLength [1..200] :: Int8-56
valuegroup :: 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 is non-empty, all elements are equal to the first one, and consecutive equal elements of the input end up in the same element of the output list.

group is a special case of groupBy, which allows the programmer to supply their own equality test.

It's often preferable to use Data.List.NonEmpty.group, which provides type-level guarantees of non-emptiness of inner lists. A common idiom to squash repeating elements map head . group is better served by map Data.List.NonEmpty.head . Data.List.NonEmpty.group because it avoids partial functions.

Examples
Example1 expression
group "Mississippi"["M","i","ss","i","ss","i","pp","i"]
Example1 expression
group [1, 1, 1, 2, 2, 3, 4, 5, 5][[1,1,1],[2,2],[3],[4],[5,5]]
valuegroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
#

The groupBy function is the non-overloaded version of group.

When a supplied relation is not transitive, it is important to remember that equality is checked against the first element in the group, not against the nearest neighbour:

Example1 expression
groupBy (\a b -> b - a < 5) [0..19][[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]]

It's often preferable to use Data.List.NonEmpty.groupBy, which provides type-level guarantees of non-emptiness of inner lists.

Examples
Example1 expression
groupBy (/=) [1, 1, 1, 2, 3, 1, 4, 4, 5][[1],[1],[1,2,3],[1,4,4,5]]
Example1 expression
groupBy (>) [1, 3, 5, 1, 4, 2, 6, 5, 4][[1],[3],[5,1,4,2],[6,5,4]]
Example1 expression
groupBy (const not) [True, False, True, False, False, False, True][[True,False],[True,False,False,False],[True]]
valueinits :: [a] -> [[a]]
#

The inits function returns all initial segments of the argument, shortest first.

inits is semantically equivalent to map reverse . scanl (flip (:)) [], but under the hood uses a queue to amortize costs of reverse.

Laziness

Note that inits has the following strictness property: inits (xs ++ _|_) = inits xs ++ _|_

In particular, inits _|_ = [] : _|_

Examples
Example1 expression
inits "abc"["","a","ab","abc"]
Example1 expression
inits [][[]]

inits is productive on infinite lists:

Example1 expression
take 5 $ inits [1..][[],[1],[1,2],[1,2,3],[1,2,3,4]]
valueinsert :: 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.

Examples
Example1 expression
insert (-1) [1, 2, 3][-1,1,2,3]
Example1 expression
insert 'd' "abcefg""abcdefg"
Example1 expression
insert 4 [1, 2, 3, 5, 6, 7][1,2,3,4,5,6,7]
valueinsertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
#

\mathcal{O}(n). The non-overloaded version of insert.

Examples
Example1 expression
insertBy (\x y -> compare (length x) (length y)) [1, 2] [[1], [1, 2, 3], [1, 2, 3, 4]][[1],[1,2],[1,2,3],[1,2,3,4]]
valueintercalate :: [a] -> [[a]] -> [a]
#

intercalate xs xss is equivalent to (concat (intersperse xs xss)). It inserts the list xs in between the lists in xss and concatenates the result.

Laziness

intercalate has the following properties:

Example1 expression
take 5 (intercalate undefined ("Lorem" : undefined))"Lorem"
Example1 expression
take 6 (intercalate ", " ("Lorem" : undefined))"Lorem*** Exception: Prelude.undefined
Examples
Example1 expression
intercalate ", " ["Lorem", "ipsum", "dolor"]"Lorem, ipsum, dolor"
Example1 expression
intercalate [0, 1] [[2, 3], [4, 5, 6], []][2,3,0,1,4,5,6,0,1]
Example1 expression
intercalate [1, 2, 3] [[], []][1,2,3]
valueintersect :: Eq a => [a] -> [a] -> [a]
#

The intersect function takes the list intersection of two lists. It is a special case of intersectBy, which allows the programmer to supply their own equality test.

Examples
Example1 expression
[1,2,3,4] `intersect` [2,4,6,8][2,4]

If equal elements are present in both lists, an element from the first list will be used, and all duplicates from the second list quashed:

Example2 expressions
import Data.Semigroupintersect [Arg () "dog"] [Arg () "cow", Arg () "cat"][Arg () "dog"]

However if the first list contains duplicates, so will the result.

Example2 expressions
"coot" `intersect` "heron""oo""heron" `intersect` "coot""o"

If the second list is infinite, intersect either hangs or returns its first argument in full. Otherwise if the first list is infinite, intersect might be productive:

Example4 expressions
intersect [100..] [0..][100,101,102,103...intersect [0] [1..]* Hangs forever *intersect [1..] [0]* Hangs forever *intersect (cycle [1..3]) [2][2,2,2,2...
valueintersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
#

The intersectBy function is the non-overloaded version of intersect. It is productive for infinite arguments only if the first one is a subset of the second.

valueintersperse :: 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.

Laziness

intersperse has the following properties

Example1 expression
take 1 (intersperse undefined ('a' : undefined))"a"
Example1 expression
take 2 (intersperse ',' ('a' : undefined))"a*** Exception: Prelude.undefined
Examples
Example1 expression
intersperse ',' "abcde""a,b,c,d,e"
Example1 expression
intersperse 1 [3, 4, 5][3,1,4,1,5]
valueisInfixOf :: Eq a => [a] -> [a] -> Bool
#

The isInfixOf function takes two lists and returns True iff the first list is contained, wholly and intact, anywhere within the second.

Examples
Example1 expression
isInfixOf "Haskell" "I really like Haskell."True
Example1 expression
isInfixOf "Ial" "I really like Haskell."False

For the result to be True, the first list must be finite; for the result to be False, the second list must be finite:

Example1 expression
[20..50] `isInfixOf` [0..]True
Example1 expression
[0..] `isInfixOf` [20..50]False
Example1 expression
[0..] `isInfixOf` [0..]* Hangs forever *
valueisPrefixOf :: 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.

Examples
Example1 expression
"Hello" `isPrefixOf` "Hello World!"True
Example1 expression
"Hello" `isPrefixOf` "Wello Horld!"False

For the result to be True, the first list must be finite; False, however, results from any mismatch:

Example1 expression
[0..] `isPrefixOf` [1..]False
Example1 expression
[0..] `isPrefixOf` [0..99]False
Example1 expression
[0..99] `isPrefixOf` [0..]True
Example1 expression
[0..] `isPrefixOf` [0..]* Hangs forever *

isPrefixOf shortcuts when the first argument is empty:

Example1 expression
isPrefixOf [] undefinedTrue
valueisSuffixOf :: Eq a => [a] -> [a] -> Bool
#

The isSuffixOf function takes two lists and returns True iff the first list is a suffix of the second.

Examples
Example1 expression
"ld!" `isSuffixOf` "Hello World!"True
Example1 expression
"World" `isSuffixOf` "Hello World!"False

The second list must be finite; however the first list may be infinite:

Example1 expression
[0..] `isSuffixOf` [0..99]False
Example1 expression
[0..99] `isSuffixOf` [0..]* Hangs forever *
valuelines :: String -> [String]
#

Splits the argument into a list of lines stripped of their terminating \n characters. The \n terminator is optional in a final non-empty line of the argument string.

When the argument string is empty, or ends in a \n character, it can be recovered by passing the result of lines to the unlines function. Otherwise, unlines appends the missing terminating \n. This makes unlines . lines idempotent:

(unlines . lines) . (unlines . lines) = (unlines . lines)
Examples
Example1 expression
lines ""           -- empty input contains no lines[]
Example1 expression
lines "\n"         -- single empty line[""]
Example1 expression
lines "one"        -- single unterminated line["one"]
Example1 expression
lines "one\n"      -- single non-empty line["one"]
Example1 expression
lines "one\n\n"    -- second line is empty["one",""]
Example1 expression
lines "one\ntwo"   -- second line is unterminated["one","two"]
Example1 expression
lines "one\ntwo\n" -- two non-empty lines["one","two"]
valuenub :: Eq a => [a] -> [a]
#

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.

This function knows too little about the elements to be efficient. Its asymptotic complexity is O(n ⋅ d), where d is the number of distinct elements in the list.

If there exists instance Ord a, it's faster to use nubOrd.

Examples
Example1 expression
nub [1,2,3,4,3,2,1,2,4,3,5][1,2,3,4,5]
Example1 expression
nub "hello, world!""helo, wrd!"
valuenubBy :: (a -> a -> Bool) -> [a] -> [a]
#

The nubBy function behaves just like nub, except it uses a user-supplied equality predicate instead of the overloaded (==) function.

Examples
Example1 expression
nubBy (\x y -> mod x 3 == mod y 3) [1,2,4,5,6][1,2,6]
Example1 expression
nubBy (/=) [2, 7, 1, 8, 2, 8, 1, 8, 2, 8][2,2,2]
Example1 expression
nubBy (>) [1, 2, 3, 2, 1, 5, 4, 5, 3, 2][1,2,3,5,5]
valuepartition :: (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)
Examples
Example1 expression
partition (`elem` "aeiou") "Hello World!"("eoo","Hll Wrld!")
Example1 expression
partition even [1..10]([2,4,6,8,10],[1,3,5,7,9])
Example1 expression
partition (< 5) [1..10]([1,2,3,4],[5,6,7,8,9,10])
valuepermutations :: [a] -> [[a]]
#

The permutations function returns the list of all permutations of the argument.

Note that the order of permutations is not lexicographic. It satisfies the following property:

map (take n) (take (product [1..n]) (permutations ([1..n] ++ undefined))) == permutations [1..n]
Laziness

The permutations function is maximally lazy: for each n, the value of permutations xs starts with those permutations that permute take n xs and keep drop n xs.

Examples
Example1 expression
permutations "abc"["abc","bac","cba","bca","cab","acb"]
Example1 expression
permutations [1, 2][[1,2],[2,1]]
Example1 expression
permutations [][[]]

This function is productive on infinite inputs:

Example1 expression
take 6 $ map (take 3) $ permutations ['a'..]["abc","bac","cba","bca","cab","acb"]
valuesingleton :: a -> [a]
#

Construct a list from a single element.

Examples
Example1 expression
singleton True[True]
Example1 expression
singleton [1, 2, 3][[1,2,3]]
Example1 expression
singleton 'c'"c"
valuesort :: Ord a => [a] -> [a]
#

The sort function implements a stable sorting algorithm. It is a special case of sortBy, which allows the programmer to supply their own comparison function.

Elements are arranged from lowest to highest, keeping duplicates in the order they appeared in the input.

The argument must be finite.

Examples
Example1 expression
sort [1,6,4,3,2,5][1,2,3,4,5,6]
Example1 expression
sort "haskell""aehklls"
Example2 expressions
import Data.Semigroup(Arg(..))sort [Arg ":)" 0, Arg ":D" 0, Arg ":)" 1, Arg ":3" 0, Arg ":D" 1][Arg ":)" 0,Arg ":)" 1,Arg ":3" 0,Arg ":D" 0,Arg ":D" 1]
valuesortBy :: (a -> a -> Ordering) -> [a] -> [a]
#

The sortBy function is the non-overloaded version of sort. The argument must be finite.

The supplied comparison relation is supposed to be reflexive and antisymmetric, otherwise, e. g., for _ _ -> GT, the ordered list simply does not exist. The relation is also expected to be transitive: if it is not then sortBy might fail to find an ordered permutation, even if it exists.

Examples
Example1 expression
sortBy (\(a,_) (b,_) -> compare a b) [(2, "world"), (4, "!"), (1, "Hello")][(1,"Hello"),(2,"world"),(4,"!")]
valuesortOn :: 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.

The argument must be finite.

Examples
Example1 expression
sortOn fst [(2, "world"), (4, "!"), (1, "Hello")][(1,"Hello"),(2,"world"),(4,"!")]
Example1 expression
sortOn length ["jim", "creed", "pam", "michael", "dwight", "kevin"]["jim","pam","creed","kevin","dwight","michael"]
Performance notes

This function minimises the projections performed, by materialising the projections in an intermediate list.

For trivial projections, you should prefer using sortBy with comparing, for example:

Example1 expression
sortBy (comparing fst) [(3, 1), (2, 2), (1, 3)][(1,3),(2,2),(3,1)]

Or, for the exact same API as sortOn, you can use `sortBy . comparing`:

Example1 expression
(sortBy . comparing) fst [(3, 1), (2, 2), (1, 3)][(1,3),(2,2),(3,1)]

However, sortOn may still be faster for instances with a more efficient implementation of (>) than compare.

valuestripPrefix :: 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.

Examples
Example1 expression
stripPrefix "foo" "foobar"Just "bar"
Example1 expression
stripPrefix "foo" "foo"Just ""
Example1 expression
stripPrefix "foo" "barfoo"Nothing
Example1 expression
stripPrefix "foo" "barfoobaz"Nothing
valuesubsequences :: [a] -> [[a]]
#

The subsequences function returns the list of all subsequences of the argument.

Laziness

subsequences does not look ahead unless it must:

Example2 expressions
take 1 (subsequences undefined)[[]]take 2 (subsequences ('a' : undefined))["","a"]
Examples
Example1 expression
subsequences "abc"["","a","b","ab","c","ac","bc","abc"]

This function is productive on infinite inputs:

Example1 expression
take 8 $ subsequences ['a'..]["","a","b","ab","c","ac","bc","abc"]
valuetails :: [a] -> [[a]]
#

\mathcal{O}(n). The tails function returns all final segments of the argument, longest first.

Laziness

Note that tails has the following strictness property: tails _|_ = _|_ : _|_

Example1 expression
tails undefined[*** Exception: Prelude.undefined
Example1 expression
drop 1 (tails [undefined, 1, 2])[[1, 2], [2], []]
Examples
Example1 expression
tails "abc"["abc","bc","c",""]
Example1 expression
tails [1, 2, 3][[1,2,3],[2,3],[3],[]]
Example1 expression
tails [][[]]
valuetranspose :: [[a]] -> [[a]]
#

The transpose function transposes the rows and columns of its argument.

Laziness

transpose is lazy in its elements

Example1 expression
take 1 (transpose ['a' : undefined, 'b' : undefined])["ab"]
Examples
Example1 expression
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:

Example1 expression
transpose [[10,11],[20],[],[30,31,32]][[10,20,30],[11,31],[32]]

For this reason the outer list must be finite; otherwise transpose hangs:

Example1 expression
transpose (repeat [])* Hangs forever *
valueunfoldr :: (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
Laziness
Example1 expression
take 1 (unfoldr (\x -> Just (x, undefined)) 'a')"a"
Examples
Example1 expression
unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10[10,9,8,7,6,5,4,3,2,1]
Example1 expression
take 10 $ unfoldr (\(x, y) -> Just (x, (y, x + y))) (0, 1)[0,1,1,2,3,5,8,13,21,54]
valueunion :: Eq a => [a] -> [a] -> [a]
#

The union function returns the list union of the two lists. It is a special case of unionBy, which allows the programmer to supply their own equality test.

Examples
Example1 expression
"dog" `union` "cow""dogcw"

If equal elements are present in both lists, an element from the first list will be used. If the second list contains equal elements, only the first one will be retained:

Example3 expressions
import Data.Semigroup(Arg(..))union [Arg () "dog"] [Arg () "cow"][Arg () "dog"]union [] [Arg () "dog", Arg () "cow"][Arg () "dog"]

However if the first list contains duplicates, so will the result:

Example2 expressions
"coot" `union` "duck""cootduk""duck" `union` "coot""duckot"

union is productive even if both arguments are infinite.

Example1 expression
[0, 2 ..] `union` [1, 3 ..][0,2,4,6,8,10,12..
valueunionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
#

The unionBy function is the non-overloaded version of union. Both arguments may be infinite.

Examples
Example1 expression
unionBy (>) [3, 4, 5] [1, 2, 3, 4, 5, 6][3,4,5,4,5,6]
Example2 expressions
import Data.Semigroup (Arg(..))unionBy (/=) [Arg () "Saul"] [Arg () "Kim"][Arg () "Saul", Arg () "Kim"]
valueunlines :: [String] -> String
#

Appends a \n character to each input string, then concatenates the results. Equivalent to foldMap (s -> s ++ "\n").

Examples
Example1 expression
unlines ["Hello", "World", "!"]"Hello\nWorld\n!\n"

Note that unlines . lines /= id when the input is not \n-terminated:

Example1 expression
unlines . lines $ "foo\nbar""foo\nbar\n"
valueunwords :: [String] -> String
#

unwords joins words with separating spaces (U+0020 SPACE).

unwords is neither left nor right inverse of words:

Example2 expressions
words (unwords [" "])[]unwords (words "foo\nbar")"foo bar"
Examples
Example1 expression
unwords ["Lorem", "ipsum", "dolor"]"Lorem ipsum dolor"
Example1 expression
unwords ["foo", "bar", "", "baz"]"foo bar  baz"
valueunzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])
#

The unzip4 function takes a list of quadruples and returns four lists, analogous to unzip.

valueunzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])
#

The unzip5 function takes a list of five-tuples and returns five lists, analogous to unzip.

valueunzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])
#

The unzip6 function takes a list of six-tuples and returns six lists, analogous to unzip.

valueunzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])
#

The unzip7 function takes a list of seven-tuples and returns seven lists, analogous to unzip.

valuewords :: String -> [String]
#

words breaks a string up into a list of words, which were delimited by white space (as defined by isSpace). This function trims any white spaces at the beginning and at the end.

Examples
Example1 expression
words "Lorem ipsum\ndolor"["Lorem","ipsum","dolor"]
Example1 expression
words " foo bar "["foo","bar"]
valuezip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]
#

The zip4 function takes four lists and returns a list of quadruples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]
#

The zip5 function takes five lists and returns a list of five-tuples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]
#

The zip6 function takes six lists and returns a list of six-tuples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezip7
  1. :: [a]
  2. -> [b]
  3. -> [c]
  4. -> [d]
  5. -> [e]
  6. -> [f]
  7. -> [g]
  8. -> [(a, b, c, d, e, f, g)]
#

The zip7 function takes seven lists and returns a list of seven-tuples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
#

The zipWith4 function takes a function which combines four elements, as well as four lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith5
  1. :: a -> b -> c -> d -> e -> f
  2. -> [a]
  3. -> [b]
  4. -> [c]
  5. -> [d]
  6. -> [e]
  7. -> [f]
#

The zipWith5 function takes a function which combines five elements, as well as five lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith6
  1. :: a -> b -> c -> d -> e -> f -> g
  2. -> [a]
  3. -> [b]
  4. -> [c]
  5. -> [d]
  6. -> [e]
  7. -> [f]
  8. -> [g]
#

The zipWith6 function takes a function which combines six elements, as well as six lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith7
  1. :: a -> b -> c -> d -> e -> f -> g -> h
  2. -> [a]
  3. -> [b]
  4. -> [c]
  5. -> [d]
  6. -> [e]
  7. -> [f]
  8. -> [g]
  9. -> [h]
#

The zipWith7 function takes a function which combines seven elements, as well as seven lists and returns a list of their point-wise combination, analogous to zipWith. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valueclamp :: Ord a => (a, a) -> a -> a
#
clamp (low, high) a = min high (max a low)

Function for ensuring 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.

Example1 expression
clamp (0, 10) 22
Example1 expression
clamp ('a', 'm') 'x''m'
valuecomparing :: 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) ...
valueforM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
#

forM is mapM with its arguments flipped. For a version that ignores the results see Data.Foldable.forM_.

valuemapAccumL :: 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:

Example1 expression
mapAccumL (\a b -> (a + b, a)) 0 [1..10](55,[0,1,3,6,10,15,21,28,36,45])
Example1 expression
mapAccumL (\a b -> (a <> show b, a)) "0" [1..5]("012345",["0","01","012","0123","01234"])
valuemapAccumR :: 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:

Example1 expression
mapAccumR (\a b -> (a + b, a)) 0 [1..10](55,[54,52,49,45,40,34,27,19,10,0])
Example1 expression
mapAccumR (\a b -> (a <> show b, a)) "0" [1..5]("054321",["05432","0543","054","05","0"])
valuetrace :: String -> a -> a
#

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.

Example2 expressions
let x = 123; f = showtrace ("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.

valuetraceIO :: String -> IO ()
#

The traceIO function outputs the trace message from the IO monad. This sequences the output with respect to other IO actions.

valuetraceShowId :: Show a => a -> a
#

Like traceShow but returns the shown value instead of a third value.

Example1 expression
traceShowId (1+2+3, "hello" ++ "world")(6,"helloworld")(6,"helloworld")
valuechar8 :: 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.

valuelatin1 :: TextEncoding
#

The Latin1 (ISO8859-1) encoding. This encoding maps bytes directly to the first 256 Unicode code points, and is thus not a complete Unicode encoding. An attempt to write a character greater than '\255' to a System.IO.Handle using the latin1 encoding will result in an error.

Look up the named Unicode encoding. May fail with

The set of known encodings is system-dependent, but includes at least:

  • UTF-8
  • UTF-16, UTF-16BE, UTF-16LE

  • UTF-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 //TRANSLIT will choose a replacement character for illegal sequences or code points.

  • a suffix of //ROUNDTRIP will 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:

  1. 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.

  2. 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 criterion, 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".

valueutf16 :: TextEncoding
#

The UTF-16 Unicode encoding (a byte-order-mark should be used to indicate endianness).

valueutf32 :: TextEncoding
#

The UTF-32 Unicode encoding (a byte-order-mark should be used to indicate endianness).

valueutf8_bom :: TextEncoding
#

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.

valueuserError :: String -> IOError
#

Construct an IOError 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)
valuehClose :: Handle -> IO ()
#

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.

valuehFlush :: Handle -> IO ()
#

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:

  • isFullError if the device is full;

  • isPermissionError if a system resource limit would be exceeded. It is unspecified whether the characters in the buffer are discarded or retained under these circumstances.

valuehIsEOF :: 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.

Is the handle connected to a terminal?

On Windows the result of hIsTerminalDevide might be misleading, because non-native terminals, such as MinTTY used in MSYS environments, are implemented via redirection. Use System.Win32.Types.withHandleToHANDLE System.Win32.MinTTY.isMinTTYHandle to recognise it. Also consider ansi-terminal package for crossplatform terminal support.

valuehLookAhead :: 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:

valuehSeek :: 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:

  • GHC.Internal.System.IO.Error.isIllegalOperationError if the Handle is not seekable, or does not support the requested seek mode.

  • isPermissionError if a system resource limit would be exceeded.

valuehSetBuffering :: 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 hdl is writable, the buffer is flushed as for hFlush;

  • if hdl is not writable, the contents of the buffer are discarded.

This operation may fail with:

  • isPermissionError if the handle has already been used for reading or writing and the implementation does not allow the buffering mode to be changed.

valuehSetEcho :: Handle -> Bool -> IO ()
#

Set the echoing status of a handle connected to a terminal.

valuehTell :: 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:

  • GHC.Internal.System.IO.Error.isIllegalOperationError if the Handle is not seekable.

valuehGetBuf :: 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 System.IO.TextEncoding and NewlineMode on the Handle, and reads bytes directly.

valuehGetBufNonBlocking :: 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 System.IO.TextEncoding and NewlineMode on the Handle, and reads bytes directly.

NOTE: on Windows, this function does not work correctly; it behaves identically to hGetBuf.

valuehGetBufSome :: 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 System.IO.TextEncoding and NewlineMode on the Handle, and reads bytes directly.

valuehGetChar :: 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:

valuehGetContents :: 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 treated like a closed handle, with the following exceptions:

  • Characters can be read from hdl by evaluating portions of the list returned by hGetContents hdl.

  • If the handle allows for independent reading and writing, as it is the case for socket handles, writing continues to be possible.

A semi-closed handle becomes closed:

  • if GHC.Internal.System.IO.hClose is 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:

valuehGetLine :: Handle -> IO String
#

Computation hGetLine hdl reads a line from the file or channel managed by hdl. hGetLine does not return the newline as part of the result.

A line is separated by the newline set with GHC.Internal.System.IO.hSetNewlineMode or nativeNewline by default. The read newline character(s) are not returned as part of the result.

If hGetLine encounters end-of-file at any point while reading in the middle of a line, it is treated as a line terminator and the (partial) line is returned.

This operation may fail with:

  • isEOFError if the end of file is encountered when reading the first character of the line.

Examples
Example1 expression
withFile "/home/user/foo" ReadMode hGetLine >>= putStrLnthis is the first line of the file :O
Example1 expression
withFile "/home/user/bar" ReadMode (replicateM 3 . hGetLine)["this is the first line","this is the second line","this is the third line"]
valuehPutBuf :: 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 System.IO.TextEncoding and NewlineMode on the Handle, and writes bytes directly.

This operation may fail with:

  • ResourceVanished if 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).

valuehPutChar :: 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:

valuehPutStr :: Handle -> String -> IO ()
#

Computation hPutStr hdl s writes the string s to the file or channel managed by hdl.

Note that hPutStr is not concurrency safe unless the BufferMode of hdl is set to LineBuffering or BlockBuffering:

Example2 expressions
let f = forkIO . hPutStr stdoutin do hSetBuffering stdout NoBuffering; f "This is a longer string"; f ":D"; f "Hello Haskell"; pure ()This: HDiesl lao  lHoansgkeerl lstring
Example2 expressions
let f = forkIO . hPutStr stdoutin do hSetBuffering stdout LineBuffering; f "This is a longer string"; f ":D"; f "Hello Haskell"; pure ()This is a longer string:DHello Haskell

This operation may fail with:

valuehPutStrLn :: Handle -> String -> IO ()
#

The same as hPutStr, but adds a newline character.

This operation may fail with the same errors, and has the same issues with concurrency, as hPutStr!

valuehWaitForInput :: 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:

  • isEOFError if 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.

Use the native newline representation on both input and output

nativeNewlineMode  = NewlineMode { inputNL  = nativeNewline
                                   outputNL = nativeNewline }

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 }
valueopenBinaryFile
  1. :: FilePath

    The path to the binary file that should be opened

  2. -> IOMode

    The mode in which the binary file should be opened

  3. -> IO Handle
#

The computation openBinaryFile path mode returns a file handle that can be used to interact with the binary file.

This is different from openFile as in that it does not use any file encoding.

valueopenFile
  1. :: FilePath

    The path to the file that should be opened

  2. -> IOMode

    The mode in which the file should be opened

  3. -> IO Handle
#

The computation openFile path mode returns a file handle that can be used to interact with the file.

The handle is open in text mode with localeEncoding. You can change the encoding with System.IO.hSetEncoding.

valuewithBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
#

The computation withBinaryFile path mode action opens the binary file and runs action with the obtained handle before closing the binary file.

This is different from withFile as in that it does not use any file encoding.

Even when an exception is raised within the action, the file will still be closed. This is why withBinaryFile path mode act is preferable to

openBinaryFile path mode >>= (\hdl -> act hdl >>= System.IO.hClose hdl)

See also: System.IO.bracket

valuewithFile
  1. :: FilePath

    The path to the file that should be opened

  2. -> IOMode

    The mode in which the file should be opened

  3. -> (Handle -> IO r)

    The action to run with the obtained handle

  4. -> IO r
#

The computation withFile path mode action opens the file and runs action with the obtained handle before closing the file.

Even when an exception is raised within the action, the file will still be closed. This is why withFile path mode act is preferable to

openFile path mode >>= (\hdl -> act hdl >>= System.IO.hClose hdl)

See also: System.IO.bracket

value(!!) :: HasCallStack => [a] -> Int -> a
#

List index (subscript) operator, starting from 0. It is an instance of the more general genericIndex, which takes an index of any integral type.

WARNING: This function is partial, and should only be used if you are sure that the indexing will not fail. Otherwise, use Data.List.!?.

WARNING: This function takes linear time in the index.

Examples
Example1 expression
['a', 'b', 'c'] !! 0'a'
Example1 expression
['a', 'b', 'c'] !! 2'c'
Example1 expression
['a', 'b', 'c'] !! 3*** Exception: Prelude.!!: index too large
Example1 expression
['a', 'b', 'c'] !! (-1)*** Exception: Prelude.!!: negative index
value(!?) :: [a] -> Int -> Maybe a
#

List index (subscript) operator, starting from 0. Returns Nothing if the index is out of bounds

This is the total variant of the partial !! operator.

WARNING: This function takes linear time in the index.

Examples
Example1 expression
['a', 'b', 'c'] !? 0Just 'a'
Example1 expression
['a', 'b', 'c'] !? 2Just 'c'
Example1 expression
['a', 'b', 'c'] !? 3Nothing
Example1 expression
['a', 'b', 'c'] !? (-1)Nothing
valuebreak :: (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 p is equivalent to span (not . p) and consequently to (takeWhile (not . p) xs, dropWhile (not . p) xs), even if p is _|_.

Laziness
Example1 expression
break undefined []([],[])
Example1 expression
fst (break (const True) undefined)*** Exception: Prelude.undefined
Example1 expression
fst (break (const True) (undefined : undefined))[]
Example1 expression
take 1 (fst (break (const False) (1 : undefined)))[1]

break produces the first component of the tuple lazily:

Example1 expression
take 10 (fst (break (const False) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
Example1 expression
break (> 3) [1,2,3,4,1,2,3,4]([1,2,3],[4,1,2,3,4])
Example1 expression
break (< 9) [1,2,3]([],[1,2,3])
Example1 expression
break (> 9) [1,2,3]([1,2,3],[])
valuecycle :: HasCallStack => [a] -> [a]
#

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.

Examples
Example1 expression
cycle []*** Exception: Prelude.cycle: empty list
Example1 expression
take 10 (cycle [42])[42,42,42,42,42,42,42,42,42,42]
Example1 expression
take 10 (cycle [2, 5, 7])[2,5,7,2,5,7,2,5,7,2]
Example1 expression
take 1 (cycle (42 : undefined))[42]
valuedrop :: Int -> [a] -> [a]
#

drop n xs returns the suffix of xs after the first n elements, or [] if n >= length xs.

It is an instance of the more general genericDrop, in which n may be of any integral type.

Examples
Example1 expression
drop 6 "Hello World!""World!"
Example1 expression
drop 3 [1,2,3,4,5][4,5]
Example1 expression
drop 3 [1,2][]
Example1 expression
drop 3 [][]
Example1 expression
drop (-1) [1,2][1,2]
Example1 expression
drop 0 [1,2][1,2]
valuedropWhile :: (a -> Bool) -> [a] -> [a]
#

dropWhile p xs returns the suffix remaining after takeWhile p xs.

Examples
Example1 expression
dropWhile (< 3) [1,2,3,4,5,1,2,3][3,4,5,1,2,3]
Example1 expression
dropWhile (< 9) [1,2,3][]
Example1 expression
dropWhile (< 0) [1,2,3][1,2,3]
valuefilter :: (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]
Examples
Example1 expression
filter odd [1, 2, 3][1,3]
Example1 expression
filter (\l -> length l > 3) ["Hello", ", ", "World", "!"]["Hello","World"]
Example1 expression
filter (/= 3) [1, 2, 3, 4, 3, 2, 1][1,2,4,2,1]
valuehead :: HasCallStack => [a] -> a
#

This is a partial function, it throws an error on empty lists. Use pattern matching, Data.List.uncons or listToMaybe instead. Consider refactoring to use Data.List.NonEmpty.

\mathcal{O}(1). Extract the first element of a list, which must be non-empty.

To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-} at the top of the file. To disable it throughout a package put the same options into ghc-options section of Cabal file. To disable it in GHCi put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file. See also the migration guide.

Examples
Example1 expression
head [1, 2, 3]1
Example1 expression
head [1..]1
Example1 expression
head []*** Exception: Prelude.head: empty list
valueinit :: HasCallStack => [a] -> [a]
#

This is a partial function, it throws an error on empty lists. Use Data.List.unsnoc instead. Consider refactoring to use Data.List.NonEmpty.

\mathcal{O}(n). Return all the elements of a list except the last one. The list must be non-empty.

To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-} at the top of the file. To disable it throughout a package put the same options into ghc-options section of Cabal file. To disable it in GHCi put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file. See also the migration guide.

Examples
Example1 expression
init [1, 2, 3][1,2]
Example1 expression
init [1][]
Example1 expression
init []*** Exception: Prelude.init: empty list
valueiterate :: (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), ...]
Laziness

Note that iterate is lazy, potentially leading to thunk build-up if the consumer doesn't force each element. See iterate' for a strict variant of this function.

Example3 expressions
let xs = iterate (\x -> if x == 0 then undefined else x - 1) 2xs[2,1,0,*** Exception: Prelude.undefinedlength (take 10 xs)10

In xs every element following 0 is bottom, but the list itself is infinitely long because it is generated without forcing its elements.

Examples
Example1 expression
take 10 $ iterate not True[True,False,True,False,True,False,True,False,True,False]
Example1 expression
take 10 $ iterate (+3) 42[42,45,48,51,54,57,60,63,66,69]

iterate id == repeat:

Example1 expression
take 10 $ iterate id 1[1,1,1,1,1,1,1,1,1,1]
valueiterate' :: (a -> a) -> a -> [a]
#

iterate' is the strict version of iterate.

It forces each element to weak head normal form (WHNF) before proceeding.

Laziness
Example3 expressions
let xs = iterate' (\x -> if x == 0 then undefined else x - 1) 2xs[2,1,0*** Exception: Prelude.undefinedlength (take 10 xs)*** Exception: Prelude.undefined

The list xs has 3 elements followed by a tail that is bottom.

valuelast :: HasCallStack => [a] -> a
#

This is a partial function, it throws an error on empty lists. Use Data.List.unsnoc instead. Consider refactoring to use Data.List.NonEmpty.

\mathcal{O}(n). Extract the last element of a list, which must be finite and non-empty.

To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-} at the top of the file. To disable it throughout a package put the same options into ghc-options section of Cabal file. To disable it in GHCi put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file. See also the migration guide.

Examples
Example1 expression
last [1, 2, 3]3
Example1 expression
last [1..]* Hangs forever *
Example1 expression
last []*** Exception: Prelude.last: empty list
valuelookup :: Eq a => a -> [(a, b)] -> Maybe b
#

\mathcal{O}(n). lookup key assocs looks up a key in an association list. For the result to be Nothing, the list must be finite.

Examples
Example1 expression
lookup 2 []Nothing
Example1 expression
lookup 2 [(1, "first")]Nothing
Example1 expression
lookup 2 [(1, "first"), (2, "second"), (3, "third")]Just "second"
valuerepeat :: a -> [a]
#

repeat x is an infinite list, with x the value of every element.

Examples
Example1 expression
take 10 $ repeat 17[17,17,17,17,17,17,17,17,17, 17]
Example1 expression
repeat undefined[*** Exception: Prelude.undefined
valuereplicate :: 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.

Examples
Example1 expression
replicate 0 True[]
Example1 expression
replicate (-1) True[]
Example1 expression
replicate 4 True[True,True,True,True]
valuereverse :: [a] -> [a]
#

\mathcal{O}(n). reverse xs returns the elements of xs in reverse order. xs must be finite.

Laziness

reverse is lazy in its elements.

Example1 expression
head (reverse [undefined, 1])1
Example1 expression
reverse (1 : 2 : undefined)*** Exception: Prelude.undefined
Examples
Example1 expression
reverse [][]
Example1 expression
reverse [42][42]
Example1 expression
reverse [2,5,7][7,5,2]
Example1 expression
reverse [1..]* Hangs forever *
valuescanl :: (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
Examples
Example1 expression
scanl (+) 0 [1..4][0,1,3,6,10]
Example1 expression
scanl (+) 42 [][42]
Example1 expression
scanl (-) 100 [1..4][100,99,97,94,90]
Example1 expression
scanl (\reversedString nextChar -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']["foo","afoo","bafoo","cbafoo","dcbafoo"]
Example1 expression
take 10 (scanl (+) 0 [1..])[0,1,3,6,10,15,21,28,36,45]
Example1 expression
take 1 (scanl undefined 'a' undefined)"a"
valuescanl' :: (b -> a -> b) -> b -> [a] -> [b]
#

\mathcal{O}(n). A strict version of scanl.

valuescanl1 :: (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, ...]
Examples
Example1 expression
scanl1 (+) [1..4][1,3,6,10]
Example1 expression
scanl1 (+) [][]
Example1 expression
scanl1 (-) [1..4][1,-1,-4,-8]
Example1 expression
scanl1 (&&) [True, False, True, True][True,False,False,False]
Example1 expression
scanl1 (||) [False, False, True, True][False,False,True,True]
Example1 expression
take 10 (scanl1 (+) [1..])[1,3,6,10,15,21,28,36,45,55]
Example1 expression
take 1 (scanl1 undefined ('a' : undefined))"a"
valuescanr :: (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.
Examples
Example1 expression
scanr (+) 0 [1..4][10,9,7,4,0]
Example1 expression
scanr (+) 42 [][42]
Example1 expression
scanr (-) 100 [1..4][98,-97,99,-96,100]
Example1 expression
scanr (\nextChar reversedString -> nextChar : reversedString) "foo" ['a', 'b', 'c', 'd']["abcdfoo","bcdfoo","cdfoo","dfoo","foo"]
Example1 expression
force $ scanr (+) 0 [1..]*** Exception: stack overflow
valuescanr1 :: (a -> a -> a) -> [a] -> [a]
#

\mathcal{O}(n). scanr1 is a variant of scanr that has no starting value argument.

Examples
Example1 expression
scanr1 (+) [1..4][10,9,7,4]
Example1 expression
scanr1 (+) [][]
Example1 expression
scanr1 (-) [1..4][-2,3,-1,4]
Example1 expression
scanr1 (&&) [True, False, True, True][False,False,True,True]
Example1 expression
scanr1 (||) [True, True, False, False][True,True,False,False]
Example1 expression
force $ scanr1 (+) [1..]*** Exception: stack overflow
valuespan :: (a -> Bool) -> [a] -> ([a], [a])
#

span, applied to a predicate p and a list xs, returns a tuple where first element is the longest prefix (possibly empty) of xs of elements that satisfy p and second element is the remainder of the list:

span p xs is equivalent to (takeWhile p xs, dropWhile p xs), even if p is _|_.

Laziness
Example4 expressions
span undefined []([],[])fst (span (const False) undefined)*** Exception: Prelude.undefinedfst (span (const False) (undefined : undefined))[]take 1 (fst (span (const True) (1 : undefined)))[1]

span produces the first component of the tuple lazily:

Example1 expression
take 10 (fst (span (const True) [1..]))[1,2,3,4,5,6,7,8,9,10]
Examples
Example1 expression
span (< 3) [1,2,3,4,1,2,3,4]([1,2],[3,4,1,2,3,4])
Example1 expression
span (< 9) [1,2,3]([1,2,3],[])
Example1 expression
span (< 0) [1,2,3]([],[1,2,3])
valuesplitAt :: 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 is an instance of the more general genericSplitAt, in which n may be of any integral type.

Laziness

It is equivalent to (take n xs, drop n xs) unless n is _|_: splitAt _|_ xs = _|_, not (_|_, _|_)).

The first component of the tuple is produced lazily:

Example1 expression
fst (splitAt 0 undefined)[]
Example1 expression
take 1 (fst (splitAt 10 (1 : undefined)))[1]
Examples
Example1 expression
splitAt 6 "Hello World!"("Hello ","World!")
Example1 expression
splitAt 3 [1,2,3,4,5]([1,2,3],[4,5])
Example1 expression
splitAt 1 [1,2,3]([1],[2,3])
Example1 expression
splitAt 3 [1,2,3]([1,2,3],[])
Example1 expression
splitAt 4 [1,2,3]([1,2,3],[])
Example1 expression
splitAt 0 [1,2,3]([],[1,2,3])
Example1 expression
splitAt (-1) [1,2,3]([],[1,2,3])
valuetail :: HasCallStack => [a] -> [a]
#

This is a partial function, it throws an error on empty lists. Replace it with drop 1, or use pattern matching or Data.List.uncons instead. Consider refactoring to use Data.List.NonEmpty.

\mathcal{O}(1). Extract the elements after the head of a list, which must be non-empty.

To disable the warning about partiality put {-# OPTIONS_GHC -Wno-x-partial -Wno-unrecognised-warning-flags #-} at the top of the file. To disable it throughout a package put the same options into ghc-options section of Cabal file. To disable it in GHCi put :set -Wno-x-partial -Wno-unrecognised-warning-flags into ~/.ghci config file. See also the migration guide.

Examples
Example1 expression
tail [1, 2, 3][2,3]
Example1 expression
tail [1][]
Example1 expression
tail []*** Exception: Prelude.tail: empty list
valuetake :: Int -> [a] -> [a]
#

take n, applied to a list xs, returns the prefix of xs of length n, or xs itself if n >= length xs.

It is an instance of the more general genericTake, in which n may be of any integral type.

Laziness
Example2 expressions
take 0 undefined[]take 2 (1 : 2 : undefined)[1,2]
Examples
Example1 expression
take 5 "Hello World!""Hello"
Example1 expression
take 3 [1,2,3,4,5][1,2,3]
Example1 expression
take 3 [1,2][1,2]
Example1 expression
take 3 [][]
Example1 expression
take (-1) [1,2][]
Example1 expression
take 0 [1,2][]
valuetakeWhile :: (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.

Laziness
Example1 expression
takeWhile (const False) undefined*** Exception: Prelude.undefined
Example1 expression
takeWhile (const False) (undefined : undefined)[]
Example1 expression
take 1 (takeWhile (const True) (1 : undefined))[1]
Examples
Example1 expression
takeWhile (< 3) [1,2,3,4,1,2,3,4][1,2]
Example1 expression
takeWhile (< 9) [1,2,3][1,2,3]
Example1 expression
takeWhile (< 0) [1,2,3][]
valueuncons :: [a] -> Maybe (a, [a])
#

\mathcal{O}(1). Decompose a list into its head and tail.

  • If the list is empty, returns Nothing.

  • If the list is non-empty, returns Just (x, xs), where x is the head of the list and xs its tail.

Examples
Example1 expression
uncons []Nothing
Example1 expression
uncons [1]Just (1,[])
Example1 expression
uncons [1, 2, 3]Just (1,[2,3])
valueunsnoc :: [a] -> Maybe ([a], a)
#

\mathcal{O}(n). Decompose a list into init and last.

  • If the list is empty, returns Nothing.

  • If the list is non-empty, returns Just (xs, x), where xs is the initial part of the list and x is its last element.

unsnoc is dual to uncons: for a finite list xs

unsnoc xs = (\(hd, tl) -> (reverse tl, hd)) <$> uncons (reverse xs)
Examples
Example1 expression
unsnoc []Nothing
Example1 expression
unsnoc [1]Just ([],1)
Example1 expression
unsnoc [1, 2, 3]Just ([1,2],3)
Laziness
Example1 expression
fst <$> unsnoc [undefined]Just []
Example1 expression
head . fst <$> unsnoc (1 : undefined)Just *** Exception: Prelude.undefined
Example1 expression
head . fst <$> unsnoc (1 : 2 : undefined)Just 1
valueunzip :: [(a, b)] -> ([a], [b])
#

unzip transforms a list of pairs into a list of first components and a list of second components.

Examples
Example1 expression
unzip []([],[])
Example1 expression
unzip [(1, 'a'), (2, 'b')]([1,2],"ab")
valueunzip3 :: [(a, b, c)] -> ([a], [b], [c])
#

The unzip3 function takes a list of triples and returns three lists of the respective components, analogous to unzip.

Examples
Example1 expression
unzip3 []([],[],[])
Example1 expression
unzip3 [(1, 'a', True), (2, 'b', False)]([1,2],"ab",[True,False])
valuezip :: [a] -> [b] -> [(a, b)]
#

\mathcal{O}(\min(m,n)). zip takes two lists and returns a list of corresponding pairs.

zip is right-lazy:

Example2 expressions
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.

Examples
Example1 expression
zip [1, 2, 3] ['a', 'b', 'c'][(1,'a'),(2,'b'),(3,'c')]

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:

Example1 expression
zip [1] ['a', 'b'][(1,'a')]
Example1 expression
zip [1, 2] ['a'][(1,'a')]
Example1 expression
zip [] [1..][]
Example1 expression
zip [1..] [][]
valuezip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
#

zip3 takes three lists and returns a list of triples, analogous to zip. It is capable of list fusion, but it is restricted to its first list argument and its resulting list.

valuezipWith :: (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..]

zipWith is right-lazy:

Example2 expressions
let f = undefinedzipWith f [] undefined[]

zipWith is capable of list fusion, but it is restricted to its first list argument and its resulting list.

Examples

zipWith (+) can be applied to two lists to produce the list of corresponding sums:

Example1 expression
zipWith (+) [1, 2, 3] [4, 5, 6][5,7,9]
Example1 expression
zipWith (++) ["hello ", "foo"] ["world!", "bar"]["hello world!","foobar"]
valuezipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
#

\mathcal{O}(\min(l,m,n)). 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..]
Examples
Example1 expression
zipWith3 (\x y z -> [x, y, z]) "123" "abc" "xyz"["1ax","2by","3cz"]
Example1 expression
zipWith3 (\x y z -> (x * y) + z) [1, 2, 3] [4, 5, 6] [7, 8, 9][11,18,27]
valueisEmptyMVar :: 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.

valueputMVar :: 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:

  • putMVar is single-wakeup. That is, if there are multiple threads blocked in putMVar, and the MVar becomes empty, only one thread will be woken up. The runtime guarantees that the woken thread completes its putMVar operation.

  • 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 using MVars.

valuereadMVar :: MVar a -> IO a
#

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. The runtime guarantees that all woken threads complete their readMVar operation.

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
valuetakeMVar :: MVar a -> IO a
#

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:

  • takeMVar is single-wakeup. That is, if there are multiple threads blocked in takeMVar, and the MVar becomes full, only one thread will be woken up. The runtime guarantees that the woken thread completes its takeMVar operation.

  • 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 using MVars.

valuelexLitChar :: ReadS String
#

Read a string representation of a character, using Haskell source-language escape conventions. For example:

lexLitChar  "\\nHello"  =  [("\\n", "Hello")]
valuereadLitChar :: 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")]
valueintToDigit :: Int -> Char
#

Convert an Int in the range 0..15 to the corresponding single digit Char. This function fails on other inputs, and generates lower-case hexadecimal digits.

valueshowLitChar :: 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
valuegetArgs :: IO [String]
#

Computation getArgs returns a list of the program's command line arguments (not including the program name).

valuegetEnvironment :: 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.

valuegetProgName :: 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.

valuelookupEnv :: 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.

valuesetEnv :: 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.

Beware that this function must not be executed concurrently with getEnv, lookupEnv, getEnvironment and such. One thread reading environment variables at the same time with another one modifying them can result in a segfault, see Setenv is not Thread Safe for discussion.

valueunsetEnv :: String -> IO ()
#

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.

Beware that this function must not be executed concurrently with getEnv, lookupEnv, getEnvironment and such. One thread reading environment variables at the same time with another one modifying them can result in a segfault, see Setenv is not Thread Safe for discussion.

Get an action to query the absolute pathname of the current executable.

If the operating system provides a reliable way to determine the current executable, return the query action, otherwise return Nothing. The action is defined on FreeBSD, Linux, MacOS, NetBSD, Solaris, and Windows.

Even where the query action is defined, there may be situations where no result is available, e.g. if the executable file was deleted while the program is running. Therefore the result of the query action is a Maybe FilePath.

Note that for scripts and interactive sessions, the result is the path to the interpreter (e.g. ghci.)

Note also that while most operating systems return Nothing if the executable file was deleted/unlinked, some (including NetBSD) return the original path.

Returns the absolute pathname of the current executable, or argv[0] if the operating system does not provide a reliable way query 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.

If the executable has been deleted, behaviour is ill-defined and varies by operating system. See executablePath for a more reliable way to query the current executable.

valueappendFile :: 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.

This operation may fail with the same errors as hPutStr and withFile.

Examples

The following example could be more efficently written by acquiring a handle instead with openFile and using the computations capable of writing to handles such as hPutStr.

Example2 expressions
let fn = "hello_world"in writeFile fn "hello" >> appendFile fn " world!" >> (readFile fn >>= putStrLn)"hello world!"
Example2 expressions
let fn = "foo"; output = readFile' fn >>= putStrLnin output >> appendFile fn (show [1,2,3]) >> outputthis is what's in the filethis is what's in the file[1,2,3]
valuegetChar :: IO Char
#

Read a single character from the standard input device.

getChar is implemented as hGetChar stdin.

This operation may fail with the same errors as hGetChar.

Examples
Example1 expression
getChara'a'
Example1 expression
getChar>'\n'
valuegetContents :: IO String
#

The getContents operation returns all user input as a single string, which is read lazily as it is needed.

getContents is implemented as hGetContents stdin.

This operation may fail with the same errors as hGetContents.

Examples
Example1 expression
getContents >>= putStr> aaabbbccc :Daaabbbccc :D> I hope you have a great dayI hope you have a great day> ^D
Example1 expression
getContents >>= print . length> abc> <3> def ^D11
valuegetContents' :: IO String
#

The getContents' operation returns all user input as a single string, which is fully read before being returned

getContents' is implemented as hGetContents' stdin.

This operation may fail with the same errors as hGetContents'.

Examples
Example1 expression
getContents' >>= putStr> aaabbbccc :D> I hope you have a great dayaaabbbccc :DI hope you have a great day
Example1 expression
getContents' >>= print . length> abc> <3> def ^D11
valuegetLine :: IO String
#

Read a line from the standard input device.

getLine is implemented as hGetLine stdin.

This operation may fail with the same errors as hGetLine.

Examples
Example1 expression
getLine> Hello World!"Hello World!"
Example1 expression
getLine>""
valuehPrint :: Show a => Handle -> a -> IO ()
#

Computation hPrint hdl t writes the string representation of t given by the show function to the file or channel managed by hdl and appends a newline.

This operation may fail with the same errors as hPutStrLn

Examples
Example1 expression
hPrint stdout [1,2,3][1,2,3]
Example1 expression
hPrint stdin [4,5,6]*** Exception: <stdin>: hPutStr: illegal operation (handle is not open for writing)
valuehReady :: Handle -> IO Bool
#

Computation hReady hdl indicates whether at least one item is available for input from handle hdl.

This operation may fail with:

valueinteract :: (String -> String) -> IO ()
#

interact f takes the entire input from stdin and applies f to it. The resulting string is written to the stdout device.

Note that this operation is lazy, which allows to produce output even before all input has been consumed.

This operation may fail with the same errors as getContents and putStr.

If it doesn't produce output the buffering settings may not be correct, use ^D (ctrl+D) to close stdin which forces the buffer to be consumed.

You may wish to set the buffering style appropriate to your program's needs before using this function, for example:

main :: IO ()
main = do
  hSetBuffering stdin LineBuffering
  hSetBuffering stdout NoBuffering
  interact (concatMap (str -> str ++ str) . L.lines)
Examples
Example1 expression
interact (\str -> str ++ str)> hi :)hi :)> ^Dhi :)
Example1 expression
interact (const ":D"):D
Example1 expression
interact (show . words)> hello world!> I hope you have a great day> ^D["hello","world!","I","hope","you","have","a","great","day"]
valueopenTempFile
  1. :: FilePath

    Directory in which to create the file

  2. -> 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. On Windows, the template prefix may be truncated to 3 chars, e.g. "foobar.ext" will be "fooXXX.ext".

  3. -> 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.

valueprint :: 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.

print is implemented as putStrLn . show

This operation may fail with the same errors, and has the same issues with concurrency, as hPutStr!

Examples
Example1 expression
print [1, 2, 3][1,2,3]

Be careful when using print for outputting strings, as this will invoke show and cause strings to be printed with quotation marks and non-ascii symbols escaped.

Example1 expression
print "λ :D""\995 :D"

A program to print the first 8 integers and their powers of 2 could be written as:

Example1 expression
print [(n, 2^n) | n <- [0..8]][(0,1),(1,2),(2,4),(3,8),(4,16),(5,32),(6,64),(7,128),(8,256)]
valueputChar :: Char -> IO ()
#

Write a character to the standard output device

putChar is implemented as hPutChar stdout.

This operation may fail with the same errors as hPutChar.

Examples

Note that the following do not put a newline.

Example1 expression
putChar 'x'x
Example1 expression
putChar '\0042'*
valueputStr :: String -> IO ()
#

Write a string to the standard output device

putStr is implemented as hPutStr stdout.

This operation may fail with the same errors, and has the same issues with concurrency, as hPutStr!

Examples

Note that the following do not put a newline.

Example1 expression
putStr "Hello, World!"Hello, World!
Example1 expression
putStr "\0052\0042\0050"4*2
valueputStrLn :: String -> IO ()
#

The same as putStr, but adds a newline character.

This operation may fail with the same errors, and has the same issues with concurrency, as hPutStr!

valuereadFile :: 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.

This operation may fail with the same errors as hGetContents and openFile.

Examples
Example1 expression
readFile "~/hello_world""Greetings!"
Example1 expression
take 5 <$> readFile "/dev/zero""\NUL\NUL\NUL\NUL\NUL"
valuereadIO :: Read a => String -> IO a
#

The readIO function is similar to read except that it signals parse failure to the IO monad instead of terminating the program.

This operation may fail with:

Examples
Example1 expression
fmap (+ 1) (readIO "1")2
Example1 expression
readIO "not quite ()" :: IO ()*** Exception: user error (Prelude.readIO: no parse)
valuereadLn :: Read a => IO a
#

The readLn function combines getLine and readIO.

This operation may fail with the same errors as getLine and readIO.

Examples
Example1 expression
fmap (+ 5) readLn> 2530
Example1 expression
readLn :: IO String> this is not a string literal*** Exception: user error (Prelude.readIO: no parse)
valuewriteFile :: FilePath -> String -> IO ()
#

The computation writeFile file str function writes the string str, to the file file.

This operation may fail with the same errors as hPutStr and withFile.

Examples
Example1 expression
writeFile "hello" "world" >> readFile "hello""world"
Example1 expression
writeFile "~/" "D:"*** Exception: ~/: withFile: inappropriate type (Is a directory)

I/O error where the operation failed because one of its arguments is a single-use resource, which is already being used.

valuecatchIOError :: IO a -> (IOError -> IO a) -> IO a
#

The catchIOError function establishes a handler that receives any IOError raised in the action protected by catchIOError. An IOError is caught by the most recent handler established by one of the exception handling functions. These handlers are not selective: all IOErrors 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 IOError value and exits the program.

Non-I/O exceptions are not caught by this variant; to catch all exceptions, use catch from Control.Exception.

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).

valueisEOFError :: IOError -> Bool
#

An error indicating that an IO operation failed because the end of file has been reached.

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.

An error indicating that an IO operation failed because the user does not have sufficient operating system privilege to perform that operation.

I/O error where the operation failed because the user does not have sufficient operating system privilege to perform that operation.

I/O error where the operation failed because the user does not have sufficient operating system privilege to perform that operation.

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.

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:

Example7 expressions
generalCategory 'a'LowercaseLettergeneralCategory 'A'UppercaseLettergeneralCategory '0'DecimalNumbergeneralCategory '%'OtherPunctuationgeneralCategory '♥'OtherSymbolgeneralCategory '\31'ControlgeneralCategory ' 'Space
valueisAlpha :: Char -> Bool
#

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.

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".

valueisAlphaNum :: 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, e.g., Roman numerals like V, full-width digits like '1' (aka '65297').

This function returns True if its argument has one of the following GeneralCategorys, or False otherwise:

valueisAscii :: Char -> Bool
#

Selects the first 128 characters of the Unicode character set, corresponding to the ASCII character set.

valueisControl :: Char -> Bool
#

Selects control characters, which are the non-printing characters of the Latin-1 subset of Unicode.

valueisHexDigit :: Char -> Bool
#

Selects ASCII hexadecimal digits, i.e. '0'..'9', 'a'..'f', 'A'..'F'.

valueisLatin1 :: Char -> Bool
#

Selects the first 256 characters of the Unicode character set, corresponding to the ISO 8859-1 (Latin-1) character set.

valueisLower :: Char -> Bool
#

Selects lower-case alphabetic Unicode characters (letters).

Note: this predicate does not work for letter-like characters such as: 'ⓐ' (U+24D0 circled Latin small letter a) and 'ⅳ' (U+2173 small Roman numeral four). This is due to selecting only characters with the GeneralCategory LowercaseLetter.

See isLowerCase for a more intuitive predicate.

valueisLowerCase :: Char -> Bool
#

Selects lower-case Unicode letter-like characters.

Note: this predicate selects characters with the Unicode property Lowercase, which includes letter-like characters such as: 'ⓐ' (U+24D0 circled Latin small letter a) and 'ⅳ' (U+2173 small Roman numeral four).

See isLower for the legacy predicate.

valueisPunctuation :: 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:

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:

Example6 expressions
isPunctuation 'a'FalseisPunctuation '7'FalseisPunctuation '♥'FalseisPunctuation '"'TrueisPunctuation '?'TrueisPunctuation '—'True
valueisSpace :: Char -> Bool
#

Returns True for any Unicode space character, and the control characters \t, \n, \r, \f, \v.

valueisSymbol :: Char -> Bool
#

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:

Example3 expressions
isSymbol 'a'FalseisSymbol '6'FalseisSymbol '='True

The definition of "math symbol" may be a little counter-intuitive depending on one's background:

Example2 expressions
isSymbol '+'TrueisSymbol '-'False
valueisUpper :: Char -> Bool
#

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.

Note: this predicate does not work for letter-like characters such as: 'Ⓐ' (U+24B6 circled Latin capital letter A) and 'Ⅳ' (U+2163 Roman numeral four). This is due to selecting only characters with the GeneralCategory UppercaseLetter or TitlecaseLetter.

See isUpperCase for a more intuitive predicate. Note that unlike isUpperCase, isUpper does select title-case characters such as 'Dž' (U+01C5 Latin capital letter d with small letter z with caron) or 'ᾯ' (U+1FAF Greek capital letter omega with dasia and perispomeni and prosgegrammeni).

valueisUpperCase :: Char -> Bool
#

Selects upper-case Unicode letter-like characters.

Note: this predicate selects characters with the Unicode property Uppercase, which include letter-like characters such as: 'Ⓐ' (U+24B6 circled Latin capital letter A) and 'Ⅳ' (U+2163 Roman numeral four).

See isUpper for the legacy predicate. Note that unlike isUpperCase, isUpper does select title-case characters such as 'Dž' (U+01C5 Latin capital letter d with small letter z with caron) or 'ᾯ' (U+1FAF Greek capital letter omega with dasia and perispomeni and prosgegrammeni).

valuetoLower :: Char -> Char
#

Convert a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged.

valuetoTitle :: Char -> Char
#

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.

valuetoUpper :: Char -> Char
#

Convert a letter to the corresponding upper-case letter, if any. Any other character is returned unchanged.

valueargsToCliOpts :: [String] -> [String] -> IO CliOpts
#

A helper for addons/scripts: this parses hledger CliOpts from these command line arguments and add-on command names, roughly how hledger main does. If option parsing/validating fails, it exits the program with usageError. Unlike main, this does not read extra args from a config file or search for addons; to do those things, mimic the code in main for now.

Derive 1. an account tree and 2. each account's total exclusive and inclusive changes associated with dates from a list of postings and a function for associating a date to each posting (usually representing the start dates of report subperiods). This is the core of the balance command (and of *ledger). The accounts are returned as a tree.

valueaccountTree :: Monoid a => AccountName -> [AccountName] -> Account a
#

Convert a list of account names to a tree of Account objects, with just the account names filled in and an empty balance. A single root account with the given name is added.

Derive 1. an account tree and 2. each account's total exclusive and inclusive changes associated with dates from a list of postings and a function for associating a date to each posting (usually representing the start dates of report subperiods). 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.)

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

valueflattenAccounts :: Account a -> [Account a]
#

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!

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).

Sort each group of siblings in an account tree by declaration order, then account name. So each group will contain first the declared accounts, in the same order as their account directives were parsed, and then the undeclared accounts, sorted by account name.

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.

The level (depth) of an account name.

Example3 expressions
accountNameLevel ""  -- special case0accountNameLevel "assets"1accountNameLevel "assets:cash"2

Regular expressions matching common English top-level account names, used as a fallback when account types are not declared.

Clip an account name to a given DepthSpec, first checking whether it matches any of the regular expressions controlling depth. If so, clip to the depth of the most specific of those matches, i.e. the one which starts matching the latest as you progress up the parents of the account. Otherwise clip to the flat depth provided, or return the full name if Nothing.

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.

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!
valueescapeName :: AccountName -> Text
#

Escape an AccountName for use within a regular expression. >>> putStr . T.unpack $ escapeName "First?!#$*?$(*) !^#*? %)*!#" First?!#$*?$\* !^#*? %)*!#

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"]

Calculate the depth to which an account name should be clipped for a given DepthSpec.

First checking whether the account name matches any of the regular expressions controlling depth. If so, clip to the depth of the most specific of those matches, i.e. the one which starts matching the latest as you progress up the parents of the account. Otherwise clip to the flat depth provided, or return the full name if Nothing.

A top-level account prefixed to some accounts in budget reports. Defined here so it can be ignored by accountNameDrop.

valueamountCost :: Amount -> Amount
#

Convert a amount to its total cost in another commodity, using its attached cost amount if it has one. Notes:

  • cost amounts must be MixedAmounts with exactly one component Amount (or there will be a runtime error XXX)

  • cost amounts should be positive in the Journal (though this is currently not enforced)

valueamountIsZero :: Amount -> Bool
#

Is this Amount (and its total cost, if it has one) exactly zero, ignoring its display precision ?

valueamountLooksZero :: Amount -> Bool
#

Do this Amount and (and its total cost, 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.

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.

We often want to display "infinite decimal" amounts rounded to some readable number of digits, while still displaying amounts with a large but "non infinite" number of decimal digits (eg 10 or 100 or 200 digits) in full. This helper is like amountSetFullPrecision, but with some refinements:

  1. A maximum display precision can be specified, setting a hard upper limit.

  2. If no limit is specified, and the internal precision is the maximum (255), indicating an infinite decimal, display precision is set to a smaller default (8).

This function always sets an explicit display precision (ie, Precision n).

valueamounts :: 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 costs or total costs

  • 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

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.

valueamountsRaw :: 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 cost commodity, then by unit cost from most negative to most positive.

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.

valuecshowAmount :: 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}

The fallback display precision used when showing amounts representing an infinite decimal.

Return an unnormalised MixedAmount containing just the amounts in the requested commodity from the original mixed amount.

The result will contain at least one Amount of the requested commodity, even if the original mixed amount did not (with quantity zero in that case, and this would be discarded when the mixed amount is next normalised).

The result can contain more than one Amount of the requested commodity, eg because there were several with different costs, or simply because the original mixed amount was was unnormalised.

Like defaultFmt but show zero amounts with commodity symbol and styling, like non-zero amounts.

valuegetAmounts :: Amount -> [Amount]
#

Get an amount and its attached cost amount if any. Returns one or two amounts.

valueinvertAmount :: Amount -> Amount
#

Invert an amount (replace its quantity q with 1/q). The amount's transacted price, if any, is not changed. An amount with zero quantity is left unchanged.

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.

valuemaIsNonZero :: MixedAmount -> Bool
#

Is this mixed amount non-zero, ignoring its display precision?

A convenient alias for not . mixedAmountIsZero.

valuemaIsZero :: MixedAmount -> Bool
#

Is this mixed amount exactly zero, ignoring its display precision?

A convenient alias for mixedAmountIsZero.

A (slightly more) machine-readable amount format; like oneLineNoCostFmt but don't show digit group marks.

valuemissingamt :: 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.

A special mixed amount used as a marker, meaning "no explicit amount provided here, infer it when needed".

In each component amount, increase the display precision sufficiently to render it exactly if possible, but not more than the given max precision, and if no max precision is given and the amount has infinite decimals, limit display precision to a hard-coded smaller number (8). See amountSetFullPrecisionUpTo.

valuenullamt :: Amount
#

The empty simple amount - a zero with no commodity symbol or cost and the default amount display style.

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)".

valueshowAmount :: Amount -> String
#

Render an amount using its display style and the default amount format. Zero-equivalent amounts are shown as just "0". The special "missing" amount is shown as the empty string.

Render an amount using its display style and the given amount format, as a builder for efficiency. (This can be converted to a Text with wbToText or to a String with wbUnpack). The special "missing" amount is displayed as the empty string.

Get a string representation of an amount for debugging, appropriate to the current debug level. 9 shows maximum detail.

Like showAmount, but show a zero amount's commodity if it has one.

showAmountWithZeroCommodity = wbUnpack . showAmountB defaultFmt{displayZeryCommodity=True}

Get the string representation of an amount, without any @ cost.

showAmountWithoutCost = wbUnpack . showAmountB noCostFmt

Render a mixed amount using its amount display styles and the default amount format, after normalising it (to at most one amount in each of its commodities). See showMixedAmountB for special cases.

Render a mixed amount using its amount display styles and the given amount format, as a builder for efficiency. (This can be converted to a Text with wbToText or to a String with wbUnpack).

Warning: this (and its showMixedAmount aliases above) basically assumes amounts have no costs. It can show misleading costs or not show costs which are there.

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.

Zero-equivalent amounts are shown as just "0".

The special "missing" amount is shown as the empty string (?).

Like showMixedAmountOneLineWithoutCost, 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. See showMixedAmountB for special cases.

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.

Get the string representation of a mixed amount, without showing any costs. With a True argument, adds ANSI codes to show negative amounts in red. See showMixedAmountB for special cases.

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.

Balance this isolated 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.

Note this is not as accurate as balanceTransactionInJournal, which considers the whole journal when calculating balance assignments and balance assertions.

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.

valuecurrencyCodeToSymbol :: CurrencyCode -> Maybe CurrencySymbol
#

Look for a currency symbol corresponding to this ISO 4217 currency code.

Example1 expression
currencyCodeToSymbol "CZK"  -- Just "Kč"Just "K\269"
valuecurrencySymbolToCode :: CurrencySymbol -> Maybe CurrencyCode
#

Look for a ISO 4217 currency code corresponding to this currency symbol.

Example2 expressions
currencySymbolToCode ""NothingcurrencySymbolToCode "$"Just "USD"
valuedaysSpan :: [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).

valuefixSmartDate :: 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:
Example32 expressions
:set -XOverloadedStringslet 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"

refdate is Wednesday, 2008-11-26 >>> t "last wednesday" "2008-11-19" >>> t "this wednesday" "2008-12-03" >>> t "next wednesday" "2008-12-03" >>> t "last january" "2008-01-01" >>> t "this january" "2009-01-01" >>> t "next january" "2009-01-01" >>> t "last november" "2007-11-01" >>> t "this november" "2009-11-01" >>> t "next november" "2009-11-01"

Example5 expressions
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"
valuefixSmartDateStr :: Day -> Text -> Text
#

Convert a smart date string to an explicit yyyy/mm/dd string using the provided reference date, or raise an error.

valueisEmptySpan :: DateSpan -> Bool
#

Is this an empty span, ie closed with the end date on or before the start date ?

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.

valuenextNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day
#

Find the next occurrence of some nth weekday of a month, on or after the given date d.

Example4 expressions
let wed22nd = fromGregorian 2017 11 22nextNthWeekdayOfMonth 3 3 wed22nd  -- next third wednesday2017-12-20nextNthWeekdayOfMonth 4 3 wed22nd  -- next fourth wednesday2017-11-22nextNthWeekdayOfMonth 5 3 wed22nd  -- next fifth wednesday2017-11-29
valuenextmonthandday :: Month -> MonthDay -> Day -> Day
#

Find the next occurrence of the specified month and day of month, on or after the given date. The month should be 1-12 and the day of month should be 1-31, or an error will be raised.

Example4 expressions
let wed22nd = fromGregorian 2017 11 22nextmonthandday 11 21 wed22nd2018-11-21nextmonthandday 11 22 wed22nd2017-11-22nextmonthandday 11 23 wed22nd2017-11-23
valuenextnthdayofmonth :: MonthDay -> Day -> Day
#

Find the next occurrence of the specified day of month, on or after the given date. The day of month should be 1-31, or an error will be raised.

Example4 expressions
let wed22nd = fromGregorian 2017 11 22nextnthdayofmonth 21 wed22nd2017-12-21nextnthdayofmonth 22 wed22nd2017-11-22nextnthdayofmonth 23 wed22nd2017-11-23

For given date d find week-long interval that starts on nth day of week and covers it.

Examples: 2017-11-22 is Wed. Week-long intervals that cover it and start on Mon, Tue or Wed will start in the same week. However intervals that start on Thu or Fri should start in prev week: >>> let wed22nd = fromGregorian 2017 11 22 >>> nthdayofweekcontaining 1 wed22nd 2017-11-20 >>> nthdayofweekcontaining 2 wed22nd 2017-11-21 >>> nthdayofweekcontaining 3 wed22nd 2017-11-22 >>> nthdayofweekcontaining 4 wed22nd 2017-11-16 >>> nthdayofweekcontaining 5 wed22nd 2017-11-17

valueparsedate :: String -> Maybe Day
#

A simple date parsing helper: parses these YMD date string formats: `YYYY-MM-DD`, `YYYYMMDD`, YYYY.MM.DD or YYYYMMDD, where the month and day each have two digits and the year has one or more.

This is different from the Smart Dates of the CLI and period expressions ("smartdate", below) and not quite the same as the Simple Dates of the journal ("datep", in Hledger.Read.Common). It's mainly for internal or interactive use, eg when debugging - but currently is also used in a few user-facing places, such as: parsing --value's argument, parsing .latest files, and parsing hledger's --version output (which uses unseparated dates).

Unseparated dates were added in 2025 for convenience. Note it means many integers will now parse successfully.

Example7 expressions
parsedate "2008/02/03"Just 2008-02-03parsedate "2008/02/03/"Nothingparsedate "2008/02/30"Nothingparsedate "2025-01-01"Just 2025-01-01parsedate "2025.01.01"Just 2025-01-01parsedate "20250101"Just 2025-01-01parsedate "00101"Just 0000-01-01

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).

Example26 expressions
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 (MonthDay 2,DateSpan ..)p "every 2nd day"Right (MonthDay 2,DateSpan ..)p "every 2nd day 2009.."Right (MonthDay 2,DateSpan 2009-01-01..)p "every 2nd day 2009-"Right (MonthDay 2,DateSpan 2009-01-01..)p "every 29th Nov"Right (MonthAndDay 11 29,DateSpan ..)p "every 29th nov ..2009"Right (MonthAndDay 11 29,DateSpan ..2008-12-31)p "every nov 29th"Right (MonthAndDay 11 29,DateSpan ..)p "every Nov 29th 2009.."Right (MonthAndDay 11 29,DateSpan 2009-01-01..)p "every 11/29 from 2009"Right (MonthAndDay 11 29,DateSpan 2009-01-01..)p "every 11/29 since 2009"Right (MonthAndDay 11 29,DateSpan 2009-01-01..)p "every 2nd Thursday of month to 2009"Right (NthWeekdayOfMonth 2 4,DateSpan ..2008-12-31)p "every 1st monday of month to 2009"Right (NthWeekdayOfMonth 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 (MonthDay 2,DateSpan ..)p "every 2nd day"Right (MonthDay 2,DateSpan ..)p "every 2nd day 2009.."Right (MonthDay 2,DateSpan 2009-01-01..)p "every 2nd day of month 2009.."Right (MonthDay 2,DateSpan 2009-01-01..)
valueprevNthWeekdayOfMonth :: Int -> WeekDay -> Day -> Day
#

Find the previous occurrence of some nth weekday of a month, on or before the given date d.

Example3 expressions
let wed22nd = fromGregorian 2017 11 22prevNthWeekdayOfMonth 4 3 wed22nd2017-11-22prevNthWeekdayOfMonth 5 2 wed22nd2017-10-31
valueshowDateSpan :: DateSpan -> Text
#

Render a datespan as a display string, abbreviating into a compact form if possible. Warning, hides whether dates are Exact or Flex.

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)
last/this/next monday/mon                   (the previous or next named weekday; this=next)
last/next january/jan                       (previous or next start of named month; this disallowed to avoid confusion)
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)

Fill any unspecified dates in the first span with the dates from the second one (if specified there). Sort of a one-way spanIntersect. This one can create an invalid span that'll always be empty.

Example1 expression
:{ DateSpan (Just $ Exact $ fromGregorian 2024 1 1) Nothing `spanDefaultsFrom` DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2):}DateSpan 2024-01-01
Example1 expression
:{ DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing `spanDefaultsFrom` DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2):}DateSpan 2025-01-01..2024-01-01

Extend the definite start/end dates of the first span, if needed, to include the definite start/end dates of the second span. Andor, replace open startend dates in the first span with definite start/end dates from the second. Unlike spanUnion, open start/end dates in the second are ignored.

Example9 expressions
ys2024 = fromGregorian 2024 01 01ys2025 = fromGregorian 2025 01 01to2024 = DateSpan Nothing               (Just $ Exact ys2024)all2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)partof2024 = DateSpan (Just $ Exact $ fromGregorian 2024 03 01) (Just $ Exact $ fromGregorian 2024 09 01)spanExtend to2024 all2024DateSpan 2024spanExtend all2024 to2024DateSpan 2024spanExtend partof2024 all2024DateSpan 2024spanExtend all2024 partof2024DateSpan 2024

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

Calculate the union of two datespans. If either span is open-ended, the union will be too.

Example6 expressions
ys2024 = fromGregorian 2024 01 01ys2025 = fromGregorian 2025 01 01to2024 = DateSpan Nothing               (Just $ Exact ys2024)in2024 = DateSpan (Just $ Exact ys2024) (Just $ Exact ys2025)spanUnion to2024 in2024DateSpan ..2024-12-31spanUnion in2024 to2024DateSpan ..2024-12-31

A smarter version of spanDefaultsFrom that avoids creating invalid spans ending before they begin. Kept separate for now to reduce risk.

Example1 expression
:{ DateSpan (Just $ Exact $ fromGregorian 2025 1 1) Nothing `spanValidDefaultsFrom` DateSpan (Just $ Exact $ fromGregorian 2024 1 1) (Just $ Exact $ fromGregorian 2024 1 2):}DateSpan 2025-01-01..
valuespansSpan :: [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.

valueyearp :: TextParser m Integer
#

Parse a year number from a Text, making sure that at least four digits are used.

Construct a DayPartition from a non-empty list of period boundary dates (start dates plus a final exclusive end date).

Example1 expression
boundariesToDayPartition (fromGregorian 2025 01 01 :| [fromGregorian 2025 02 01])DayPartition {dayPartitionToPeriodData = PeriodData{ pdpre = 2024-12-31, pdperiods = fromList [(2025-01-01,2025-01-31)]}}

Find the start and end dates of the period within a DayPartition which contains a given day. If the day is after the end of the last period, it is assumed to be within the last period. If the day is before the start of the first period (ie, in the historical period), only the historical period's end date is returned.

Get the natural start for the given interval that falls on or before the given day, when applicable. Works for Weeks, Months, Quarters, Years, eg.

Split a DateSpan into a DayPartition consisting of consecutive exact spans of the specified Interval, or Nothing if the span is invalid. If no interval is specified, the original span is returned. If the original span is the null date span, ie unbounded, Nothing is returned. If the original span is empty, eg if the end date is <= the start date, Nothing is returned.

Date adjustment

Some intervals respect the "adjust" flag (years, quarters, months, weeks, every Nth weekday of month seem to be the ones that need it). This will move the start date earlier, if needed, to the previous natural interval boundary (first of year, first of quarter, first of month, monday, previous Nth weekday of month). Related: #1982 #2218

The end date is always moved later if needed to the next natural interval boundary, so that the last period is the same length as the others.

Examples
Example14 expressions
let t i y1 m1 d1 y2 m2 d2 = fmap dayPartitionToNonEmpty . splitSpan True i $ DateSpan (Just $ Flex $ fromGregorian y1 m1 d1) (Just $ Flex $ fromGregorian y2 m2 d2)t NoInterval 2008 01 01 2009 01 01Just ((2008-01-01,2008-12-31) :| [])t (Quarters 1) 2008 01 01 2009 01 01Just ((2008-01-01,2008-03-31) :| [(2008-04-01,2008-06-30),(2008-07-01,2008-09-30),(2008-10-01,2008-12-31)])splitSpan True (Quarters 1) nulldatespanNothingt (Days 1) 2008 01 01 2008 01 01  -- an empty datespanNothingt (Quarters 1) 2008 01 01 2008 01 01Nothingt (Months 1) 2008 01 01 2008 04 01Just ((2008-01-01,2008-01-31) :| [(2008-02-01,2008-02-29),(2008-03-01,2008-03-31)])t (Months 2) 2008 01 01 2008 04 01Just ((2008-01-01,2008-02-29) :| [(2008-03-01,2008-04-30)])t (Weeks 1) 2008 01 01 2008 01 15Just ((2007-12-31,2008-01-06) :| [(2008-01-07,2008-01-13),(2008-01-14,2008-01-20)])t (Weeks 2) 2008 01 01 2008 01 15Just ((2007-12-31,2008-01-13) :| [(2008-01-14,2008-01-27)])t (MonthDay 2) 2008 01 01 2008 04 01Just ((2008-01-02,2008-02-01) :| [(2008-02-02,2008-03-01),(2008-03-02,2008-04-01)])t (NthWeekdayOfMonth 2 4) 2011 01 01 2011 02 15Just ((2010-12-09,2011-01-12) :| [(2011-01-13,2011-02-09),(2011-02-10,2011-03-09)])t (DaysOfWeek [2]) 2011 01 01 2011 01 15Just ((2010-12-28,2011-01-03) :| [(2011-01-04,2011-01-10),(2011-01-11,2011-01-17)])t (MonthAndDay 11 29) 2012 10 01 2013 10 15Just ((2012-11-29,2013-11-28) :| [])

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.

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.

Given a problem price directive, and maybe a function to calculate the error region's column(s) (currently ignored): generate a megaparsec-style error message with highlighted excerpt. Returns the source file path, line number, column(s) if known, and the rendered excerpt, or as much of these as possible. Columns will be accurate for the rendered error message, not for the original journal entry.

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.

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.

All raw amounts appearing in this journal, with MixedAmounts flattened, in no particular order. (Including from posting amounts, cost amounts, P directives, and the last D directive.)

The account name to use for conversion postings generated by --infer-equity. This is the first account declared with type V/Conversion, or otherwise the defaultBaseConversionAccount (equity:conversion).

Sorted unique commodity symbols mentioned anywhere in this journal. (Including commodity directives, P directives, the last D directive, posting amounts and cost amounts.)

Sorted unique commodity symbols used anywhere in this journal, including commodity directives, P directives, the last D directive, posting amounts and cost amounts.

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.

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.

All the accounts in this journal which are declared or inferred as V/Conversion type. This does not include new account names which might be generated by --infer-equity, currently.

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.

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.

valuejournalEndDate :: 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.

Collect and save inferred amount styles for each commodity based on P directive amounts, posting amounts but not cost amounts, and maybe the last D amount, in that commodity. Can return an error message eg if inconsistent number formats are found.

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.

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.

valuejournalPivot :: 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.

To all postings in the journal, add any tags from their account (including those inherited from parent accounts). If a tag already exists on the posting, it is not changed (the account tag will be ignored).

To all postings in the journal, add any tags from their amount's commodities. If a tag already exists on the posting, it is not changed (the commodity tag will be ignored).

Remove all tags from the journal's postings except those provided by their account. This is useful for the accounts report. It does not remove tag declarations from the posting comments.

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.

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.

Identify and tag (1) equity conversion postings and (2) postings which have (or could have ?) redundant costs. And if the addcosts flag is true, also add any costs which can be inferred from equity conversion postings. This is always called before transaction balancing to tag the redundant-cost postings so they can be ignored. With --infer-costs, it is called again after transaction balancing (when it has more information to work with) to infer costs from equity postings. See transactionTagCostsAndEquityAndMaybeInferCosts for more details, and hledger manual > Cost reporting for more background.

valuejournalTransactionsSimilarTo
  1. :: Journal
  2. -> Text
  3. -> Query
  4. -> SimilarityScore
  5. -> Int
  6. -> [(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.

Check all balance assertions in the journal and return an error message if any of them fail. (Technically, this also tries to balance the journal and can return balancing failure errors; ensure the journal is already balanced (with journalBalanceTransactions) to avoid this.)

Check that all the commodities used in this journal's postings and P directives have been declared by commodity directives, returning an error message otherwise.

Check that all the journal's tags (on accounts, transactions, postings..) have been declared with tag directives, returning an error message otherwise.

valuereadJsonFile :: 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

valuetoJsonText :: ToJSON a => a -> Text
#

Show a JSON-convertible haskell value as pretty-printed JSON text.

valuewriteJsonFile :: ToJSON a => FilePath -> a -> IO ()
#

Write a JSON-convertible haskell value to a pretty-printed JSON file. Eg: writeJsonFile "a.json" nulltransaction

The (fully specified) date span containing all the ledger's (filtered) transactions, or DateSpan Nothing Nothing if there are none.

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.

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.

Convert DateSpans to Periods.

Example1 expression
dateSpanAsPeriod $ DateSpan (Just $ Exact $ fromGregorian 2000 1 1) (Just $ Exact $ fromGregorian 2000 2 1)MonthPeriod 2000 1
valueisStandardPeriod :: 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.

Convert Periods to exact DateSpans.

Example1 expression
periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ Flex $ fromGregorian 2000 1 1) (Just $ Flex $ fromGregorian 2000 2 1)True
valueperiodGrow :: 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.

valueperiodMoveTo :: Day -> Period -> Period
#

Move a standard period stepwise so that it encloses the given date. Non-standard periods are unaffected.

valueperiodNext :: Period -> Period
#

Move a standard period to the following period of same duration. Non-standard periods are unaffected.

valueperiodNextIn :: DateSpan -> Period -> Period
#

Move a standard period to the following period of same duration, staying within enclosing dates. Non-standard periods are unaffected.

valueperiodPrevious :: Period -> Period
#

Move a standard period to the preceding period of same duration. Non-standard periods are unaffected.

Move a standard period to the preceding period of same duration, staying within enclosing dates. Non-standard periods are unaffected.

valueperiodShrink :: 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.

valueshowPeriod :: Period -> Text
#

Render a period as a compact display string suitable for user output.

Example2 expressions
showPeriod (WeekPeriod (fromGregorian 2016 7 25))"2016-W30"showPeriod (WeekPeriod (fromGregorian 2024 12 30))"2025-W01"
valueshowPeriodAbbrev :: Period -> Text
#

Like showPeriod, but if it's a month or week period show an abbreviated form. >>> showPeriodAbbrev (WeekPeriod (fromGregorian 2016 7 25)) W30 >>> showPeriodAbbrev (WeekPeriod (fromGregorian 2024 12 30)) W01

valuesimplifyPeriod :: Period -> Period
#

Convert PeriodBetweens to a more abstract period where possible.

Example8 expressions
simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1)YearPeriod 1simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1)QuarterPeriod 2000 4simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1)MonthPeriod 2000 2simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1)WeekPeriod 2016-07-25simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2)DayPeriod 2000-01-01simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1)PeriodBetween 2000-02-28 2000-03-01simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1)DayPeriod 2000-02-29simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1)DayPeriod 2000-12-31
valuelookupPeriodData :: Day -> PeriodData a -> Maybe (Day, a)
#

Get the data for the period containing the given Day, and that period's start date. If the day is after the end of the last period, it is assumed to be within the last period. If the day is before the start of the first period (ie, in the historical period), return Nothing.

Get the data for the period containing the given Day, and that period's start date. If the day is after the end of the last period, it is assumed to be within the last period. If the day is before the start of the first period (ie, in the historical period), return the data for the historical period and no start date.

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.

Example2 expressions
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.002017-02-01    ; generated-transaction: ~ monthly from 2017/1 to 2017/4    a           $1.002017-03-01    ; generated-transaction: ~ monthly from 2017/1 to 2017/4    a           $1.00
Example1 expression
_ptgen "monthly from 2017/1 to 2017/5"2017-01-01    ; generated-transaction: ~ monthly from 2017/1 to 2017/5    a           $1.002017-02-01    ; generated-transaction: ~ monthly from 2017/1 to 2017/5    a           $1.002017-03-01    ; generated-transaction: ~ monthly from 2017/1 to 2017/5    a           $1.002017-04-01    ; generated-transaction: ~ monthly from 2017/1 to 2017/5    a           $1.00
Example1 expression
_ptgen "every 2nd day of month from 2017/02 to 2017/04"2017-02-02    ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04    a           $1.002017-03-02    ; generated-transaction: ~ every 2nd day of month from 2017/02 to 2017/04    a           $1.00
Example1 expression
_ptgen "every 30th day of month from 2017/1 to 2017/5"2017-01-30    ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5    a           $1.002017-02-28    ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5    a           $1.002017-03-30    ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5    a           $1.002017-04-30    ; generated-transaction: ~ every 30th day of month from 2017/1 to 2017/5    a           $1.00
Example1 expression
_ptgen "every 2nd Thursday of month from 2017/1 to 2017/4"2017-01-12    ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4    a           $1.002017-02-09    ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4    a           $1.002017-03-09    ; generated-transaction: ~ every 2nd Thursday of month from 2017/1 to 2017/4    a           $1.00
Example1 expression
_ptgen "every nov 29th from 2017 to 2019"2017-11-29    ; generated-transaction: ~ every nov 29th from 2017 to 2019    a           $1.002018-11-29    ; generated-transaction: ~ every nov 29th from 2017 to 2019    a           $1.00
Example1 expression
_ptgen "2017/1"2017-01-01    ; generated-transaction: ~ 2017/1    a           $1.00
Example1 expression
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))[]
Example1 expression
_ptgenspan "every 3 months from 2019-05" (DateSpan (Just $ Flex $ fromGregorian 2020 01 01) (Just $ Flex $ fromGregorian 2020 02 01))
Example3 expressions
_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.002018-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
valuecommentAddTag :: 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.

valuecommentAddTagNextLine :: 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.

valuecommentJoin :: 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.

Special tags hledger sometimes adds to mark various things. These should be hidden tag names, beginning with _. With --verbose-tags, the equivalent visible tags will also be added. These tag names are mentioned in docs and can be matched by user queries, so consider the impact before changing them.

Special tags hledger sometimes adds to mark various things. These should be hidden tag names, beginning with _. With --verbose-tags, the equivalent visible tags will also be added. These tag names are mentioned in docs and can be matched by user queries, so consider the impact before changing them.

Special tags hledger sometimes adds to mark various things. These should be hidden tag names, beginning with _. With --verbose-tags, the equivalent visible tags will also be added. These tag names are mentioned in docs and can be matched by user queries, so consider the impact before changing them.

Special tags hledger sometimes adds to mark various things. These should be hidden tag names, beginning with _. With --verbose-tags, the equivalent visible tags will also be added. These tag names are mentioned in docs and can be matched by user queries, so consider the impact before changing them.

Special tags hledger sometimes adds to mark various things. These should be hidden tag names, beginning with _. With --verbose-tags, the equivalent visible tags will also be added. These tag names are mentioned in docs and can be matched by user queries, so consider the impact before changing them.

valuepostingAddTags :: Posting -> [Tag] -> Posting
#

Add tags to a posting, discarding any for which the posting already has a value. Note this does not add tags to the posting's comment.

valuepostingAsLines
  1. :: Bool
  2. -> Bool
  3. -> Int
  4. -> Int
  5. -> Posting
  6. -> ([Text], Int, Int)
#

Render one posting, on one or more lines, suitable for print output. Also returns the widths calculated for the account and amount fields.

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.

valuepostingDate :: 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.

valuepostingDate2 :: 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.

valuepostingIndent :: Text -> Text
#

Prepend a suitable indent for a posting (or transaction/posting comment) line.

valuepostingStatus :: 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".

valuepostingsAsLines :: Bool -> [Posting] -> [Text]
#

Render a transaction's postings as indented lines, suitable for print output.

Normally these will be in valid journal syntax which hledger can reparse (though they may include no-longer-valid balance assertions). Explicit amounts are shown, 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.

Posting amounts will be aligned with each other, starting about 4 columns beyond the widest account name (see postingAsLines for details). The postings will appear balanced (amounts summing to zero). Amounts' display precisions, which may have been limited by commodity directives, will be increased if necessary to ensure this.

valuerenderCommentLines :: 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.

valueshowPostingLines :: Posting -> [Text]
#

Render a posting, at the appropriate width for aligning with its siblings if any. Used by the rewrite command.

valuechoiceopt
  1. :: (String -> Maybe a)

    "parser" that returns Just value for valid choice

  2. -> RawOpts

    actual options where to look for flag

  3. -> Maybe a

    exclusive choice among those returned as Just from "parser"

#

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...

Example4 expressions
import Safe (readMay)choiceopt Just (RawOpts [("a",""), ("b",""), ("c","")])Just "c"choiceopt (const Nothing) (RawOpts [("a","")])Nothingchoiceopt readMay (RawOpts [("LT",""),("EQ",""),("Neither","")]) :: Maybe OrderingJust EQ
valuecollectopts :: ((String, String) -> Maybe a) -> RawOpts -> [a]
#

Collects processed and filtered list of options preserving their order

Example2 expressions
collectopts (const Nothing) (RawOpts [("x","")])[]collectopts Just (RawOpts [("a",""),("b","")])[("a",""),("b","")]
valueintopt :: 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.

valuemaybeintopt :: 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.

Reads the named option's natural-number argument, if it is present. An argument that is negative or too large will raise an error.

valueposintopt :: 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.

valuetoggleopt :: 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.

Convert timeclock entries to journal transactions. This is the new, default version added in hledger 1.43 and improved in 1.50. It allows concurrent clocked-in sessions (though not with the same account name), and clock-in/clock-out entries in any order.

Entries are processed in parse order. Sessions crossing midnight are split into days to give accurate per-day totals. At the end, any sessions with no clockout get an implicit clockout with the provided "now" time. If any entries cannot be paired as expected, an error is raised.

Convert timeclock entries to journal transactions. This is the old version from hledger <1.43, now enabled by --old-timeclock. It requires strictly alternating clock-in and clock-entries. It was documented as allowing only one clocked-in session at a time, but in fact it allows concurrent sessions, even with the same account name.

Entries must be a strict alternation of in and out, beginning with in. When there is no clockout, one is added with the provided current time. Sessions crossing midnight are split into days to give accurate per-day totals. If entries are not in the expected in/out order, an error is raised.

Parse a transaction's description into payee and note (aka narration) fields, assuming a convention of separating these with | (like Beancount). Ie, everything up to the first | is the payee, everything after it is the note. When there's no |, payee == note == description.

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).

Find, associate, and tag the corresponding equity conversion postings and costful or potentially costful postings in this transaction. With a true addcosts argument, also generate and add any equivalent costs that are missing. The (previously detected) names of all equity conversion accounts should be provided.

For every pair of adjacent conversion postings, this first searches for a posting with equivalent cost (1). If no such posting is found, it then searches the costless postings, for one matching one of the conversion amounts (2). If either of these found a candidate posting, it is tagged with costPostingTagName. Then if in addcosts mode, if a costless posting was found, a cost equivalent to the conversion amounts is added to it.

The name reflects the complexity of this and its helpers; clarification is ongoing.

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.

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.

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.

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.

valuefilterQuery :: (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.

valuefilterQueryOrNotQuery :: (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.

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).

valuematchesDescription :: Query -> Text -> Bool
#

Does the query match this transaction description ? Non-desc: query terms are ignored (this might disrupt some boolean queries).

valuematchesPayeeWIP :: 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.

valuematchesPosting :: 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.

valuematchesTag :: Query -> Tag -> Bool
#

Does the query match the name and optionally the value of this tag ? Non-tag: query terms are ignored (this might disrupt some boolean queries).

valueparseQuery :: 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:

  1. 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.

  1. 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.

Example1 expression
parseQuery nulldate "expenses:dining out"Right (Or [Acct (RegexpCI "expenses:dining"),Acct (RegexpCI "out")],[])
Example1 expression
parseQuery nulldate "\"expenses:dining out\""Right (Acct (RegexpCI "expenses:dining out"),[])
valueparseQueryList :: 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

valuequeryDateSpan :: 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.

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.

valuequeryEndDate :: 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.

valuequeryIsDate :: Query -> Bool
#

Is this a simple query of this type (date:) ? Does not match a compound query involving andornot. Likewise for the following functions.

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.

valuequeryStartDate :: 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.

valuewords'' :: [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.

Read the default journal file specified by the environment, with default input options, or raise an error.

Get the default journal file path - either $LEDGER_FILE or $HOME/.hledger.journal file.

This looks for the LEDGER_FILE environment variable, like Ledger. The value should be a file path, possibly with ~ at the start meaning the current user's home directory. Or the value can be a glob pattern (containing *, ?, [ or {) ), in which case the first matching file path is used. When it's a glob pattern that matches no existing files, an error is raised.

If LEDGER_FILE is unset or set to the empty string, this returns a default file path: .hledger.journal in the user's home directory, or if we can't find the user's home directory, in the current directory.

The referenced file can be nonexistent.

Does any part of this path contain non-. characters and end with a . ? Such paths are not safe to use on Windows (cf #1056).

readJournal iopts mfile txt

Read a Journal from some handle, 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 mfile path

  • a file extension in mfile

If none of these is available, or if the reader name is unrecognised, the journal reader is used.

If a file path is not provided, "-" is assumed (and may appear in error messages, files output etc, where it will be a slight lie: it will mean "not from a file", not necessarily "from standard input".

Read a Journal from this file, or from stdin if the file path is -, with strict checks if enabled, or return an error message. XXX or, calls error if the file does not exist.

(Note strict checks are disabled temporarily here when this is called by readJournalFiles). 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 not deferred by readJournalFiles, 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 processed.

Read a Journal from each specified file path (using readJournalFile) and combine them into one; or return the first error message.

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.

Strict checks, if enabled, are temporarily deferred until all files are read, to ensure they see the whole journal, and/or to avoid redundant work. (Some checks, like assertions and ordereddates, might still be doing redundant work ?)

Writing .latest files, if enabled, is also deferred till the end, and is done only if strict checks pass.

Like readJournalFiles, but if the first file does not exist, provides an empty journal with that file path set. Other files must exist as normal. This is useful for commands like add and import that write to the first file, which might not exist yet, while also reading other files for completions etc.

If the specified journal file does not exist (and is not "-"), call error with an informative message. (Using "journal file" generically here; it could be in any of hledger's supported formats.)

valuesaveLatestDates :: 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. Unless no latest dates are provided, in which case do nothing.

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. (We should have required them to start with an alphanumeric, but didn't.) Note, this means account names can contain all kinds of punctuation, including ; which usually starts a following comment. Parent parsers usually remove the following comment before using this parser.

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:

  1. If a decimal mark has been set explicitly in the journal parse state, we use that

  2. Or if the journal has a commodity declaration for the amount's commodity, we get the decimal mark from that

  3. 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.)

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.

Example1 expression
either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"Right [("date",2016-01-02),("date2",2016-03-04)]
Example1 expression
either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"Left ...not a bracketed date...
Example1 expression
either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"Left ...1:2:...This is not a valid date...
Example1 expression
either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]"Left ...1:2:...This partial date can not be parsed because the current year is unknown...
Example1 expression
either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"Left ...1:13:...expecting month or day...
valuedatep :: 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.

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).

Parse possibly empty text until a semicolon or newline. Whitespace is preserved (for now - perhaps helps preserve alignment of same-line comments ?).

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. See also emptyorcommentlinep2.

valueemptyorcommentlinep2 :: [Char] -> TextParser m ()
#

A newer comment line parser. Parses a line which is empty, all blanks, or whose first non-blank character is one of those provided. A final newline is optional.

Parse a comment following a journal item, possibly continued on multiple lines, and return the comment text.

Example5 expressions
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"

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.

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

  • propagate account tags to postings

  • maybe add forecast transactions

  • propagate account tags to postings (again to affect forecast transactions)

  • maybe add auto postings

  • propagate account tags to postings (again to affect auto postings)

  • evaluate balance assignments and balance each transaction

  • maybe check balance assertions

  • maybe infer costs from equity postings

  • maybe infer equity postings from costs

  • manye infer market prices from costs

One correctness check (parseable) has already passed when this function is called. Up to four more are performed here:

  • ordereddates (when enabled)

  • assertions (when enabled)

  • autobalanced (and with --strict, balanced ?), in the journalBalanceTransactions step.

Others (commodities, accounts..) are done later by journalStrictChecks.

Parse an account name plus one following space if present (see accountnamep); 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. The flag says whether account names may include semicolons; currently account names in journal format may, but account names in timeclock/timedot formats may not.

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.

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.

Example2 expressions
let getTags (_,tags,_,_) = tagslet parseTags = fmap getTags . rtp (postingcommentp Nothing)
Example1 expression
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.

Example2 expressions
let getDates (_,_,d1,d2) = (d1, d2)let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))
Example2 expressions
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)

valuerawnumberp :: 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.

Example3 expressions
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)
valuesinglespacep :: TextParser m ()
#

Parse one non-newline whitespace character that is not followed by another one.

Parse a transaction comment and extract its tags.

The first line of a transaction may be followed a 1-or-more-lines comment, beginning with a semicolon possibly preceded by whitespace on the current line, or with an indented semicolon on the next line. Additional lines also must begin with an indented semicolon. See also followingcommentpWith.

200011 ; a transaction comment starting on the same line ... ; extending to the next line account1 $1 account2

Tags are name-value pairs.

Example2 expressions
let getTags (_,tags) = tagslet parseTags = fmap getTags . rtp transactioncommentp
Example1 expression
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.

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.

findReader mformat mpath

Find the reader named by mformat, if provided. ("ssv" and "tsv" are recognised as alternate names for the csv reader, which also handles those formats.) Or, if a file path is provided, find the first reader that handles its file extension, if any.

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.

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.

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).

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.

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).

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.

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.

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.

Generate a ReportOpts from raw command-line input, given a day and whether to use ANSI colour/styles in standard output. 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,

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).

The effective report span is the start and end dates requested by options or queries. If the start date is unspecified, the earliest transaction or posting date is used. If the end date is unspecified, the latest transaction or posting date (or non-future market price date, when doing an end value report) is used. If none of these things are present, the null date span is returned. The report sub-periods caused by a report interval, if any, are also returned.

If the ReportOpts specify that we will need to consider historical postings, either because this is a historical report, or because the valuation strategy requires historical amounts.

valuesimplifyStatuses :: 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.

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.

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.

valueall1 :: (a -> Bool) -> [a] -> Bool
#

Version of all that fails on an empty list.

valueapplyN :: 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 ?

valuecurry2 :: ((a, b) -> c) -> a -> b -> c
#
valuecurry3 :: ((a, b, c) -> d) -> a -> b -> c -> d
#
valuecurry4 :: ((a, b, c, d) -> e) -> a -> b -> c -> d -> e
#
valuefifth5 :: (a, b, c, d, e) -> e
#
valuefifth6 :: (a, b, c, d, e, f) -> e
#
valuefirst3 :: (a, b, c) -> a
#
valuefirst4 :: (a, b, c, d) -> a
#
valuefirst5 :: (a, b, c, d, e) -> a
#
valuefirst6 :: (a, b, c, d, e, f) -> a
#
valuefourth5 :: (a, b, c, d, e) -> d
#
valuefourth6 :: (a, b, c, d, e, f) -> d
#

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

valuemapM' :: Monad f => (a -> f b) -> [a] -> f [b]
#

Like mapM but uses sequence'.

valuemaximum' :: Integral a => [a] -> a
#

Total version of maximum, for integral types, giving 0 for an empty list.

valuemaximumStrict :: Ord a => [a] -> a
#

Strict version of maximum that doesn’t leak space

valueminimumStrict :: Ord a => [a] -> a
#

Strict version of minimum that doesn’t leak space

valuemulticol :: Int -> [String] -> String
#

Convert a list of strings to a multi-line multi-column list fitting within the given width. Not wide character aware.

valuenumDigitsInteger :: 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.

valuesecond5 :: (a, b, c, d, e) -> b
#
valuesecond6 :: (a, b, c, d, e, f) -> b
#
valuesequence' :: 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.

valuesixth6 :: (a, b, c, d, e, f) -> f
#
valuesumStrict :: Num a => [a] -> a
#

Strict version of sum that doesn’t leak space

valuetakeUntilFails :: (a -> Bool) -> [a] -> [a]
#

Take elements from a list until a predicate fails, and then keep the first failing element as well.

valuethird3 :: (a, b, c) -> c
#
valuethird4 :: (a, b, c, d) -> c
#
valuethird5 :: (a, b, c, d, e) -> c
#
valuethird6 :: (a, b, c, d, e, f) -> c
#
valuetreeLeaves :: 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.

valueuncurry2 :: (a -> b -> c) -> (a, b) -> c
#
valueuncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
#
valueuncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
#
valuedbg :: Show a => Int -> String -> a -> a
#

Trace or log a label and showable value, pretty-printed, if the program debug level is at or above the specified level; then return the value.

valuedbgMsg :: Int -> String -> a -> a
#

Trace or log a string if the program debug level is at or above the specified level, then return the second argument.

valuedbgWith :: Int -> (a -> String) -> a -> a
#

Like dbg, but with a custom show function.

valuedbg_ :: Show a => Int -> String -> a -> a
#

Alias for dbg, can be used to avoid namespace clashes.

valuedebugLevel :: Int
#

The program's debug output verbosity, from 0 to 9. The default is 0 meaning no debug output. This can be overridden by running the program with a --debug [1-9] command line option; a --debug flag with no value means 1. Uses unsafePerformIO to read the command line. When running in GHCI, changing this requires reloading this module.

Should the program open a socket allowing control by ghc-debug-brick or similar ghc-debug client ? See GhcDebugMode.

valueghcDebugPause' :: IO ()
#

When ghc-debug support has been built into the program, this calls ghc-debug's pause, otherwise it's a no-op.

valuelbl_ :: 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.

Eg: let lbl = lbl_ "print", dbg1With (lbl "part 1".show) ....

valueprogName :: String
#

The progam name, with any ".log" suffix removed.

valuewithGhcDebug' :: a -> a
#

When ghc-debug support has been built into the program and enabled at runtime with --debug=-N, this calls ghc-debug's withGhcDebug; otherwise it's a no-op.

valuebold' :: String -> String
#

Set various ANSI styles/colours in a string, only if useColorOnStdoutUnsafe says we should.

valuecolor :: 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".

valuecolorOption :: IO YNA
#

Get the value of the rightmost --color or --colour option from the program's command line arguments. Throws an error if the option's value could not be parsed.

valueerror' :: String -> a
#

Call errorWithoutStackTrace, prepending a "Error:" label.

valueexpandGlob :: 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. Can raise an error. For a more elaborate glob expander, see findMatchedFiles (used by the include directive).

Expand a single tilde (representing home directory) at the start of a file path. ~username is not supported. This can raise an IO error.

Given a current directory, convert a possibly relative, possibly tilde-prefixed file path to an absolute one. ~username is not supported. If the file path is "-", it is left as-is. This can an raise an IO error.

Like expandPath, but if the path contains glob metacharacters (* ? [ {), treats it as a glob pattern and expands it, returning the first match. Raises an error if the glob pattern matches no files. If the path contains no glob metacharacters, just expands ~ and returns the path, even if the file doesn't exist yet. This is useful for options like -f and LEDGER_FILE that should: - accept non-existent files (for commands like add/import that create them) - expand glob patterns and error if they don't match anything

valuefindPager :: IO (Maybe String)
#

Try to find a pager executable robustly, safely handling various error conditions like an unset PATH var or the specified pager not being found as an executable. The pager can be specified by a path or program name in the PAGER environment variable. If that is unset or has a problem, "less" is tried, then "more". If successful, the pager's path or program name is returned.

valuegetFlag :: [String] -> IO Bool
#

Given one or more long or short flag names, report whether this flag is present in the command line. Concatenated short flags (-a -b written as -ab) are not supported.

valuegetHomeSafe :: IO (Maybe FilePath)
#

Like getHomeDirectory, but in case of IO error (home directory not found, not understood, etc.), returns "".

valuegetOpt :: [String] -> IO (Maybe String)
#

Given one or more long or short option names, read the rightmost value of this option from the command line arguments. If the value is missing raise an error. Concatenated short flags (-a -b written as -ab) are not supported.

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.

Read text from a handle, perhaps using a specified encoding from the encoding package. Or if no encoding is specified, using the handle's current encoding, changing it to UTF-8BOM if it was UTF-8, to ignore any Byte Order Mark at the start. Also it converts Windows line endings to newlines. If decoding fails, this throws an IOException (or possibly a UnicodeException or something else from the encoding package).

valuehandleExit :: IO () -> IO ()
#

This wraps a program's main routine so as to display more consistent, useful, and GHC-version-independent error output when the program exits because of certain common exceptions. It

  1. disables SIGPIPE errors, which are usually harmless, caused when our output is truncated in a piped command.

  2. catches these common exceptions:

  • UnicodeException, caused eg by text decoding errors in pure code

  • IOException, caused by IO errors, including text decoding errors during IO

  • ErrorCall - error / errorWithoutStackTrace calls

  1. compensates for GHC output bugs:

  • removes the trailing newlines added by some GHC 9.10.* versions

  • removes "uncaught exception" output added by some GHC 9.12.* versions

  • ensures a consistent "PROGNAME: " prefix

  1. applies bold bright red ANSI styling to the first line of error output, if that is supported and allowed

  2. for unicode exceptions and I/O exceptions which look like they were unicode-related, it adds a message (in english) explaining the problem and what to do.

Some exceptions this does not catch are ExitCode (exitSuccessexitFailureexitWith) and UserInterrupt (control-C).

valuelessIsWorking :: Maybe [(String, String)] -> IO Bool
#

Test less, by running less --version and looking for a nonzero exit, timeout, or stderr output. Uses the provided environment, containing a LESS variable, if any. We do this because various LESS settings can cause some less versions to fail or cause confusing output without failing.

Compute the LESS environment variable value that hledger will use for the less pager. This used in runPager when invoking less, and also in the setup command for display. It takes the current HLEDGER_LESS and LESS env var values, and whether we are showing colour on stdout, and returns the adjusted LESS value that should be used. Specifically:

  • If HLEDGER_LESS is defined, we use it in place of the LESS environment variable.

  • Otherwise, if LESS is defined, append some preferred options (lessOptions and maybe lessColourOptions) to it.

  • Otherwise, we set LESS to just use those preferred options.

Open a file for reading, using the standard System.IO.openFile. This opens the handle in text mode, using the initial system locale's text encoding.

valuepprint :: Show a => a -> IO ()
#

Pretty print a showable value. An easier alias for pretty-simple's pPrint. This will print in colour if useColorOnStderrUnsafe is true.

valuepprint' :: Show a => a -> IO ()
#

Monochrome version of pprint. This will never print in colour.

valueprintError :: String -> IO ()
#

Print an error message to stderr, with a consistent "programname: " prefix, and applying ANSI styling (bold bright red) to the first line if that is supported and allowed.

valueprogArgs :: [String]
#

The program's command line arguments. Uses unsafePerformIO; tends to stick in GHCI until reloaded, and may or may not detect args provided by a hledger config file.

valuepshow :: Show a => a -> String
#

Pretty show. An easier alias for pretty-simple's pShow. This will probably show in colour if useColorOnStderrUnsafe is true.

valuepshow' :: Show a => a -> String
#

Monochrome version of pshow. This will never show in colour.

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.

valuerunPager :: String -> IO ()
#

Display the given text on the terminal, trying to use a pager ($PAGER, less, or more) when appropriate (see maybePagerFor), otherwise printing to standard output. Also, if the pager is less, we modify the LESS environment variable (see lessVarValue) and check for problems which could cause confusing output (see lessIsWorking).

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.

Detect the terminal's current background lightness (0..1), if possible, using unsafePerformIO. If the terminal is transparent, its apparent lightness may be different.

valuetextToHandle :: Text -> IO Handle
#

Create a handle from which the given text can be read. Its encoding will be UTF-8.

Should ANSI color and styles be used for standard error output ? Considers useColorOnHandle stderr; is not affected by an --output-file option.

Should ANSI color and styles be used for standard output ? Considers useColorOnHandle stdout and hasOutputFile.

Like useColorOnStdout, but using unsafePerformIO. Useful eg for low-level debug code. Sticky in GHCI until reloaded, may not always be affected by --color in a hledger config file, etc.

valuewarn :: String -> a -> a
#

Show a warning message on stderr before returning the given value. Like trace, but prepends a "Warning:" label, and does some ANSI styling of the first line when allowed (using unsafe IO). Currently we use this very sparingly in hledger; we prefer to either quietly work, or loudly raise an error. Varying output can make scripting harder. But on stderr, it shouldn't cause much hassle.

valuewarnIO :: MonadIO m => String -> m ()
#

Like warn, but take extra care to sequence properly in IO.

valuechoice' :: [TextParser m a] -> TextParser m a
#

Backtracking choice, use this when alternatives share a prefix. Consumes no input if all choices fail.

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.

valuedbgparse :: 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. See also: Hledger.Utils.Debug, megaparsec's dbg. Uses unsafePerformIO. XXX Can be hard to make this evaluate.

valueparseErrorAtRegion
  1. :: Int

    Start offset

  2. -> Int

    End end offset

  3. -> String

    Error message

  4. -> HledgerParseErrorData
#

Fail at a specific source interval, given by the raw offsets of its endpoints from the start of the input stream (the numbers of tokens processed at those points).

Note that care must be taken to ensure that the specified interval does not span multiple lines of the input source. This will not be checked.

'reparseExcerpt s p' "re-parses" the source excerpt s using the parser p. Parse errors raised by p will be re-thrown at the source position of the source excerpt.

In order for the correct source file to be displayed when re-throwing parse errors, we must ensure that the source file during the use of 'reparseExcerpt s p' is the same as that during the use of excerpt_ that generated the source excerpt s. However, we can usually expect this condition to be satisfied because, at the time of writing, the only changes of source file in the codebase take place through include files, and the parser for include files neither accepts nor returns SourceExcerpts.

valueregexMatchText :: Regexp -> Text -> Bool
#

Tests whether a Regexp matches a Text.

This currently unpacks the Text to a String, to work around a performance bug in regex-tdfa (#9), which may or may not be relevant here.

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.

valuechomp1 :: String -> String
#

Remove all trailing newline/carriage returns, leaving just one trailing newline.

valueformatString :: 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).

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.

Example3 expressions
quoteForCommandLine "a""a"quoteForCommandLine "\"""'\"'"quoteForCommandLine "$""'$'"
valuequoteIfNeeded :: String -> String
#

Double-quote this string if it contains whitespace, single quotes or double-quotes, escaping the quotes as needed.

Single-quote this string if it contains whitespace or double-quotes. Does not work for strings containing single quotes.

valuestrWidthAnsi :: 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.

valuestrip1By :: (Char -> Bool) -> String -> String
#

Strip a single balanced enclosing pair of a character matching the predicate from the start and end of a string.

valuestrip1Char :: Char -> Char -> String -> String
#

Strip the given starting and ending character from the start and end of a string if both are present.

valuestripAnsi :: String -> String
#

Strip ANSI escape sequences from a string.

Example1 expression
stripAnsi "\ESC[31m-1\ESC[m""-1"
valuestripBy :: (Char -> Bool) -> String -> String
#

Strip a run of zero or more characters matching the predicate from the start and end of a string.

valuetakeEnd :: Int -> [a] -> [a]
#

Take elements from the end of a list.

valuetakeWidth :: 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 "りんご" = "り".

valuewords' :: 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.

valuefitText :: 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.

valueformatText :: 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).

valuequoteIfSpaced :: 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.

valuereadDecimal :: Text -> Integer
#

Read a decimal number from a Text. Assumes the input consists only of digit characters.

valuestripquotes :: Text -> Text
#

Strip one matching pair of single or double quotes on the ends of a string.

Join several multi-line strings as side-by-side rectangular strings of the same height, bottom-padded. Treats wide characters as double width.

valuetextConcatTopPadded :: [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.

valuetextTakeWidth :: 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 "りんご" = "り".

valuetextUnbracket :: Text -> Text
#

Remove all matching pairs of square brackets and parentheses from the text.

Creates a new process from the provided CreateProcess, and wait for it to finish. If the process returns a non-zero exit code, an exception is raised.

If an asynchronous exception is thrown to the thread executing callCreateProcess, the forked process will be terminated and callCreateProcess will wait (block) until the process has been terminated.

@since TODO

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 std_in == CreatePipe, then mb_stdin_hdl will be Just h, where h is the write end of the pipe connected to the child process's stdin.

  • 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.

valuegetCurrentPid :: 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.

valuegetPid :: 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.

valuerawSystem :: String -> [String] -> IO ExitCode
#

The computation rawSystem cmd args runs the operating system command cmd 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.

valuereadCreateProcess
  1. :: CreateProcess
  2. -> String

    standard input

  3. -> 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.

valuereadProcess
  1. :: FilePath

    Filename of the executable (see RawCommand for details)

  2. -> [String]

    any arguments

  3. -> String

    standard input

  4. -> 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. See RawCommand for further discussion of Windows semantics.

  • A string to pass on standard input to the forked process.

valuereadProcessWithExitCode
  1. :: FilePath

    Filename of the executable (see RawCommand for details)

  2. -> [String]

    any arguments

  3. -> String

    standard input

  4. -> IO (ExitCode, String, String)

    exitcode, stdout, stderr

#

readProcessWithExitCode is like readProcess but with two differences:

  • it returns the ExitCode of the process, and does not throw any exception if the code is not ExitSuccess.

  • 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.

valuerunInteractiveProcess
  1. :: FilePath

    Filename of the executable (see RawCommand for details)

  2. -> [String]

    Arguments to pass to the executable

  3. -> Maybe FilePath

    Optional path to the working directory

  4. -> Maybe [(String, String)]

    Optional environment (otherwise inherit)

  5. -> 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)
valuerunProcess
  1. :: FilePath

    Filename of the executable (see RawCommand for details)

  2. -> [String]

    Arguments to pass to the executable

  3. -> Maybe FilePath

    Optional path to the working directory

  4. -> Maybe [(String, String)]

    Optional environment (otherwise inherit)

  5. -> Maybe Handle

    Handle to use for stdin (Nothing => use existing stdin)

  6. -> Maybe Handle

    Handle to use for stdout (Nothing => use existing stdout)

  7. -> Maybe Handle

    Handle to use for stderr (Nothing => use existing stderr)

  8. -> 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.

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).

valuesystem :: 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.

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.

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 ExitFailure -signum indicates that the child was terminated by signal signum. 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.

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
  ...
valuecreatePipe :: 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 readEnd
    #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 responsibility to register the handle if it supports async access.

valuecreatePipeFd :: IO (FD, FD)
#

Create a pipe for interprocess communication and return a (readEnd, writeEnd) FD pair.

valuecreateProcess_
  1. :: String

    Function name (for error messages).

    This can be any String, but will typically be the name of the caller. E.g., spawnProcess passes "spawnProcess" here when calling createProcess_.

  2. -> CreateProcess
  3. -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
#

This function is almost identical to createProcess. The only differences are:

  • Handles provided via UseHandle are not closed automatically.

  • This function takes an extra String argument 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.

valueinterruptProcessGroupOf
  1. :: ProcessHandle

    A process in the process group

  2. -> 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

valueabort :: Partial => String -> a
#

Synonym for error. Used for instances where the program has decided to exit because of invalid user input, or the user pressed quit etc. This function allows error to be reserved for programmer errors.

valuefindJust :: (a -> Bool) -> [a] -> a
#
findJust op = fromJust . find op
valuefoldl1Def :: a -> (a -> a -> a) -> [a] -> a
#

Deprecated. Use foldl1May instead.

valuefoldl1Def' :: a -> (a -> a -> a) -> [a] -> a
#

Deprecated. Use foldl1May' instead.

valuefoldr1Def :: a -> (a -> a -> a) -> [a] -> a
#

Deprecated. Use foldr1May instead.

valuefromJustDef :: a -> Maybe a -> a
#

An alternative name for fromMaybe, to fit the naming scheme of this package. Generally using fromMaybe directly would be considered better style.

valueheadErr :: Partial => [a] -> a
#

Identical to head, namely that fails on an empty list. Useful to avoid the x-partial warning introduced in GHC 9.8.

headErr [] = error "Prelude.head: empty list"
headErr [1,2,3] = 1
valuelookupJust :: (Eq a, Partial) => a -> [(a, b)] -> b
#
lookupJust key = fromJust . lookup key
valuemaximumBound :: Ord a => a -> [a] -> a
#

The largest element of a list. The result is bounded by the value given as the first argument.

valuemaximumBoundBy :: 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.

valueminimumBound :: Ord a => a -> [a] -> a
#

The smallest element of a list. The result is bounded by the value given as the first argument.

valueminimumBoundBy :: 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.

valuescanl1Def :: [a] -> (a -> a -> a) -> [a] -> [a]
#
valuescanr1Def :: [a] -> (a -> a -> a) -> [a] -> [a]
#
valuetailDef :: [a] -> [a] -> [a]
#
tailDef [12] [] = [12]
tailDef [12] [1,3,4] = [3,4]
valuetailErr :: Partial => [a] -> [a]
#

Identical to tail, namely that fails on an empty list. Useful to avoid the x-partial warning introduced in GHC 9.8.

tailErr [] = error "Prelude.tail: empty list"
tailErr [1,2,3] = [2,3]
valuetailMay :: [a] -> Maybe [a]
#
tailMay [] = Nothing
tailMay [1,3,4] = Just [3,4]
valuetailNote :: Partial => String -> [a] -> [a]
#
tailNote "help me" [] = error "Safe.tailNote [], help me"
tailNote "help me" [1,3,4] = [3,4]
valuetailSafe :: [a] -> [a]
#
tailSafe [] = []
tailSafe [1,3,4] = [3,4]
valuewithResource
  1. :: IO a

    initialize the resource

  2. -> (a -> IO ())

    free the resource

  3. -> (IO a -> TestTree)

    IO a is an action which returns the acquired resource. Despite it being an IO action, the resource it returns will be acquired only once and shared across all the tests in the tree.

  4. -> TestTree
#

Acquire the resource to run this test (sub)tree and release it afterwards.

valueafter
  1. :: DependencyType

    whether to run the tests even if some of the dependencies fail

  2. -> String

    the pattern

  3. -> TestTree

    the subtree that depends on other tests

  4. -> 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.

after AllFinish "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 Test.Tasty.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.

after AllFinish "$0 == \"Tests.Foo.Bar\"" $
   

testCase "A test that depends on Foo.Bar" $ ...

Or only specify the dependency's own name, ignoring the group names:

after AllFinish "$NF == \"Bar\"" $
   

testCase "A test that depends on Foo.Bar" $ ...

valueafter_
  1. :: DependencyType

    whether to run the tests even if some of the dependencies fail

  2. -> Expr

    the pattern

  3. -> TestTree

    the subtree that depends on other tests

  4. -> 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 (Field NF) (StringLit "Bar")) $
   

testCase "A test that depends on Foo.Bar" $ ...

valuedependentTestGroup
  1. :: TestName

    name of the group

  2. -> DependencyType

    whether to run subsequent tests even if earlier ones have failed

  3. -> [TestTree]

    tests to execute sequentially

  4. -> TestTree
#

Create a named group of test cases or other groups. Tests are executed in order and each test is considered a dependency of the next one. If filtering by TestPattern (--pattern) is in action, any test matching the pattern also shields earlier tests from filtering out, even if they themselves do not match the pattern.

For parallel execution, see testGroup. For ordered test execution, but with default filtering behavior, see inOrderTestGroup.

Note that this is will only work when used with the default TestManager. If you use another manager, like tasty-rerun for instance, sequentiality might possibly be ignored.

valueinOrderTestGroup
  1. :: TestName

    name of the group

  2. -> [TestTree]

    tests to execute sequentially

  3. -> TestTree
#

Create a named group of test cases that will be played sequentially, in the exact order provided. Similarly to testGroup and in contrast to dependentTestGroup, filtering by TestPattern is applied uniformly.

Note that this is will only work when used with the default TestManager. If you use another manager, like tasty-rerun for instance, the fact that these tests should be run in the given order might possibly be ignored.

value(@=?)
  1. :: (Eq a, Show a, HasCallStack)
  2. => a

    The expected value

  3. -> a

    The actual value

  4. -> Assertion
#

Asserts that the specified actual value is equal to the expected value (with the expected value on the left-hand side).

value(@?)
  1. :: (AssertionPredicable t, HasCallStack)
  2. => t

    A value of which the asserted condition is predicated

  3. -> String

    A message that is displayed if the assertion fails

  4. -> 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 IO Bool predicates, so instead of

do
  e <- doesFileExist "test"
  e @? "File does not exist"

you can write

doesFileExist "test" @? "File does not exist"
value(@?=)
  1. :: (Eq a, Show a, HasCallStack)
  2. => a

    The actual value

  3. -> a

    The expected value

  4. -> Assertion
#

Asserts that the specified actual value is equal to the expected value (with the actual value on the left-hand side).

valueassertEqual
  1. :: (Eq a, Show a, HasCallStack)
  2. => String

    The message prefix

  3. -> a

    The expected value

  4. -> a

    The actual value

  5. -> 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.

valueassertFailure
  1. :: HasCallStack
  2. => String

    A message that is displayed with the assertion failure

  3. -> 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
valueassertString
  1. :: HasCallStack
  2. => String

    The message that is displayed with the assertion failure

  3. -> Assertion
#

Deprecated. Why not use assertBool instead?

Signals an assertion failure if a non-empty message (i.e., a message other than "") is passed.

valuetestCaseSteps :: 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.

valuepack :: String -> Text
#

O(n) Convert a String into a Text. Performs replacement on invalid scalar values, so unpack . pack is not id:

Example1 expression
Data.Text.unpack (pack "\55555")"\65533"
valueperiodFromDay :: DayPeriod p => Day -> (p, Int)
#

Get the period this day is in, with the 1-based day number within the period.

periodFromDay (periodFirstDay p) = (p,1)
patternpattern 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.

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.

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.

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.

Calendrical difference, with as many whole months as possible. Has the property addGregorianDurationClip (diffGregorianDurationClip d2 d1) d1 = d2. For example, 2027-03-01 - 2027-01-31 = 1 month and 1 day.

Calendrical difference, with as many whole months as possible. Has the property addGregorianDurationRollOver (diffGregorianDurationRollOver d2 d1) d1 = d2. For example, 2027-03-01 - 2027-01-31 = 29 days.

valueisLeapYear :: Year -> Bool
#

Is this year a leap year according to the proleptic Gregorian calendar?

valueweekAllDays :: DayOfWeek -> Day -> [Day]
#

Returns a week containing the given Day where the first day is the DayOfWeek specified.

Examples:

Example1 expression
weekAllDays Sunday (YearMonthDay 2022 02 21)[YearMonthDay 2022 2 20 .. YearMonthDay 2022 2 26]
Example1 expression
weekAllDays Monday (YearMonthDay 2022 02 21)[YearMonthDay 2022 2 21 .. YearMonthDay 2022 2 27]
Example1 expression
weekAllDays Tuesday (YearMonthDay 2022 02 21)[YearMonthDay 2022 2 15 .. YearMonthDay 2022 2 21]
valueweekFirstDay :: DayOfWeek -> Day -> Day
#

Returns the first day of a week containing the given Day.

Examples:

Example1 expression
weekFirstDay Sunday (YearMonthDay 2022 02 21)YearMonthDay 2022 2 20
Example1 expression
weekFirstDay Monday (YearMonthDay 2022 02 21)YearMonthDay 2022 2 21
Example1 expression
weekFirstDay Tuesday (YearMonthDay 2022 02 21)YearMonthDay 2022 2 15
valueweekLastDay :: DayOfWeek -> Day -> Day
#

Returns the last day of a week containing the given Day.

Examples:

Example1 expression
weekLastDay Sunday (YearMonthDay 2022 02 21)YearMonthDay 2022 2 26
Example1 expression
weekLastDay Monday (YearMonthDay 2022 02 21)YearMonthDay 2022 2 27
Example1 expression
weekLastDay Tuesday (YearMonthDay 2022 02 21)YearMonthDay 2022 2 21
valueformatTime :: 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

dateTimeFmt

locale

(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

timeFmt

locale

(e.g.

%H:%M:%S

)

%r

as

time12Fmt

locale

(e.g.

%I:%M:%S %p

)

%P

day-half of day from (

amPm

locale

), converted to lowercase,

am

,

pm

%p

day-half of day from (

amPm

locale

),

AM

,

PM

%H

hour of day (24-hour), 0-padded to two chars,

00

-

23

%k

hour of day (24-hour), space-padded to two chars,

0

-

23

%I

hour of day-half (12-hour), 0-padded to two chars,

01

-

12

%l

hour of day-half (12-hour), space-padded to two chars,

1

-

12

%M

minute of hour, 0-padded to two chars,

00

-

59

%S

second of minute (without decimal part), 0-padded to two chars,

00

-

60

%q

picosecond of second, 0-padded to twelve chars,

000000000000

-

999999999999

.

%Q

decimal point and fraction of second, up to 12 second decimals, without trailing zeros. For a whole number of seconds,

%Q

omits 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.%q

and

%s%Q

the decimals are positive, not negative. For example, 0.9 seconds before the Unix epoch is formatted as

-1.1

with

%s%Q

.

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 (

snd

from

wDays

locale

),

Sun

-

Sat

%A

day of week, long form (

fst

from

wDays

locale

),

Sunday

-

Saturday

QuarterOfYear

For QuarterOfYear (and Quarter and Month and Day and LocalTime and ZonedTime and UTCTime and UniversalTime):

%v

quarter number,

1

-

4

Quarter

For Quarter (and Month and Day and LocalTime and ZonedTime and UTCTime and UniversalTime):

%Y

year, no padding. Note

%0Y

and

%_Y

pad to four chars

%y

year of century, 0-padded to two chars,

00

-

99

%C

century, no padding. Note

%0C

and

%_C

pad to two chars

%v

quarter number,

1

-

4

Month

For Month (and Day and LocalTime and ZonedTime and UTCTime and UniversalTime):

%B

month name, long form (

fst

from

months

locale

),

January

-

December

%b, %h

month name, short form (

snd

from

months

locale

),

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

dateFmt

locale

(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

%G

year for ISO 8601 Week Date format. Note

%0G

and

%_G

pad to four chars

%g

year of century for ISO 8601 Week Date format, 0-padded to two chars,

00

-

99

%f

century for ISO 8601 Week Date format, no padding. Note

%0f

and

%_f

pad to two chars

%V

week of year for ISO 8601 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,

%Es

omits 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,

%ES

omits 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,

%Es

omits 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,

%ES

omits the decimal point unless padding is specified.

%0ES

seconds of minute as two digits, with decimal point and <width> (default 12) decimal places.

Locale representing American usage.

knownTimeZones contains only the ten time-zones mentioned in RFC 822 sec. 5: "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT". Note that the parsing functions will regardless parse "UTC", single-letter military time-zones, and +HHMM format.

valueparseTimeM
  1. :: (MonadFail m, ParseTime t)
  2. => Bool

    Accept leading and trailing whitespace?

  3. -> TimeLocale

    Time locale.

  4. -> String

    Format string.

  5. -> String

    Input string.

  6. -> 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

±HHMM

or

±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
valueparseTimeMultipleM
  1. :: (MonadFail m, ParseTime t)
  2. => Bool

    Accept leading and trailing whitespace?

  3. -> TimeLocale

    Time locale.

  4. -> [(String, String)]

    Pairs of (format string, input string).

  5. -> 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.

Get the configured time-zone for a given time (varying as per summertime adjustments).

On Unix systems the output of this function depends on:

  1. The value of TZ environment variable (if set)

  2. The system time zone (usually configured by /etc/localtime symlink)

For details see tzset(3) and localtime(3).

Example:

> let t = UTCTime (fromGregorian 2021 7 1) 0
> getTimeZone t
CEST
> setEnv "TZ" "America/New_York" >> getTimeZone t
EDT
> setEnv "TZ" "Europe/Berlin" >> getTimeZone t
CEST

On Windows systems the output of this function depends on:

  1. The value of TZ environment variable (if set). See here for how Windows interprets this variable.

  2. The system time zone, configured in Settings

newtypenewtype WrappedArrow (a :: Type -> Type -> Type) b c
#

Constructors

Instances12Generic1, Functor, Applicative, Alternative, Alt, Apply, …
newtypenewtype WrappedMonad (m :: Type -> Type) a
#

Constructors

Instances15Generic1, Monad, Functor, Applicative, Alternative, Distributive, …
datadata Chan a
#

Chan is an abstract type representing an unbounded FIFO channel.

Instances1Eq
  • Eq (Chan a)Defined in base-4.23.0.0 · Control.Concurrent.Chan
newtypenewtype QSem
#

QSem is a quantity semaphore in which the resource is acquired and released in units of one. It provides guaranteed FIFO ordering for satisfying blocked waitQSem calls.

The pattern

bracket_ waitQSem signalQSem (...)

is safe; it never loses a unit of the resource.

datadata QSemN
#

QSemN is a quantity semaphore in which the resource is acquired and released in arbitrary amounts. It provides guaranteed FIFO ordering for satisfying blocked waitQSemN calls.

The pattern

bracket_ (waitQSemN n) (signalQSemN n) (...)

is safe; it never loses any of the resource.

datadata FieldFormat
#

Description of field formatting for formatArg. See UNIX printf(3) for a description of how field formatting works.

Constructors

Instances3Arbitrary, CoArbitrary, Function
datadata FormatParse
#

The "format parser" walks over argument-type-specific modifier characters to find the primary format character. This is the type of its result.

Constructors

Instances3Arbitrary, CoArbitrary, Function
classclass IsChar c where
#

This class, with only the one instance, is used as a workaround for the fact that String, as a concrete type, is not allowable as a typeclass instance. IsChar is exported for backward-compatibility.

Methods

Instances1IsChar
  • IsChar CharDefined in base-4.23.0.0 · Text.Printf
classclass PrintfArg a where
#

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.

Instances19PrintfArg, …
classclass PrintfType t where
#

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.

Instances3PrintfType
datadata Complete
#

How to complete a command line option. The Show instance is suitable for parsing from shell scripts.

Constructors

Instances3Eq, Ord, Show
  • Eq CompleteDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Complete
  • Ord CompleteDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Complete
  • Show CompleteDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Complete
datadata HelpFormat
#

Specify the format to output the help.

Constructors

Instances7Bounded, Enum, Eq, Ord, Read, Show, …
  • Bounded HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
  • Enum HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
  • Eq HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
  • Ord HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
  • Read HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
  • Show HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
  • Default HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
datadata Arg a
#

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
    • argValue :: Update a

      A way of processing the argument.

    • argType :: FlagHelp

      The type of data for the argument, i.e. FILE/DIR/EXT

    • argRequire :: Bool

      Is at least one of these arguments required, the command line will fail if none are set

Instances3Remap, Show, Packer
  • Remap ArgDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Show (Arg a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help · orphan
  • Packer a => Packer (Arg a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Helper
datadata Flag a
#

A flag, consisting of a list of flag names and other information.

Constructors

Instances3Remap, Show, Packer
  • Remap FlagDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Show (Flag a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help · orphan
  • Packer a => Packer (Flag a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Helper
datadata FlagInfo
#

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

Instances4Eq, Ord, Show, Packer
  • Eq FlagInfoDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Ord FlagInfoDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Show FlagInfoDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Packer FlagInfoDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Helper
datadata Group a
#

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

Instances5Functor, Show, Semigroup, Monoid, Packer
  • Functor GroupDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Show a => Show (Group a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Semigroup (Group a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Monoid (Group a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Packer a => Packer (Group a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Helper
typetype Help = String
#

A help message that goes with either a flag or a mode.

datadata Mode a
#

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:

To produce the help information for a mode, either use helpText or show.

Constructors

Instances3Remap, Show, Packer
  • Remap ModeDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Show (Mode a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help · orphan
  • Packer a => Packer (Mode a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Helper
typetype Name = String
#

A name, either the name of a flag (--foo) or the name of a mode.

classclass Remap (m :: Type -> Type) where
#

Like functor, but where the the argument isn't just covariant.

Methods

  • remap :: (a -> b) -> (b -> (a, a -> b)) -> m a -> m b

    Convert between two values.

Instances3Remap
  • Remap ArgDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Remap FlagDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Remap ModeDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
typetype 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).

datadata Permissions
#
Instances4Eq, Ord, Read, Show
  • Eq PermissionsDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Ord PermissionsDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Read PermissionsDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Show PermissionsDefined in directory-1.3.11.0 · System.Directory.Internal.Common
datadata 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.

Constructors

  • XdgData

    For data files (e.g. images). It uses the XDG_DATA_HOME environment variable. On non-Windows systems, the default is ~/.local/share. On Windows, the default is %APPDATA% (e.g. C:/Users/<user>/AppData/Roaming). Can be considered as the user-specific equivalent of /usr/share.

  • XdgConfig

    For configuration files. It uses the XDG_CONFIG_HOME environment variable. On non-Windows systems, the default is ~/.config. On Windows, the default is %APPDATA% (e.g. C:/Users/<user>/AppData/Roaming). Can be considered as the user-specific equivalent of /etc.

  • XdgCache

    For non-essential files (e.g. cache). It uses the XDG_CACHE_HOME environment variable. On non-Windows systems, the default is ~/.cache. On Windows, the default is %LOCALAPPDATA% (e.g. C:/Users/<user>/AppData/Local). Can be considered as the user-specific equivalent of /var/cache.

  • 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 XdgData. It uses the XDG_STATE_HOME environment variable. On non-Windows systems, the default is ~/.local/state. On Windows, the default is %LOCALAPPDATA% (e.g. C:/Users/<user>/AppData/Local).

Instances6Bounded, Enum, Eq, Ord, Read, Show
  • Bounded XdgDirectoryDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Enum XdgDirectoryDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Eq XdgDirectoryDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Ord XdgDirectoryDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Read XdgDirectoryDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Show XdgDirectoryDefined in directory-1.3.11.0 · System.Directory.Internal.Common
datadata XdgDirectoryList
#

Search paths for various application data, as specified by the XDG Base Directory Specification.

The list of paths is split using System.FilePath.searchPathSeparator, which on Windows is a semicolon.

Note: On Windows, XdgDataDirs and XdgConfigDirs usually yield the same result.

Constructors

  • XdgDataDirs

    For data files (e.g. images). It uses the XDG_DATA_DIRS environment variable. On non-Windows systems, the default is /usr/local/share/ and /usr/share/. On Windows, the default is %PROGRAMDATA% or %ALLUSERSPROFILE% (e.g. C:/ProgramData).

  • XdgConfigDirs

    For configuration files. It uses the XDG_CONFIG_DIRS environment variable. On non-Windows systems, the default is /etc/xdg. On Windows, the default is %PROGRAMDATA% or %ALLUSERSPROFILE% (e.g. C:/ProgramData).

Instances6Bounded, Enum, Eq, Ord, Read, Show
classclass 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:

Examples
Example1 expression
Nothing <|> Just 42Just 42
Example1 expression
[1, 2] <|> [3, 4][1,2,3,4]
Example1 expression
empty <|> print (2^15)32768

Methods

  • empty :: f a

    The identity of <|>

    empty <|> a     == a
    a     <|> empty == a
  • (<|>) :: f a -> f a -> f ainfixl 3

    An associative binary operation

  • some :: f a -> f [a]

    One or more.

    Examples
    Example1 expression
    some (putStr "la")lalalalalalalalala... * goes on forever *
    Example1 expression
    some Nothingnothing
    Example1 expression
    take 5 <$> some (Just 1)* hangs forever *

    Note that this function can be used with Parsers based on Applicatives. In that case some parser will attempt to parse parser one or more times until it fails.

  • many :: f a -> f [a]

    Zero or more.

    Examples
    Example1 expression
    many (putStr "la")lalalalalalalalala... * goes on forever *
    Example1 expression
    many NothingJust []
    Example1 expression
    take 5 <$> many (Just 1)* hangs forever *

    Note that this function can be used with Parsers based on Applicatives. In that case many parser will attempt to parse parser zero or more times until it fails.

Instances86Alternative, …
classclass Functor f => Applicative (f :: Type -> Type) where
#

A functor with application, providing operations to

  • embed pure expressions (pure), and

  • sequence computations and combine their results (<*> and liftA2).

A minimal complete definition must include implementations of pure and one of either <*> or liftA2. If it defines both, then they must behave the same as their default definitions:

(<*>) = liftA2 id
liftA2 f x y = f Prelude.<$> x <*> y

Further, any definition must satisfy the following:

Identity
pure id <*> v = v
Composition
pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
Homomorphism
pure f <*> pure x = pure (f x)
Interchange
u <*> pure y = 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

liftA2 p (liftA2 q u v) = liftA2 f u . liftA2 g v

If f is also a Monad, it should satisfy

(which implies that pure and <*> satisfy the applicative functor laws).

Methods

  • pure :: a -> f a

    Lift a value into the Structure.

    Examples
    Example1 expression
    pure 1 :: Maybe IntJust 1
    Example1 expression
    pure 'z' :: [Char]"z"
    Example1 expression
    pure (pure ":D") :: Maybe [String]Just [":D"]
  • (<*>) :: f (a -> b) -> f a -> f binfixl 4

    Sequential application.

    A few functors support an implementation of <*> that is more efficient than the default one.

    Example

    Used in combination with (Data.Functor.<$>), (<*>) can be used to build a record.

    Example1 expression
    data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz}
    Example3 expressions
    produceFoo :: Applicative f => f FooproduceBar :: Applicative f => f BarproduceBaz :: Applicative f => f Baz
    Example2 expressions
    mkState :: Applicative f => f MyStatemkState = 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
    Example1 expression
    liftA2 (,) (Just 3) (Just 5)Just (3,5)
    Example1 expression
    liftA2 (+) [1, 2, 3] [4, 5, 6][5,6,7,6,7,8,7,8,9]
  • (*>) :: f a -> f b -> f binfixl 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.

    Example1 expression
    Just 2 *> Just 3Just 3
    Example1 expression
    Nothing *> Just 3Nothing

    Of course a more interesting use case would be to have effectful computations instead of just returning pure values.

    Example4 expressions
    import Data.Charimport GHC.Internal.Text.ParserCombinators.ReadPlet p = string "my name is " *> munch1 isAlpha <* eofreadP_to_S p "my name is Simon"[("Simon","")]
  • (<*) :: f a -> f b -> f ainfixl 4

    Sequence actions, discarding the value of the second argument.

Instances200Applicative, …
classclass 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:

Identity

fmap id == id

Composition

fmap (f . g) == fmap f . fmap g

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. See these articles by School of Haskell or David Luposchainsky for an explanation.

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 Bifunctor instance that allows both the last and the penultimate parameters to be mapped over.

    Examples

    Convert from a Maybe Int to a Maybe String using show:

    Example2 expressions
    fmap show NothingNothingfmap show (Just 3)Just "3"

    Convert from an Either Int Int to an Either Int String using show:

    Example2 expressions
    fmap show (Left 17)Left 17fmap show (Right 17)Right "17"

    Double each element of a list:

    Example1 expression
    fmap (*2) [1,2,3][2,4,6]

    Apply even to the second element of a pair:

    Example1 expression
    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:

    Example1 expression
    fmap even ("hello", 1.0, 4)("hello",1.0,True)
  • (<$) :: a -> f b -> f ainfixl 4

    Replace all locations in the input with the same value. The default definition is fmap . const, but this may be overridden with a more efficient version.

    Examples

    Perform a computation with Maybe and replace the result with a constant value if it is Just:

    Example2 expressions
    'a' <$ Just 2Just 'a''a' <$ NothingNothing
Instances375Functor, …
  • Functor OnlyDefined in Only-0.1 · Data.Tuple.Only
  • Functor GenDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Gen
  • Functor BlindDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor FixedDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor LargeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor NegativeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor NoShrinkDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor NonEmptyListDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor NonNegativeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor NonPositiveDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor NonZeroDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor OrderedListDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor PositiveDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor Shrink2Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor SmallDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor SmartDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor SortedListDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor RoseDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Property
  • Functor KeyMapDefined in aeson-2.2.5.1 · Data.Aeson.KeyMap
  • Functor FromJSONKeyFunctionDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON

    Only law abiding up to interpretation

  • Functor IResultDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Functor ParserDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Functor ResultDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Functor GetDefined in asn1-encoding-0.9.6 · Data.ASN1.Get
  • Functor ResultDefined in asn1-encoding-0.9.6 · Data.ASN1.Get
  • Functor AsyncDefined in async-2.2.6 · Control.Concurrent.Async.Internal
  • Functor ConcurrentlyDefined in async-2.2.6 · Control.Concurrent.Async.Internal
  • Functor ResultDefined in attoparsec-0.14.4 · Data.Attoparsec.ByteString.Lazy
  • Functor ResultDefined in attoparsec-0.14.4 · Data.Attoparsec.Text.Lazy
  • Functor ComplexDefined in base-4.23.0.0 · Data.Complex
  • Functor FirstDefined in base-4.23.0.0 · Data.Semigroup
  • Functor LastDefined in base-4.23.0.0 · Data.Semigroup
  • Functor MaxDefined in base-4.23.0.0 · Data.Semigroup
  • Functor MinDefined in base-4.23.0.0 · Data.Semigroup
  • Functor ArgDescrDefined in base-4.23.0.0 · System.Console.GetOpt
  • Functor ArgOrderDefined in base-4.23.0.0 · System.Console.GetOpt
  • Functor OptDescrDefined in base-4.23.0.0 · System.Console.GetOpt
  • Functor Base16Defined in base16-1.0 · Data.Base16.Types.Internal
  • Functor ArrayDefined in basement-0.0.16 · Basement.BoxedArray
  • Functor DecoderDefined in binary-0.8.9.3 · Data.Binary.Get.Internal
  • Functor GetDefined in binary-0.8.9.3 · Data.Binary.Get.Internal
  • Functor PutMDefined in binary-0.8.9.3 · Data.Binary.Put
  • Functor MarkupMDefined in blaze-markup-0.8.3.0 · Text.Blaze.Internal
  • Functor PutDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.Internal
  • Functor ParserDefined in cassava-0.5.4.1 · Data.Csv.Conversion
  • Functor HeaderParserDefined in cassava-0.5.4.1 · Data.Csv.Incremental
  • Functor ParserDefined in cassava-0.5.4.1 · Data.Csv.Incremental
  • Functor RecordsDefined in cassava-0.5.4.1 · Data.Csv.Streaming
  • Functor PPDefined in cborg-0.2.10.0 · Codec.CBOR.Pretty
  • Functor GetDefined in cereal-0.5.8.3 · Data.Serialize.Get
  • Functor ResultDefined in cereal-0.5.8.3 · Data.Serialize.Get
  • Functor PutMDefined in cereal-0.5.8.3 · Data.Serialize.Put
  • Functor CaptureDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Annotate
  • Functor GroupDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Functor ArgOrderDefined in cmdargs-0.10.22 · System.Console.CmdArgs.GetOpt
  • Functor CmdArgsDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Implicit.Type
  • Functor RGBDefined in colour-2.3.7 · Data.Colour.RGB
  • Functor SCCDefined in containers-0.8 · Data.Graph
  • Functor IntMapDefined in containers-0.8 · Data.IntMap.Internal
  • Functor DigitDefined in containers-0.8 · Data.Sequence.Internal
  • Functor ElemDefined in containers-0.8 · Data.Sequence.Internal
  • Functor FingerTreeDefined in containers-0.8 · Data.Sequence.Internal
  • Functor NodeDefined in containers-0.8 · Data.Sequence.Internal
  • Functor SeqDefined in containers-0.8 · Data.Sequence.Internal
  • Functor ViewLDefined in containers-0.8 · Data.Sequence.Internal
  • Functor ViewRDefined in containers-0.8 · Data.Sequence.Internal
  • Functor PostOrderDefined in containers-0.8 · Data.Tree
  • Functor TreeDefined in containers-0.8 · Data.Tree
  • Functor CryptoFailableDefined in crypton-2.1.7 · Crypto.Error.Types
  • Functor GetDefined in crypton-asn1-encoding-0.10.0 · Data.ASN1.Get
  • Functor ResultDefined in crypton-asn1-encoding-0.10.0 · Data.ASN1.Get
  • Functor ParseASN1Defined in crypton-asn1-parse-0.10.0 · Data.ASN1.Parse
  • Functor ParserDefined in crypton-socks-0.6.2 · Network.Socks5.Parse
  • Functor DNonEmptyDefined in dlist-1.0 · Data.DList.DNonEmpty.Internal
  • Functor DListDefined in dlist-1.0 · Data.DList.Internal
  • Functor DocDefined in doclayout-0.6 · Text.DocLayout
  • Functor FlatDocDefined in doclayout-0.6 · Text.DocLayout
  • Functor AttrDefined in doclayout-0.6 · Text.DocLayout.Attributed
  • Functor AttributedDefined in doclayout-0.6 · Text.DocLayout.Attributed
  • Functor PutMEDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Functor StrictSinkDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Functor StrictSinkEDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Functor StrictSinkExplicitDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Functor PprMDefined in ghc-boot-th-10.0.0.20260917 · GHC.Boot.TH.PprLib
  • Functor NonEmptyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.NonEmpty · orphan
  • Functor HandlerDefined in ghc-internal-10.0.0 · GHC.Internal.Control.Exception
  • Functor IdentityDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Identity
  • Functor FirstDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Functor LastDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Functor DownDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Ord
  • Functor DualDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Functor ProductDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Functor SumDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Functor ZipListDefined in ghc-internal-10.0.0 · GHC.Internal.Functor.ZipList
  • Functor NoIODefined in ghc-internal-10.0.0 · GHC.Internal.GHCi
  • Functor Par1Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor GenClosureDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Functor GenStackFieldDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Functor GenStackFrameDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Functor GenStgStackClosureDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Functor MaybeDefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor STMDefined in ghc-internal-10.0.0 · GHC.Internal.STM
  • Functor QDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Monad
  • Functor TyVarBndrDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Functor PDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadP
  • Functor ReadPDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadP
  • Functor ReadPrecDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadPrec
  • Functor SoloDefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor IODefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor KeyConsumedDefined in haskeline-0.8.5.0 · System.Console.Haskeline.Command
  • Functor KeyMapDefined in haskeline-0.8.5.0 · System.Console.Haskeline.Command
  • Functor ArgModeDefined in haskeline-0.8.5.0 · System.Console.Haskeline.LineState
  • Functor DiffLineDefined in hledger-1.52.4 · Hledger.Cli.Commands.Rewrite
  • Functor AccountDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Functor PeriodDataDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Functor BorderDefined in hledger-lib-1.52.4 · Hledger.Write.Spreadsheet
  • Functor LocalTimeDefined in hourglass-0.2.12 · Data.Hourglass.Local
  • Functor LenientDataDefined in http-api-data-0.7 · Web.Internal.HttpApiData
  • Functor HistoriedResponseDefined in http-client-0.7.19 · Network.HTTP.Client
  • Functor ResponseDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Functor RootDefined in math-functions-0.3.4.4 · Numeric.RootFinding
  • Functor SequenceDefined in math-functions-0.3.4.4 · Numeric.Series
  • Functor ErrorFancyDefined in megaparsec-9.5.0 · Text.Megaparsec.Error
  • Functor ErrorItemDefined in megaparsec-9.5.0 · Text.Megaparsec.Error
  • Functor PackerDefined in memory-0.18.0 · Data.ByteArray.Pack.Internal
  • Functor ChunkDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Help.Chunk
  • Functor ComplResultDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Functor CompletionDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Functor PDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Functor CReaderDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor OptReaderDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor OptionDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor ParserDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor ParserFailureDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor ParserInfoDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor ParserMDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor ParserResultDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor ReadMDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Functor ConsumedDefined in parsec-3.1.18.0 · Text.Parsec.Prim
  • Functor AnnotDetailsDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
  • Functor DocDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
  • Functor SpanDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJ
  • Functor DocDefined in prettyprinter-1.7.2 · Prettyprinter.Internal

    Alter the document’s annotations.

    This instance makes Doc more flexible (because it can be used in Functor-polymorphic values), but fmap is much less readable compared to using reAnnotate in code that only works for Doc anyway. Consider using the latter when the type does not matter.

  • Functor FlattenResultDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Functor SimpleDocStreamDefined in prettyprinter-1.7.2 · Prettyprinter.Internal

    Alter the document’s annotations.

    This instance makes SimpleDocStream more flexible (because it can be used in Functor-polymorphic values), but fmap is much less readable compared to using reAnnotateST in code that only works for SimpleDocStream anyway. Consider using the latter when the type does not matter.

  • Functor SimpleDocTreeDefined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.SimpleDocTree

    Alter the document’s annotations.

    This instance makes SimpleDocTree more flexible (because it can be used in Functor-polymorphic values), but fmap is much less readable compared to using reAnnotateST in code that only works for SimpleDocTree anyway. Consider using the latter when the type does not matter.

  • Functor ArrayDefined in primitive-0.9.1.0 · Data.Primitive.Array
  • Functor SmallArrayDefined in primitive-0.9.1.0 · Data.Primitive.SmallArray
  • Functor PackerDefined in ram-0.22.1 · Data.ByteArray.Pack.Internal
  • Functor CharMapDefined in regex-tdfa-1.3.2.6 · Data.IntMap.CharMap2
  • Functor ReqDefined in req-3.13.4 · Network.HTTP.Req
  • Functor ResultDefined in shakespeare-2.2.0 · Text.Hamlet.Parse
  • Functor STMDefined in stm-2.5.3.1 · Control.Sequential.STM
  • Functor MaybeDefined in strict-0.5.1 · Data.Strict.Maybe
  • Functor HeaderDefined in tabular-0.2.2.8 · Text.Tabular
  • Functor ParserDefined in tasty-1.5.4 · Test.Tasty.Patterns.Parser
  • Functor WindowDefined in terminal-size-0.3.4 · System.Console.Terminal.Common
  • Functor CapabilityDefined in terminfo-0.4.1.7 · System.Console.Terminfo.Base
  • Functor LocalTimeDefined in time-hourglass-0.3.0 · Time.LocalTime
  • Functor HandshakeMDefined in tls-2.4.9 · Network.TLS.Handshake.State
  • Functor RecordMDefined in tls-2.4.9 · Network.TLS.Record.State
  • Functor TLSStDefined in tls-2.4.9 · Network.TLS.State
  • Functor VectorDefined in vector-0.13.2.0 · Data.Vector
  • Functor IdDefined in vector-0.13.2.0 · Data.Vector.Fusion.Util
  • Functor VectorDefined in vector-0.13.2.0 · Data.Vector.Strict
  • Functor BoxDefined in vector-stream-0.1.0.1 · Data.Stream.Monadic
  • Functor BoolPairDefined in witherable-0.5 · Witherable
  • Functor BasicIODefined in wizards-1.0.3 · System.Console.Wizard.BasicIO
  • Functor HaskelineDefined in wizards-1.0.3 · System.Console.Wizard.Haskeline
  • Functor WithSettingsDefined in wizards-1.0.3 · System.Console.Wizard.Haskeline
  • Functor ArbitraryIODefined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor CharacterDefined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor LineDefined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor LinePrewrittenDefined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor OutputDefined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor OutputLnDefined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor PasswordDefined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor PureDefined in wizards-1.0.3 · System.Console.Wizard.Pure
  • Functor StreamDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Functor []Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • DRG gen => Functor (MonadPseudoRandom gen)Defined in crypton-2.1.7 · Crypto.Random.Types
  • Functor ProxyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Proxy
  • Functor U1Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor V1Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (PolyDiff a)Defined in Diff-2.0.1 · Data.Algorithm.Diff.Type
  • Functor (Fun a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Function
  • Functor (Shrinking s)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Functor (PropertyM m)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Monadic
  • Functor (TkArray k)Defined in aeson-2.2.5.1 · Data.Aeson.Decoding.Tokens
  • Functor (TkRecord k)Defined in aeson-2.2.5.1 · Data.Aeson.Decoding.Tokens
  • Functor (Tokens k)Defined in aeson-2.2.5.1 · Data.Aeson.Decoding.Tokens
  • Functor (Tagged2 s)Defined in aeson-2.2.5.1 · Data.Aeson.Types.Generic
  • Functor (MkParser inp)Defined in appar-0.1.8 · Text.Appar.Parser
  • Functor (ConcurrentlyE e)Defined in async-2.2.6 · Control.Concurrent.Async.Internal
  • Functor (IResult i)Defined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
  • Functor (Parser i)Defined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
  • Functor (Arg a)Defined in base-4.23.0.0 · Data.Semigroup
  • Functor (Base64 k)Defined in base64-1.0 · Data.Base64.Types.Internal
  • Functor (Vect n)Defined in basement-0.0.16 · Basement.Sized.Vect
  • Functor (Decoder s)Defined in cborg-0.2.10.0 · Codec.CBOR.Decoding
  • Functor (IncrementalDecoder s)Defined in cborg-0.2.10.0 · Codec.CBOR.Read
  • Functor (Map k)Defined in containers-0.8 · Data.Map.Internal
  • Functor (State s)Defined in containers-0.8 · Utils.Containers.Internal.State
  • Functor (C mu)Defined in control-monad-free-0.6.2 · Control.Monad.Free.Improve
  • Functor (Array i)Defined in ghc-internal-10.0.0 · GHC.Internal.Arr
  • Functor (ST s)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Monad.ST.Lazy.Imp
  • Functor (Either a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Either
  • Functor (StateL s)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Utils
  • Functor (StateR s)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Utils
  • Functor (ST s)Defined in ghc-internal-10.0.0 · GHC.Internal.ST
  • Functor (Tuple2 a)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor (CompoundPeriodicReport a)Defined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • Functor (PeriodicReport a)Defined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • Functor (PeriodicReportRow a)Defined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • Functor (Cell border)Defined in hledger-lib-1.52.4 · Hledger.Write.Spreadsheet
  • Functor (IPRTable k)Defined in iproute-1.7.15 · Data.IP.RouteTable.Internal
  • Functor (Parser byteArray)Defined in memory-0.18.0 · Data.ByteArray.Parse
  • Functor (Vector n)Defined in mlkem-0.2.3.0 · Vector
  • Functor (UniqueParser s)Defined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.SimpleDocTree
  • Functor (Parser byteArray)Defined in ram-0.22.1 · Data.ByteArray.Parse
  • Functor (Either a)Defined in strict-0.5.1 · Data.Strict.Either
  • Functor (These a)Defined in strict-0.5.1 · Data.Strict.These
  • Functor (Pair e)Defined in strict-0.5.1 · Data.Strict.Tuple
  • Functor (IParser t)Defined in text-2.1.4 · Data.Text.Internal.Read
  • Functor (These a)Defined in these-1.2.1 · Data.These
  • Functor (PacketFlightM b)Defined in tls-2.4.9 · Network.TLS.IO
  • Functor (HashMap k)Defined in unordered-containers-0.2.21 · Data.HashMap.Internal
  • Functor (Step s)Defined in vector-stream-0.1.0.1 · Data.Stream.Monadic
  • Functor ((:->) a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Function
  • Functor backend => Functor (Wizard backend)Defined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor f => Functor (Free f)Defined in control-monad-free-0.6.2 · Control.Monad.Free
  • Functor f => Functor (Zippy f)Defined in semialign-1.3.1.1 · Data.Zip
  • Functor f => Functor (MaybeApply f)Defined in semigroupoids-6.0.2 · Data.Functor.Bind.Class
  • Functor f => Functor (WrappedApplicative f)Defined in semigroupoids-6.0.2 · Data.Functor.Bind.Class
  • Functor f => Functor (Act f)Defined in semigroupoids-6.0.2 · Data.Semigroup.Bifoldable
  • Functor f => Functor (Act f)Defined in semigroupoids-6.0.2 · Data.Semigroup.Foldable
  • Functor f => Functor (Ap f)Defined in tasty-1.5.4 · Test.Tasty.Runners.Reducers
  • Functor f => Functor (Lift f)Defined in transformers-0.6.3.0 · Control.Applicative.Lift
  • Functor f => Functor (WrappedFoldable f)Defined in witherable-0.5 · Witherable
  • Functor m => Functor (DumbTerm m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.Backend.DumbTerm
  • Functor m => Functor (Draw m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.Backend.Terminfo
  • Functor m => Functor (InputT m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.InputT
  • Functor m => Functor (HtmlT m)Defined in lucid-2.11.20260427 · Lucid.Base

    Just re-uses Monad.

  • Functor m => Functor (Permutation m)Defined in parser-combinators-1.3.1 · Control.Applicative.Permutations
  • Functor m => Functor (Permutation m)Defined in parser-combinators-1.3.1 · Control.Monad.Permutations
  • Functor m => Functor (QuoteToQuasi m)Defined in th-compat-0.1.7 · Language.Haskell.TH.Syntax.Compat
  • Functor m => Functor (RecvHandshake13M m)Defined in tls-2.4.9 · Network.TLS.Handshake.Common13
  • Functor m => Functor (MaybeT m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Maybe
  • Functor p => Functor (Branch p)Defined in parser-combinators-1.3.1 · Control.Applicative.Permutations
  • Monad m => Functor (ZeptoT m)Defined in attoparsec-0.14.4 · Data.Attoparsec.Zepto
  • Monad m => Functor (WrappedMonad m)Defined in base-4.23.0.0 · Control.Applicative
  • Monad m => Functor (Handler m)Defined in exceptions-0.10.12 · Control.Monad.Catch
  • Monad m => Functor (CatchT m)Defined in exceptions-0.10.12 · Control.Monad.Catch.Pure
  • Monad m => Functor (CmdM m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.Command
  • Monad m => Functor (ListT m)Defined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Monad m => Functor (NondetT m)Defined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Monad m => Functor (Stream m)Defined in vector-stream-0.1.0.1 · Data.Stream.Monadic
  • Ord k => Functor (EnumMap k)Defined in regex-tdfa-1.3.2.6 · Data.IntMap.EnumMap2
  • Arrow a => Functor (ArrowMonad a)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Arrow
  • Bifunctor p => Functor (Fix p)Defined in bifunctors-5.6.3 · Data.Bifunctor.Fix
  • Bifunctor p => Functor (Join p)Defined in bifunctors-5.6.3 · Data.Bifunctor.Join
  • Functor (Mag a b)Defined in bifunctors-5.6.3 · Data.Biapplicative
  • Functor (Const m)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Const
  • Functor (URec Char)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (URec Double)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (URec Float)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (URec Int)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (URec Word)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (URec (Ptr ()))Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (Tuple3 a b)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor (Reply e s)Defined in megaparsec-9.5.0 · Text.Megaparsec.Internal
  • Functor (Result s e)Defined in megaparsec-9.5.0 · Text.Megaparsec.Internal
  • Functor (Bazaar a b)Defined in microlens-0.5.0.0 · Lens.Micro
  • Functor (Reply s u)Defined in parsec-3.1.18.0 · Text.Parsec.Prim
  • Functor (StackMachine output style)Defined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.StackMachine
  • Functor (CopastroSum p a)Defined in profunctors-5.6.3 · Data.Profunctor.Choice
  • Functor (CotambaraSum p a)Defined in profunctors-5.6.3 · Data.Profunctor.Choice
  • Functor (PastroSum p a)Defined in profunctors-5.6.3 · Data.Profunctor.Choice
  • Functor (Environment p a)Defined in profunctors-5.6.3 · Data.Profunctor.Closed
  • Functor (Bar t b)Defined in profunctors-5.6.3 · Data.Profunctor.Mapping
  • Functor (FreeMapping p a)Defined in profunctors-5.6.3 · Data.Profunctor.Mapping
  • Functor (Copastro p a)Defined in profunctors-5.6.3 · Data.Profunctor.Strong
  • Functor (Cotambara p a)Defined in profunctors-5.6.3 · Data.Profunctor.Strong
  • Functor (Pastro p a)Defined in profunctors-5.6.3 · Data.Profunctor.Strong
  • Functor (Baz t b)Defined in profunctors-5.6.3 · Data.Profunctor.Traversing
  • Functor (Bazaar a b)Defined in profunctors-5.6.3 · Data.Profunctor.Traversing
  • Functor (FreeTraversing p a)Defined in profunctors-5.6.3 · Data.Profunctor.Traversing
  • Functor (Coyoneda p a)Defined in profunctors-5.6.3 · Data.Profunctor.Yoneda
  • Functor (Yoneda p a)Defined in profunctors-5.6.3 · Data.Profunctor.Yoneda
  • Functor (Tagged s)Defined in tagged-0.8.11 · Data.Tagged
  • Functor (Constant a)Defined in transformers-0.6.3.0 · Data.Functor.Constant
  • Functor (bi a) => Functor (Biap bi a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Biap
  • Functor (t m) => Functor (LiftingAccum t m)Defined in mtl-2.3.2 · Control.Monad.Accum
  • Functor (t m) => Functor (LiftingSelect t m)Defined in mtl-2.3.2 · Control.Monad.Select
  • Functor f => Functor (Ap f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Functor f => Functor (Alt f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Functor f => Functor (Rec1 f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor f => Functor (Indexing f)Defined in indexed-traversable-0.1.5 · WithIndex
  • Functor f => Functor (Static f a)Defined in semigroupoids-6.0.2 · Data.Semigroupoid.Static
  • Functor f => Functor (Backwards f)Defined in transformers-0.6.3.0 · Control.Applicative.Backwards

    Derived instance.

  • Functor f => Functor (Reverse f)Defined in transformers-0.6.3.0 · Data.Functor.Reverse

    Derived instance.

  • Functor m => Functor (Kleisli m a)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Arrow
  • Functor m => Functor (StateT s m)Defined in microlens-0.5.0.0 · Lens.Micro
  • Functor m => Functor (AccumT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Accum
  • Functor m => Functor (ExceptT e m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Except
  • Functor m => Functor (IdentityT m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Identity
  • Functor m => Functor (ReaderT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Reader
  • Functor m => Functor (SelectT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Select
  • Functor m => Functor (StateT s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.State.Lazy
  • Functor m => Functor (StateT s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.State.Strict
  • Functor m => Functor (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.CPS
  • Functor m => Functor (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Lazy
  • Functor m => Functor (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Strict
  • Functor w => Functor (EnvT e w)Defined in comonad-5.0.10 · Control.Comonad.Trans.Env
  • Functor w => Functor (StoreT s w)Defined in comonad-5.0.10 · Control.Comonad.Trans.Store
  • Functor w => Functor (TracedT m w)Defined in comonad-5.0.10 · Control.Comonad.Trans.Traced
  • Monad m => Functor (Reader r m)Defined in basement-0.0.16 · Basement.Compat.MonadTrans
  • Monad m => Functor (State s m)Defined in basement-0.0.16 · Basement.Compat.MonadTrans
  • Monad m => Functor (StateT s m)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Utils
  • Monad m => Functor (Bundle m v)Defined in vector-0.13.2.0 · Data.Vector.Fusion.Bundle.Monadic
  • Arrow a => Functor (WrappedArrow a b)Defined in base-4.23.0.0 · Control.Applicative
  • Profunctor p => Functor (TambaraSum p a)Defined in profunctors-5.6.3 · Data.Profunctor.Choice
  • Profunctor p => Functor (Closure p a)Defined in profunctors-5.6.3 · Data.Profunctor.Closed
  • Profunctor p => Functor (Coprep p)Defined in profunctors-5.6.3 · Data.Profunctor.Rep
  • Profunctor p => Functor (Prep p)Defined in profunctors-5.6.3 · Data.Profunctor.Rep
  • Profunctor p => Functor (Tambara p a)Defined in profunctors-5.6.3 · Data.Profunctor.Strong
  • (Contravariant f, Contravariant g) => Functor (Compose f g)Defined in contravariant-1.5.6 · Data.Functor.Contravariant.Compose
  • (Applicative f, Monad f) => Functor (WhenMissing f x)Defined in containers-0.8 · Data.IntMap.Internal
  • (Functor f, Functor g) => Functor (ComposeCF f g)Defined in contravariant-1.5.6 · Data.Functor.Contravariant.Compose
  • (Functor f, Functor g) => Functor (ComposeFC f g)Defined in contravariant-1.5.6 · Data.Functor.Contravariant.Compose
  • (Functor f, Functor g) => Functor (These1 f g)Defined in these-1.2.1 · Data.Functor.These
  • (Functor f, Functor g) => Functor (f :+: g)Defined in wizards-1.0.3 · System.Console.Wizard.Internal
  • (Functor f, Functor m) => Functor (FreeT f m)Defined in control-monad-free-0.6.2 · Control.Monad.Free
  • (Generic1 f, Functor (Rep1 f)) => Functor (Generically1 f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (Cokleisli w a)Defined in comonad-5.0.10 · Control.Comonad
  • Functor (K1 i c)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (Tuple4 a b c)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor (ParsecT e s m)Defined in megaparsec-9.5.0 · Text.Megaparsec.Internal
  • Functor (ParsecT s u m)Defined in parsec-3.1.18.0 · Text.Parsec.Prim
  • Functor (Costar f a)Defined in profunctors-5.6.3 · Data.Profunctor.Types
  • Functor (Forget r a)Defined in profunctors-5.6.3 · Data.Profunctor.Types
  • Functor (ContT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Cont
  • Functor ((->) r)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor (f (g m)) => Functor (ComposeT f g m)Defined in mmorph-1.2.2 · Control.Monad.Trans.Compose
  • Functor f => Functor (WhenMatched f x y)Defined in containers-0.8 · Data.IntMap.Internal
  • Functor f => Functor (Star f a)Defined in profunctors-5.6.3 · Data.Profunctor.Types
  • (Applicative f, Monad f) => Functor (WhenMissing f k x)Defined in containers-0.8 · Data.Map.Internal
  • (Functor f, Functor g) => Functor (Product f g)Defined in base-4.23.0.0 · Data.Functor.Product
  • (Functor f, Functor g) => Functor (Sum f g)Defined in base-4.23.0.0 · Data.Functor.Sum
  • (Functor f, Functor g) => Functor (f :*: g)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • (Functor f, Functor g) => Functor (f :+: g)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Bifunctor p => Functor (Flip p a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Flip
  • Bifunctor p => Functor (WrappedBifunctor p a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Wrapped
  • Functor (Clown f a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Clown
  • Functor (Tuple5 a b c d)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Functor f => Functor (WhenMatched f k x y)Defined in containers-0.8 · Data.Map.Internal
  • Functor f => Functor (M1 i c f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor g => Functor (Joker g a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Joker
  • Functor m => Functor (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.CPS
  • Functor m => Functor (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.Lazy
  • Functor m => Functor (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.Strict
  • Profunctor p => Functor (Codensity p a)Defined in profunctors-5.6.3 · Data.Profunctor.Ran
  • Reifies s (ReifiedApplicative f) => Functor (ReflectedApplicative f s)Defined in reflection-2.1.9 · Data.Reflection
  • (Functor f, Functor g) => Functor (Compose f g)Defined in base-4.23.0.0 · Data.Functor.Compose
  • (Functor f, Functor g) => Functor (f :.: g)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Functor (Tuple6 a b c d e)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad state => Functor (Builder collection mutCollection step state err)Defined in basement-0.0.16 · Basement.MutableBuilder
  • (Functor (f a), Functor (g a)) => Functor (Product f g a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Product
  • (Functor (f a), Functor (g a)) => Functor (Sum f g a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Sum
  • Functor (Tuple7 a b c d e f)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Profunctor p => Functor (Procompose p q a)Defined in profunctors-5.6.3 · Data.Profunctor.Composition
  • Profunctor p => Functor (Rift p q a)Defined in profunctors-5.6.3 · Data.Profunctor.Composition
  • Profunctor q => Functor (Ran p q a)Defined in profunctors-5.6.3 · Data.Profunctor.Ran
  • (Functor f, Bifunctor p) => Functor (Tannen f p a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Tannen
  • (Bifunctor p, Functor g) => Functor (Biff p f g a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Biff
classclass 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

return a >>= 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 List, Maybe and System.IO.IO defined in the Prelude satisfy these laws.

Methods

  • (>>=) :: m a -> (a -> m b) -> m binfixl 1

    Sequentially compose two actions, passing any value produced by the first as an argument to the second.

    'as >>= bs' can be understood as the do expression

    do a <- as
       bs a
    

    An alternative name for this function is 'bind', because it is used to introduce bindings in monadic contexts, but some people may refer to it as 'flatMap', which results from it being equivalent to

    \x f -> join (fmap f x) :: Monad m => m a -> (a -> m b) -> m b

    which can be seen as mapping a value with Monad m => m a -> m (m b) and then 'flattening' m (m b) to m b using join.

  • (>>) :: m a -> m b -> m binfixl 1

    Sequentially compose two actions, discarding any value produced by the first, like sequencing operators (such as the semicolon) in imperative languages.

    'as >> bs' can be understood as the do expression

    do as
       bs
    

    or in terms of (>>=) as

    as >>= const bs
  • return :: a -> m a

    Inject a value into the monadic type. This function should not be different from its default implementation as pure. The justification for the existence of this function is merely historic.

Instances163Monad, …
  • Monad GenDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Gen
  • Monad RoseDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Property
  • Monad IResultDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Monad ParserDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Monad ResultDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Monad GetDefined in asn1-encoding-0.9.6 · Data.ASN1.Get
  • Monad ComplexDefined in base-4.23.0.0 · Data.Complex
  • Monad FirstDefined in base-4.23.0.0 · Data.Semigroup
  • Monad LastDefined in base-4.23.0.0 · Data.Semigroup
  • Monad MaxDefined in base-4.23.0.0 · Data.Semigroup
  • Monad MinDefined in base-4.23.0.0 · Data.Semigroup
  • Monad Base16Defined in base16-1.0 · Data.Base16.Types.Internal
  • Monad GetDefined in binary-0.8.9.3 · Data.Binary.Get.Internal
  • Monad PutMDefined in binary-0.8.9.3 · Data.Binary.Put
  • Monad MarkupMDefined in blaze-markup-0.8.3.0 · Text.Blaze.Internal
  • Monad PutDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.Internal
  • Monad ParserDefined in cassava-0.5.4.1 · Data.Csv.Conversion
  • Monad PPDefined in cborg-0.2.10.0 · Codec.CBOR.Pretty
  • Monad GetDefined in cereal-0.5.8.3 · Data.Serialize.Get
  • Monad PutMDefined in cereal-0.5.8.3 · Data.Serialize.Put
  • Monad SeqDefined in containers-0.8 · Data.Sequence.Internal
  • Monad TreeDefined in containers-0.8 · Data.Tree
  • Monad CryptoFailableDefined in crypton-2.1.7 · Crypto.Error.Types
  • Monad GetDefined in crypton-asn1-encoding-0.10.0 · Data.ASN1.Get
  • Monad ParseASN1Defined in crypton-asn1-parse-0.10.0 · Data.ASN1.Parse
  • Monad ParserDefined in crypton-socks-0.6.2 · Network.Socks5.Parse
  • Monad DNonEmptyDefined in dlist-1.0 · Data.DList.DNonEmpty.Internal
  • Monad DListDefined in dlist-1.0 · Data.DList.Internal
  • Monad PutMEDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Monad StrictSinkDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Monad StrictSinkEDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Monad StrictSinkExplicitDefined in encoding-0.10.3 · Data.Encoding.ByteSink
  • Monad PprMDefined in ghc-boot-th-10.0.0.20260917 · GHC.Boot.TH.PprLib
  • Monad NonEmptyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.NonEmpty · orphan
  • Monad IdentityDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Identity
  • Monad FirstDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Monad LastDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Monad DownDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Ord
  • Monad DualDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad ProductDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad SumDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad NoIODefined in ghc-internal-10.0.0 · GHC.Internal.GHCi
  • Monad Par1Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad MaybeDefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad STMDefined in ghc-internal-10.0.0 · GHC.Internal.STM
  • Monad QDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Monad
  • Monad PDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadP
  • Monad ReadPDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadP
  • Monad ReadPrecDefined in ghc-internal-10.0.0 · GHC.Internal.Text.ParserCombinators.ReadPrec
  • Monad SoloDefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad IODefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad RootDefined in math-functions-0.3.4.4 · Numeric.RootFinding
  • Monad PackerDefined in memory-0.18.0 · Data.ByteArray.Pack.Internal
  • Monad ChunkDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Help.Chunk
  • Monad ComplResultDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Monad CompletionDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Monad PDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Monad ParserMDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Monad ParserResultDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Monad ReadMDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Monad ArrayDefined in primitive-0.9.1.0 · Data.Primitive.Array
  • Monad SmallArrayDefined in primitive-0.9.1.0 · Data.Primitive.SmallArray
  • Monad PackerDefined in ram-0.22.1 · Data.ByteArray.Pack.Internal
  • Monad ReqDefined in req-3.13.4 · Network.HTTP.Req
  • Monad ResultDefined in shakespeare-2.2.0 · Text.Hamlet.Parse
  • Monad STMDefined in stm-2.5.3.1 · Control.Sequential.STM
  • Monad ParserDefined in tasty-1.5.4 · Test.Tasty.Patterns.Parser
  • Monad CapabilityDefined in terminfo-0.4.1.7 · System.Console.Terminfo.Base
  • Monad HandshakeMDefined in tls-2.4.9 · Network.TLS.Handshake.State
  • Monad RecordMDefined in tls-2.4.9 · Network.TLS.Record.State
  • Monad TLSStDefined in tls-2.4.9 · Network.TLS.State
  • Monad VectorDefined in vector-0.13.2.0 · Data.Vector
  • Monad IdDefined in vector-0.13.2.0 · Data.Vector.Fusion.Util
  • Monad VectorDefined in vector-0.13.2.0 · Data.Vector.Strict
  • Monad BoxDefined in vector-stream-0.1.0.1 · Data.Stream.Monadic
  • Monad StreamDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Monad []Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • DRG gen => Monad (MonadPseudoRandom gen)Defined in crypton-2.1.7 · Crypto.Random.Types
  • Functor backend => Monad (Wizard backend)Defined in wizards-1.0.3 · System.Console.Wizard.Internal
  • Functor f => Monad (Free f)Defined in control-monad-free-0.6.2 · Control.Monad.Free
  • Monad ProxyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Proxy
  • Monad U1Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad (MkParser inp)Defined in appar-0.1.8 · Text.Appar.Parser
  • Monad (Parser i)Defined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
  • Monad (Base64 k)Defined in base64-1.0 · Data.Base64.Types.Internal
  • Monad (Decoder s)Defined in cborg-0.2.10.0 · Codec.CBOR.Decoding
  • Monad (IncrementalDecoder s)Defined in cborg-0.2.10.0 · Codec.CBOR.Read
  • Monad (State s)Defined in containers-0.8 · Utils.Containers.Internal.State
  • Monad (C mu)Defined in control-monad-free-0.6.2 · Control.Monad.Free.Improve
  • Monad (ST s)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Monad.ST.Lazy.Imp
  • Monad (Either e)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Either
  • Monad (ST s)Defined in ghc-internal-10.0.0 · GHC.Internal.ST
  • Monad (Parser byteArray)Defined in memory-0.18.0 · Data.ByteArray.Parse
  • Monad (UniqueParser s)Defined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.SimpleDocTree
  • Monad (Parser byteArray)Defined in ram-0.22.1 · Data.ByteArray.Parse
  • Monad (IParser t)Defined in text-2.1.4 · Data.Text.Internal.Read
  • Monad (PacketFlightM b)Defined in tls-2.4.9 · Network.TLS.IO
  • Monad f => Monad (Ap f)Defined in tasty-1.5.4 · Test.Tasty.Runners.Reducers
  • Monad m => Monad (PropertyM m)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Monadic
  • Monad m => Monad (ZeptoT m)Defined in attoparsec-0.14.4 · Data.Attoparsec.Zepto
  • Monad m => Monad (WrappedMonad m)Defined in base-4.23.0.0 · Control.Applicative
  • Monad m => Monad (CatchT m)Defined in exceptions-0.10.12 · Control.Monad.Catch.Pure
  • Monad m => Monad (DumbTerm m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.Backend.DumbTerm
  • Monad m => Monad (Draw m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.Backend.Terminfo
  • Monad m => Monad (CmdM m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.Command
  • Monad m => Monad (InputT m)Defined in haskeline-0.8.5.0 · System.Console.Haskeline.InputT
  • Monad m => Monad (HtmlT m)Defined in lucid-2.11.20260427 · Lucid.Base

    Basically acts like Writer.

  • Monad m => Monad (ListT m)Defined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Monad m => Monad (NondetT m)Defined in optparse-applicative-0.18.1.0 · Options.Applicative.Internal
  • Monad m => Monad (QuoteToQuasi m)Defined in th-compat-0.1.7 · Language.Haskell.TH.Syntax.Compat
  • Monad m => Monad (RecvHandshake13M m)Defined in tls-2.4.9 · Network.TLS.Handshake.Common13
  • Monad m => Monad (MaybeT m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Maybe
  • Monoid a => Monad (Tuple2 a)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Semigroup a => Monad (These a)Defined in strict-0.5.1 · Data.Strict.These
  • Semigroup a => Monad (These a)Defined in these-1.2.1 · Data.These
  • ArrowApply a => Monad (ArrowMonad a)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Arrow
  • Monad (Tagged s)Defined in tagged-0.8.11 · Data.Tagged
  • Monad (bi a) => Monad (Biap bi a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Biap
  • Monad (t m) => Monad (LiftingAccum t m)Defined in mtl-2.3.2 · Control.Monad.Accum
  • Monad (t m) => Monad (LiftingSelect t m)Defined in mtl-2.3.2 · Control.Monad.Select
  • Monad f => Monad (Ap f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Monad f => Monad (Alt f)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Monad f => Monad (Rec1 f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad m => Monad (Reader r m)Defined in basement-0.0.16 · Basement.Compat.MonadTrans
  • Monad m => Monad (State r m)Defined in basement-0.0.16 · Basement.Compat.MonadTrans
  • Monad m => Monad (Kleisli m a)Defined in ghc-internal-10.0.0 · GHC.Internal.Control.Arrow
  • Monad m => Monad (StateT s m)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Utils
  • Monad m => Monad (StateT s m)Defined in microlens-0.5.0.0 · Lens.Micro
  • Monad m => Monad (ExceptT e m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Except
  • Monad m => Monad (IdentityT m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Identity
  • Monad m => Monad (ReaderT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Reader
  • Monad m => Monad (SelectT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Select
  • Monad m => Monad (StateT s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.State.Lazy
  • Monad m => Monad (StateT s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.State.Strict
  • Monad m => Monad (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.CPS
  • Monad m => Monad (Reverse m)Defined in transformers-0.6.3.0 · Data.Functor.Reverse

    Derived instance.

  • Monoid output => Monad (StackMachine output style)Defined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.StackMachine
  • (Applicative f, Monad f) => Monad (WhenMissing f x)Defined in containers-0.8 · Data.IntMap.Internal

    Equivalent to ReaderT k (ReaderT x (MaybeT f)).

  • (Functor f, Monad m) => Monad (FreeT f m)Defined in control-monad-free-0.6.2 · Control.Monad.Free
  • (Monad (Rep p), Representable p) => Monad (Prep p)Defined in profunctors-5.6.3 · Data.Profunctor.Rep
  • (Monoid a, Monoid b) => Monad (Tuple3 a b)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • (Monoid w, Functor m, Monad m) => Monad (AccumT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Accum
  • (Monoid w, Monad m) => Monad (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Lazy
  • (Monoid w, Monad m) => Monad (WriterT w m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Strict
  • Monad (Cokleisli w a)Defined in comonad-5.0.10 · Control.Comonad
  • Monad (ParsecT s u m)Defined in parsec-3.1.18.0 · Text.Parsec.Prim
  • Monad (Costar f a)Defined in profunctors-5.6.3 · Data.Profunctor.Types
  • Monad (ContT r m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Cont
  • Monad ((->) r)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad (f (g m)) => Monad (ComposeT f g m)Defined in mmorph-1.2.2 · Control.Monad.Trans.Compose
  • Monad f => Monad (Star f a)Defined in profunctors-5.6.3 · Data.Profunctor.Types
  • Stream s => Monad (ParsecT e s m)Defined in megaparsec-9.5.0 · Text.Megaparsec.Internal

    return returns a parser that succeeds without consuming input.

  • (Applicative f, Monad f) => Monad (WhenMissing f k x)Defined in containers-0.8 · Data.Map.Internal

    Equivalent to ReaderT k (ReaderT x (MaybeT f)) .

  • (Monad f, Applicative f) => Monad (WhenMatched f x y)Defined in containers-0.8 · Data.IntMap.Internal

    Equivalent to ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))

  • (Monad f, Monad g) => Monad (Product f g)Defined in base-4.23.0.0 · Data.Functor.Product
  • (Monad f, Monad g) => Monad (f :*: g)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • (Monoid a, Monoid b, Monoid c) => Monad (Tuple4 a b c)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Monad f => Monad (M1 i c f)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Monad m => Monad (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.CPS
  • (Monad f, Applicative f) => Monad (WhenMatched f k x y)Defined in containers-0.8 · Data.Map.Internal

    Equivalent to ReaderT k (ReaderT x (ReaderT y (MaybeT f)))

  • (Monoid w, Monad m) => Monad (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.Lazy
  • (Monoid w, Monad m) => Monad (RWST r w s m)Defined in transformers-0.6.3.0 · Control.Monad.Trans.RWS.Strict
  • Monad state => Monad (Builder collection mutCollection step state err)Defined in basement-0.0.16 · Basement.MutableBuilder
classclass (Alternative m, Monad m) => MonadPlus (m :: Type -> Type) where
#

Monads that also support choice and failure.

Methods

  • mzero :: m a

    The identity of mplus. It should also satisfy the equations

    mzero >>= f  =  mzero
    v >> mzero   =  mzero

    The default definition is

    mzero = empty
    
  • mplus :: m a -> m a -> m a

    An associative operation. The default definition is

    mplus = (<|>)
    
Instances70MonadPlus, …
classclass Eq a => Ord a where
#

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

, then

x <= z

=

True

Reflexivity

x <= x

=

True

Antisymmetry

if

x <= y && y <= x

=

True

, then

x == y

=

True

The following operator interactions are expected to hold:

  1. x >= y = y <= x

  2. x < y = x <= y && x /= y

  3. x > y = y < x

  4. x < y = compare x y == LT

  5. x > y = compare x y == GT

  6. x == y = compare x y == EQ

  7. min x y == if x <= y then x else y = True

  8. max 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 (==). Users who expect a stronger guarantee are advised to write their own min and/or max functions.

The nuance of the above distinction is not always fully internalized by developers, and in the past (tracing back to the Haskell 1.4 Report) the specification for Ord asserted the stronger property that (min x y, max x y) = (x, y) or (y, x), or in other words, that min and max will return one of their arguments, using argument order as the tie-breaker if the arguments are equal by comparison. A few list and Foldable functions have behavior that is best understood with this assumption in mind: all variations of minimumBy and maximumBy (which can't use min and max in their implementations) are written such that minimumBy compare and maximumBy compare are respectively equivalent to minimum and maximum (which do use min and max) only if min and max adhere to this tie-breaking convention. Otherwise, if there are multiple least or largest elements in a container, minimum and maximum may not return the same one that minimumBy compare and maximumBy compare do (though they should return something that is equal). (This is relevant for types with non-extensional equality, like Arg, but also in cases where the precise reference held matters for memory-management reasons.) Unless there is a reason to deviate, it is less confusing for implementors of Ord to respect this same convention (as the default definitions of min and max do).

Minimal complete definition: either compare or <=. Using compare can be more efficient for complex types.

Methods

Instances727Ord, …
  • Ord LineRangeDefined in Diff-2.0.1 · Data.Algorithm.DiffOutput
  • Ord ASCIIStringDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord PrintableStringDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord UnicodeStringDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord OrdADefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Poly
  • Ord OrdBDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Poly
  • Ord OrdCDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Poly
  • Ord KeyDefined in aeson-2.2.5.1 · Data.Aeson.Key
  • Ord ArityDefined in aeson-2.2.5.1 · Data.Aeson.TH
  • Ord DotNetTimeDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Ord JSONPathElementDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal
  • Ord ValueDefined in aeson-2.2.5.1 · Data.Aeson.Types.Internal

    The ordering is total, consistent with Eq instance. However, nothing else about the ordering is specified, and it may change from environment to environment and version to version of either this package or its dependencies (hashable and 'unordered-containers').

  • Ord BlinkSpeedDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
  • Ord ColorDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
  • Ord ColorIntensityDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
  • Ord ConsoleIntensityDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
  • Ord ConsoleLayerDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
  • Ord UnderliningDefined in ansi-terminal-types-1.1.3 · System.Console.ANSI.Types
  • Ord ASN1TimeTypeDefined in asn1-types-0.3.4 · Data.ASN1.Types
  • Ord ASN1ClassDefined in asn1-types-0.3.4 · Data.ASN1.Types.Lowlevel
  • Ord ASN1CharacterStringDefined in asn1-types-0.3.4 · Data.ASN1.Types.String
  • Ord ASN1StringEncodingDefined in asn1-types-0.3.4 · Data.ASN1.Types.String
  • Ord PosDefined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
  • Ord NumberDefined in attoparsec-0.14.4 · Data.Attoparsec.Number
  • Ord CredentialDefined in authenticate-oauth-1.7 · Web.Authenticate.OAuth
  • Ord OAuthVersionDefined in authenticate-oauth-1.7 · Web.Authenticate.OAuth
  • Ord ByteArrayDefined in base-4.23.0.0 · Data.Array.Byte

    Non-lexicographic ordering. This compares the lengths of the byte arrays first and uses a lexicographic ordering if the lengths are equal. Subject to change between major versions.

  • Ord EncodingDefined in basement-0.0.16 · Basement.String
  • Ord UTF32_InvalidDefined in basement-0.0.16 · Basement.String.Encoding.UTF32
  • Ord AsciiStringDefined in basement-0.0.16 · Basement.Types.AsciiString
  • Ord Char7Defined in basement-0.0.16 · Basement.Types.Char7
  • Ord FileSizeDefined in basement-0.0.16 · Basement.Types.OffsetSize
  • Ord AddrDefined in basement-0.0.16 · Basement.Types.Ptr
  • Ord Word128Defined in basement-0.0.16 · Basement.Types.Word128
  • Ord Word256Defined in basement-0.0.16 · Basement.Types.Word256
  • Ord StringDefined in basement-0.0.16 · Basement.UTF8.Base
  • Ord OptionsDefined in bifunctors-5.6.3 · Data.Bifunctor.TH
  • Ord ByteOrderDefined in byteorder-1.0.4 · System.ByteOrder
  • Ord ByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Internal.Type
  • Ord ByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Lazy.Internal
  • Ord ShortByteStringDefined in bytestring-0.12.2.0 · Data.ByteString.Short.Internal

    Lexicographic order.

  • Ord ConversionErrorDefined in cassava-megaparsec-2.1.1 · Data.Csv.Parser.Megaparsec.Internals
  • Ord ByteArrayDefined in cborg-0.2.10.0 · Codec.CBOR.ByteArray
  • Ord SlicedByteArrayDefined in cborg-0.2.10.0 · Codec.CBOR.ByteArray.Sliced
  • Ord TokenTypeDefined in cborg-0.2.10.0 · Codec.CBOR.Decoding
  • Ord TermTokenDefined in cborg-0.2.10.0 · Codec.CBOR.FlatTerm
  • Ord TermDefined in cborg-0.2.10.0 · Codec.CBOR.Term
  • Ord TimeSpecDefined in clock-0.8.4 · System.Clock
  • Ord SecondsDefined in clock-0.8.4 · System.Clock.Seconds
  • Ord CompleteDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Complete
  • Ord HelpFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Help
  • Ord FlagInfoDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Explicit.Type
  • Ord AnnDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Implicit.Ann
  • Ord CmdArgsPrivateDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Implicit.Type
  • Ord TextFormatDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Text
  • Ord VerbosityDefined in cmdargs-0.10.22 · System.Console.CmdArgs.Verbosity
  • Ord IntSetDefined in containers-0.8 · Data.IntSet.Internal
  • Ord IntersectionDefined in containers-0.8 · Data.IntSet.Internal
  • Ord CipherErrorDefined in crypto-api-0.13.3 · Crypto.Classes.Exceptions
  • Ord GenErrorDefined in crypto-api-0.13.3 · Crypto.Random
  • Ord ReseedInfoDefined in crypto-api-0.13.3 · Crypto.Random
  • Ord BlockCipherErrorDefined in crypto-api-0.13.3 · Crypto.Types
  • Ord PrivateNumberDefined in crypto-pubkey-types-0.4.3 · Crypto.Types.PubKey.DH
  • Ord PublicNumberDefined in crypto-pubkey-types-0.4.3 · Crypto.Types.PubKey.DH
  • Ord SharedKeyDefined in crypto-pubkey-types-0.4.3 · Crypto.Types.PubKey.DH
  • Ord CurveNameDefined in crypto-pubkey-types-0.4.3 · Crypto.Types.PubKey.ECC
  • Ord OptionsDefined in crypton-2.1.7 · Crypto.KDF.Argon2
  • Ord VariantDefined in crypton-2.1.7 · Crypto.KDF.Argon2
  • Ord VersionDefined in crypton-2.1.7 · Crypto.KDF.Argon2
  • Ord ParametersDefined in crypton-2.1.7 · Crypto.KDF.BCryptPBKDF
  • Ord PrivateNumberDefined in crypton-2.1.7 · Crypto.PubKey.DH
  • Ord PublicNumberDefined in crypton-2.1.7 · Crypto.PubKey.DH
  • Ord CurveNameDefined in crypton-2.1.7 · Crypto.PubKey.ECC.Types
  • Ord ASN1TimeTypeDefined in crypton-asn1-types-0.4.1 · Data.ASN1.Types
  • Ord ASN1ClassDefined in crypton-asn1-types-0.4.1 · Data.ASN1.Types.Lowlevel
  • Ord ASN1CharacterStringDefined in crypton-asn1-types-0.4.1 · Data.ASN1.Types.String
  • Ord ASN1StringEncodingDefined in crypton-asn1-types-0.4.1 · Data.ASN1.Types.String
  • Ord ConnectDefined in crypton-socks-0.6.2 · Network.Socks5.Command
  • Ord SocksAddressDefined in crypton-socks-0.6.2 · Network.Socks5.Types
  • Ord SocksCommandDefined in crypton-socks-0.6.2 · Network.Socks5.Types
  • Ord SocksErrorDefined in crypton-socks-0.6.2 · Network.Socks5.Types
  • Ord SocksHostAddressDefined in crypton-socks-0.6.2 · Network.Socks5.Types
  • Ord SocksMethodDefined in crypton-socks-0.6.2 · Network.Socks5.Types
  • Ord SocksReplyDefined in crypton-socks-0.6.2 · Network.Socks5.Types
  • Ord SocksVersionDefined in crypton-socks-0.6.2 · Network.Socks5.Types
  • Ord DistinguishedNameDefined in crypton-x509-1.9.2 · Data.X509.DistinguishedName
  • Ord AltNameDefined in crypton-x509-1.9.2 · Data.X509.Ext
  • Ord ExtKeyUsageFlagDefined in crypton-x509-1.9.2 · Data.X509.Ext
  • Ord ExtKeyUsagePurposeDefined in crypton-x509-1.9.2 · Data.X509.Ext
  • Ord ExtSubjectAltNameDefined in crypton-x509-1.9.2 · Data.X509.Ext
  • Ord ReasonFlagDefined in crypton-x509-1.9.2 · Data.X509.Ext
  • Ord FileTypeDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Ord PermissionsDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Ord XdgDirectoryDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Ord XdgDirectoryListDefined in directory-1.3.11.0 · System.Directory.Internal.Common
  • Ord BackgroundDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord Color8Defined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord FontDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord ForegroundDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord ShapeDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord StrikeoutDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord StyleReqDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord UnderlineDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord WeightDefined in doclayout-0.6 · Text.DocLayout.ANSIFont
  • Ord ECHConfigDefined in ech-config-0.0.1 · Network.TLS.ECH.Config
  • Ord ECHConfigContentsDefined in ech-config-0.0.1 · Network.TLS.ECH.Config
  • Ord ECHConfigExtensionDefined in ech-config-0.0.1 · Network.TLS.ECH.Config
  • Ord EncodedServerPublicKeyDefined in ech-config-0.0.1 · Network.TLS.ECH.Config
  • Ord HpkeKeyConfigDefined in ech-config-0.0.1 · Network.TLS.ECH.Config
  • Ord HpkeSymmetricCipherSuiteDefined in ech-config-0.0.1 · Network.TLS.ECH.Config
  • Ord DecodingExceptionDefined in encoding-0.10.3 · Data.Encoding.Exception
  • Ord EncodingExceptionDefined in encoding-0.10.3 · Data.Encoding.Exception
  • Ord VoidDefined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Ord BigNatDefined in ghc-internal-10.0.0 · GHC.Internal.Bignum.BigNat
  • Ord IntegerDefined in ghc-internal-10.0.0 · GHC.Internal.Bignum.Integer
  • Ord NaturalDefined in ghc-internal-10.0.0 · GHC.Internal.Bignum.Natural
  • Ord ByteOrderDefined in ghc-internal-10.0.0 · GHC.Internal.ByteOrder
  • Ord ClosureTypeDefined in ghc-internal-10.0.0 · GHC.Internal.ClosureTypes
  • Ord BlockReasonDefined in ghc-internal-10.0.0 · GHC.Internal.Conc.Sync
  • Ord ThreadIdDefined in ghc-internal-10.0.0 · GHC.Internal.Conc.Sync
  • Ord ThreadStatusDefined in ghc-internal-10.0.0 · GHC.Internal.Conc.Sync
  • Ord AllDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Ord AnyDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Ord SomeTypeRepDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Typeable.Internal
  • Ord UniqueDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Unique
  • Ord VersionDefined in ghc-internal-10.0.0 · GHC.Internal.Data.Version
  • Ord TimeoutKeyDefined in ghc-internal-10.0.0 · GHC.Internal.Event.TimeOut
  • Ord UniqueDefined in ghc-internal-10.0.0 · GHC.Internal.Event.Unique
  • Ord ErrorCallDefined in ghc-internal-10.0.0 · GHC.Internal.Exception
  • Ord ArithExceptionDefined in ghc-internal-10.0.0 · GHC.Internal.Exception.Type
  • Ord FingerprintDefined in ghc-internal-10.0.0 · GHC.Internal.Fingerprint.Type
  • Ord CBoolDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CCharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CClockDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CDoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CFloatDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CIntDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CIntMaxDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CIntPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CLLongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CLongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CPtrdiffDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CSCharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CSUSecondsDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CShortDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CSigAtomicDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CSizeDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CTimeDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CUCharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CUIntDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CUIntMaxDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CUIntPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CULLongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CULongDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CUSecondsDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CUShortDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord CWcharDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.Types
  • Ord IntPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.Ptr
  • Ord WordPtrDefined in ghc-internal-10.0.0 · GHC.Internal.Foreign.Ptr
  • Ord AssociativityDefined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord DecidedStrictnessDefined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord FixityDefined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord SourceStrictnessDefined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord SourceUnpackednessDefined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord PrimTypeDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Ord TsoFlagsDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Ord WhatNextDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Ord WhyBlockedDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.Closures
  • Ord HalfWordDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.InfoTable.Types
  • Ord CostCentreDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ProfInfo.Types
  • Ord CostCentreStackDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ProfInfo.Types
  • Ord IndexTableDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ProfInfo.Types
  • Ord StgTSOProfInfoDefined in ghc-internal-10.0.0 · GHC.Internal.Heap.ProfInfo.Types
  • Ord SeekModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Device
  • Ord ArrayExceptionDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Exception
  • Ord AsyncExceptionDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Exception
  • Ord ExitCodeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Exception
  • Ord BufferModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Handle.Types
  • Ord NewlineDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Handle.Types
  • Ord NewlineModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Handle.Types
  • Ord IOModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.IOMode
  • Ord Int16Defined in ghc-internal-10.0.0 · GHC.Internal.Int
  • Ord Int32Defined in ghc-internal-10.0.0 · GHC.Internal.Int
  • Ord Int64Defined in ghc-internal-10.0.0 · GHC.Internal.Int
  • Ord Int8Defined in ghc-internal-10.0.0 · GHC.Internal.Int
  • Ord ExtensionDefined in ghc-internal-10.0.0 · GHC.Internal.LanguageExtensions
  • Ord ByteOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.Constants
  • Ord WordOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.Constants
  • Ord ByteOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.ConstantsProf
  • Ord WordOffsetDefined in ghc-internal-10.0.0 · GHC.Internal.Stack.ConstantsProf
  • Ord CBlkCntDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CBlkSizeDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CCcDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CClockIdDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CDevDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CFsBlkCntDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CFsFilCntDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CGidDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CIdDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CInoDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CKeyDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CModeDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CNfdsDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CNlinkDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord COffDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CPidDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CRLimDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CSocklenDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CSpeedDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CSsizeDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CTcflagDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CTimerDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord CUidDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord FdDefined in ghc-internal-10.0.0 · GHC.Internal.System.Posix.Types
  • Ord AnnLookupDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord AnnTargetDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord BangDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord BndrVisDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord BodyDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord BytesDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord CallconvDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord ClauseDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord ConDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord DecDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord DecidedStrictnessDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord DerivClauseDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord DerivStrategyDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord DocLocDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord ExpDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord FamilyResultSigDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord FixityDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord FixityDirectionDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord ForeignDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord FunDepDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord GuardDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord InfoDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord InjectivityAnnDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord InlineDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord LitDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord LocDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord MatchDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord ModNameDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord ModuleDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord ModuleInfoDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord NameDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord NameFlavourDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord NameSpaceDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord NamespaceSpecifierDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord OccNameDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord OverlapDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord PatDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord PatSynArgsDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord PatSynDirDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord PhasesDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord PkgNameDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord PragmaDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord RangeDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord RoleDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord RuleBndrDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord RuleMatchDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord SafetyDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord SourceStrictnessDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord SourceUnpackednessDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord SpecificityDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord StmtDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord TyLitDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord TySynEqnDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord TypeDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord TypeFamilyHeadDefined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord SomeCharDefined in ghc-internal-10.0.0 · GHC.Internal.TypeLits
  • Ord SomeSymbolDefined in ghc-internal-10.0.0 · GHC.Internal.TypeLits
  • Ord SomeNatDefined in ghc-internal-10.0.0 · GHC.Internal.TypeNats
  • Ord BoolDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord CharDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord DoubleDefined in ghc-internal-10.0.0 · GHC.Internal.Classes

    IEEE 754 Double-precision type includes not only numbers, but also positive and negative infinities and a special element called NaN (which can be quiet or signal).

    IEEE 754-2008, section 5.11 requires that if at least one of arguments of <=, <, >, >= is NaN then the result of the comparison is False, and instance Ord Double complies with this requirement. This violates the reflexivity: both NaN <= NaN and NaN >= NaN are False.

    IEEE 754-2008, section 5.10 defines totalOrder predicate. Unfortunately, compare on Doubles violates the IEEE standard and does not define a total order. More specifically, both compare NaN x and compare x NaN always return GT.

    Thus, users must be extremely cautious when using instance Ord Double. For instance, one should avoid ordered containers with keys represented by Double, because data loss and corruption may happen. An IEEE-compliant compare is available in fp-ieee package as TotallyOrdered newtype.

    Moving further, the behaviour of min and max with regards to NaN is also non-compliant. IEEE 754-2008, section 5.3.1 defines that quiet NaN should be treated as a missing data by minNum and maxNum functions, for example, minNum(NaN, 1) = minNum(1, NaN) = 1. Some languages such as Java deviate from the standard implementing minNum(NaN, 1) = minNum(1, NaN) = NaN. However, min / max in base are even worse: min NaN 1 is 1, but min 1 NaN is NaN.

    IEEE 754-2008 compliant min / max can be found in ieee754 package under minNum / maxNum names. Implementations compliant with minimumNumber / maximumNumber from a newer IEEE 754-2019, section 9.6 are available from fp-ieee package.

  • Ord FloatDefined in ghc-internal-10.0.0 · GHC.Internal.Classes

    See instance Ord Double for discussion of deviations from IEEE 754 standard.

  • Ord IntDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord OrderingDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord TyConDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord WordDefined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord GeneralCategoryDefined in ghc-internal-10.0.0 · GHC.Internal.Unicode
  • Ord Word16Defined in ghc-internal-10.0.0 · GHC.Internal.Word
  • Ord Word32Defined in ghc-internal-10.0.0 · GHC.Internal.Word
  • Ord Word64Defined in ghc-internal-10.0.0 · GHC.Internal.Word
  • Ord Word8Defined in ghc-internal-10.0.0 · GHC.Internal.Word
  • Ord HalfDefined in half-0.3.3 · Numeric.Half.Internal
  • Ord CompletionDefined in haskeline-0.8.5.0 · System.Console.Haskeline.Completion
  • Ord BaseKeyDefined in haskeline-0.8.5.0 · System.Console.Haskeline.Key
  • Ord KeyDefined in haskeline-0.8.5.0 · System.Console.Haskeline.Key
  • Ord ModifierDefined in haskeline-0.8.5.0 · System.Console.Haskeline.Key
  • Ord RowClassDefined in hledger-1.52.4 · Hledger.Cli.Commands.Balance
  • Ord CheckDefined in hledger-1.52.4 · Hledger.Cli.Commands.Check
  • Ord BalancingOptsDefined in hledger-lib-1.52.4 · Hledger.Data.Balancing
  • Ord DayPartitionDefined in hledger-lib-1.52.4 · Hledger.Data.DayPartition
  • Ord TransactionBalancingPrecisionDefined in hledger-lib-1.52.4 · Hledger.Data.Transaction
  • Ord AccountAliasDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord AccountTypeDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord AmountDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord AmountCostDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord AmountPrecisionDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord AmountStyleDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord CostBasisDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord DateSpanDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord DigitGroupStyleDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord EFDayDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord IntervalDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord MarketPriceDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord MixedAmountDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord MixedAmountKeyDefined in hledger-lib-1.52.4 · Hledger.Data.Types

    We don't auto-derive the Ord instance because it would give an undesired ordering. We want the keys to be sorted lexicographically: (1) By the primary commodity of the amount. (2) By the commodity of the cost, with no cost being first. (3) By the unit cost, from most negative to most positive, with total costs before unit costs. For example, we would like the ordering to give MixedAmountKeyNoCost X < MixedAmountKeyTotalCost X Z < MixedAmountKeyNoCost Y

  • Ord PeriodDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord PriceDirectiveDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord RoundingDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord SepFormatDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord SideDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord StatusDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord StorageFormatDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord TimeclockCodeDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord TimeclockEntryDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord InputOptsDefined in hledger-lib-1.52.4 · Hledger.Read.InputOptions
  • Ord DisplayNameDefined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • Ord GhcDebugModeDefined in hledger-lib-1.52.4 · Hledger.Utils.Debug
  • Ord HledgerParseErrorDataDefined in hledger-lib-1.52.4 · Hledger.Utils.Parse
  • Ord RegexpDefined in hledger-lib-1.52.4 · Hledger.Utils.Regex
  • Ord DataStyleDefined in hledger-lib-1.52.4 · Hledger.Write.Ods
  • Ord EmphasisDefined in hledger-lib-1.52.4 · Hledger.Write.Spreadsheet
  • Ord NumLinesDefined in hledger-lib-1.52.4 · Hledger.Write.Spreadsheet
  • Ord StyleDefined in hledger-lib-1.52.4 · Hledger.Write.Spreadsheet
  • Ord TypeDefined in hledger-lib-1.52.4 · Hledger.Write.Spreadsheet
  • Ord DurationDefined in hourglass-0.2.12 · Data.Hourglass.Diff
  • Ord PeriodDefined in hourglass-0.2.12 · Data.Hourglass.Diff
  • Ord TimezoneMinutesDefined in hourglass-0.2.12 · Data.Hourglass.Zone
  • Ord UTCDefined in hourglass-0.2.12 · Data.Hourglass.Zone
  • Ord DateDefined in hourglass-0.2.12 · Time.Types
  • Ord DateTimeDefined in hourglass-0.2.12 · Time.Types
  • Ord ElapsedDefined in hourglass-0.2.12 · Time.Types
  • Ord ElapsedPDefined in hourglass-0.2.12 · Time.Types
  • Ord HoursDefined in hourglass-0.2.12 · Time.Types
  • Ord MinutesDefined in hourglass-0.2.12 · Time.Types
  • Ord MonthDefined in hourglass-0.2.12 · Time.Types
  • Ord NanoSecondsDefined in hourglass-0.2.12 · Time.Types
  • Ord SecondsDefined in hourglass-0.2.12 · Time.Types
  • Ord TimeOfDayDefined in hourglass-0.2.12 · Time.Types
  • Ord TimezoneOffsetDefined in hourglass-0.2.12 · Time.Types
  • Ord WeekDayDefined in hourglass-0.2.12 · Time.Types
  • Ord ConnHostDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord ConnKeyDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord MaxHeaderLengthDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord MaxNumberHeadersDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord ProxyDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord ProxySecureModeDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord StatusHeadersDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord StreamFileStatusDefined in http-client-0.7.19 · Network.HTTP.Client.Types
  • Ord DigestAuthExceptionDetailsDefined in http-client-tls-0.4.0 · Network.HTTP.Client.TLS
  • Ord ByteRangeDefined in http-types-0.12.6 · Network.HTTP.Types.Header
  • Ord StdMethodDefined in http-types-0.12.6 · Network.HTTP.Types.Method
  • Ord StatusDefined in http-types-0.12.6 · Network.HTTP.Types.Status

    Statuses are ordered according to their status codes only.

  • Ord EscapeItemDefined in http-types-0.12.6 · Network.HTTP.Types.URI
  • Ord HttpVersionDefined in http-types-0.12.6 · Network.HTTP.Types.Version
  • Ord IPDefined in iproute-1.7.15 · Data.IP.Addr
  • Ord IPv4Defined in iproute-1.7.15 · Data.IP.Addr
  • Ord IPv6Defined in iproute-1.7.15 · Data.IP.Addr
  • Ord IPRangeDefined in iproute-1.7.15 · Data.IP.Range
  • Ord PosDefined in megaparsec-9.5.0 · Text.Megaparsec.Pos
  • Ord SourcePosDefined in megaparsec-9.5.0 · Text.Megaparsec.Pos
  • Ord BytesDefined in memory-0.18.0 · Data.ByteArray.Bytes
  • Ord ScrubbedBytesDefined in memory-0.18.0 · Data.ByteArray.ScrubbedBytes
  • Ord FnvHash32Defined in memory-0.18.0 · Data.Memory.Hash.FNV
  • Ord FnvHash64Defined in memory-0.18.0 · Data.Memory.Hash.FNV
  • Ord SipHashDefined in memory-0.18.0 · Data.Memory.Hash.SipHash
  • Ord DefNameDefined in microlens-th-0.4.3.18 · Lens.Micro.TH
  • Ord AuthorityDefined in modern-uri-0.3.6.1 · Text.URI.Types
  • Ord QueryParamDefined in modern-uri-0.3.6.1 · Text.URI.Types
  • Ord RTextExceptionDefined in modern-uri-0.3.6.1 · Text.URI.Types
  • Ord RTextLabelDefined in modern-uri-0.3.6.1 · Text.URI.Types
  • Ord URIDefined in modern-uri-0.3.6.1 · Text.URI.Types
  • Ord UserInfoDefined in modern-uri-0.3.6.1 · Text.URI.Types
  • Ord MsgFlagDefined in network-3.2.9.0 · Network.Socket.Flag
  • Ord SocketTimeoutDefined in network-3.2.9.0 · Network.Socket.Options
  • Ord StructLingerDefined in network-3.2.9.0 · Network.Socket.Options
  • Ord FamilyDefined in network-3.2.9.0 · Network.Socket.Types
  • Ord PortNumberDefined in network-3.2.9.0 · Network.Socket.Types
  • Ord SockAddrDefined in network-3.2.9.0 · Network.Socket.Types
  • Ord SocketTypeDefined in network-3.2.9.0 · Network.Socket.Types
  • Ord URIDefined in network-uri-2.6.4.2 · Network.URI
  • Ord URIAuthDefined in network-uri-2.6.4.2 · Network.URI
  • Ord RichnessDefined in optparse-applicative-0.18.1.0 · Options.Applicative.BashCompletion
  • Ord ParentheticDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Help.Core
  • Ord ArgPolicyDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Ord OptNameDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Ord OptVisibilityDefined in optparse-applicative-0.18.1.0 · Options.Applicative.Types
  • Ord OsCharDefined in os-string-2.0.11 · System.OsString.Internal.Types

    Byte ordering of the internal representation.

  • Ord OsStringDefined in os-string-2.0.11 · System.OsString.Internal.Types

    Byte ordering of the internal representation.

  • Ord PosixCharDefined in os-string-2.0.11 · System.OsString.Internal.Types
  • Ord PosixStringDefined in os-string-2.0.11 · System.OsString.Internal.Types
  • Ord WindowsCharDefined in os-string-2.0.11 · System.OsString.Internal.Types
  • Ord WindowsStringDefined in os-string-2.0.11 · System.OsString.Internal.Types
  • Ord MessageDefined in parsec-3.1.18.0 · Text.Parsec.Error
  • Ord SourcePosDefined in parsec-3.1.18.0 · Text.Parsec.Pos
  • Ord PrettyLevelDefined in pretty-1.1.3.6 · Text.PrettyPrint.Annotated.HughesPJClass
  • Ord PrettyLevelDefined in pretty-1.1.3.6 · Text.PrettyPrint.HughesPJClass
  • Ord FusionDepthDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Ord LayoutOptionsDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Ord PageWidthDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Ord AnsiStyleDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
  • Ord BoldDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
  • Ord ColorDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
  • Ord IntensityDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
  • Ord ItalicizedDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
  • Ord LayerDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
  • Ord UnderlinedDefined in prettyprinter-ansi-terminal-1.1.4 · Prettyprinter.Render.Terminal.Internal
  • Ord CommunicationHandleDefined in process-1.6.30.0 · System.Process.CommunicationHandle.Internal
  • Ord BytesDefined in ram-0.22.1 · Data.ByteArray.Bytes
  • Ord ScrubbedBytesDefined in ram-0.22.1 · Data.ByteArray.ScrubbedBytes
  • Ord FnvHash32Defined in ram-0.22.1 · Data.Memory.Hash.FNV
  • Ord FnvHash64Defined in ram-0.22.1 · Data.Memory.Hash.FNV
  • Ord SipHashDefined in ram-0.22.1 · Data.Memory.Hash.SipHash
  • Ord CardinalityDefined in random-1.3.1 · System.Random.GFinite
  • Ord DoPaDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Common
  • Ord WhichTestDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Common
  • Ord PatternSetCharacterClassDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Pattern
  • Ord PatternSetCollatingElementDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Pattern
  • Ord PatternSetEquivalenceClassDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Pattern
  • Ord SchemeDefined in req-3.13.4 · Network.HTTP.Req
  • Ord ScientificDefined in scientific-0.3.9.0 · Data.Scientific

    Scientific numbers can be safely compared for ordering. No magnitude 10^e is calculated so there's no risk of a blowup in space or time when comparing scientific numbers coming from untrusted sources.

  • Ord AbsoluteSizeDefined in shakespeare-2.2.0 · Text.Internal.CssCommon
  • Ord EmSizeDefined in shakespeare-2.2.0 · Text.Internal.CssCommon
  • Ord ExSizeDefined in shakespeare-2.2.0 · Text.Internal.CssCommon
  • Ord PercentageSizeDefined in shakespeare-2.2.0 · Text.Internal.CssCommon
  • Ord PixelSizeDefined in shakespeare-2.2.0 · Text.Internal.CssCommon
  • Ord VarTypeDefined in shakespeare-2.2.0 · Text.Shakespeare
  • Ord DerefDefined in shakespeare-2.2.0 · Text.Shakespeare.Base
  • Ord IdentDefined in shakespeare-2.2.0 · Text.Shakespeare.Base
  • Ord FileTypeDefined in streaming-commons-0.2.3.1 · Data.Streaming.Filesystem
  • Ord HostPreferenceDefined in streaming-commons-0.2.3.1 · Data.Streaming.Network.Internal
  • Ord StrategyDefined in streaming-commons-0.2.3.1 · Data.Streaming.Zlib.Lowlevel
  • Ord HideSuccessesDefined in tasty-1.5.4 · Test.Tasty.Ingredients.ConsoleReporter
  • Ord MinDurationToReportDefined in tasty-1.5.4 · Test.Tasty.Ingredients.ConsoleReporter
  • Ord QuietDefined in tasty-1.5.4 · Test.Tasty.Ingredients.ConsoleReporter
  • Ord UseColorDefined in tasty-1.5.4 · Test.Tasty.Ingredients.ConsoleReporter
  • Ord ListTestsDefined in tasty-1.5.4 · Test.Tasty.Ingredients.ListTests
  • Ord HideProgressDefined in tasty-1.5.4 · Test.Tasty.Options.Core
  • Ord NumThreadsDefined in tasty-1.5.4 · Test.Tasty.Options.Core
  • Ord TimeoutDefined in tasty-1.5.4 · Test.Tasty.Options.Core

    Auto-derived instance, just to allow storing in a Data.Map.Map and such.

  • Ord ColorDefined in terminfo-0.4.1.7 · System.Console.Terminfo.Color
  • Ord I8Defined in text-2.1.4 · Data.Text.Foreign
  • Ord TextDefined in text-2.1.4 · Data.Text · orphan
  • Ord BuilderDefined in text-2.1.4 · Data.Text.Internal.Builder
  • Ord TextDefined in text-2.1.4 · Data.Text.Lazy · orphan
  • Ord BuilderDefined in text-builder-linear-0.1.4 · Data.Text.Builder.Linear
  • Ord BDefined in text-short-0.1.6.1 · Data.Text.Short.Internal
  • Ord ShortTextDefined in text-short-0.1.6.1 · Data.Text.Short.Internal
  • Ord ConstructorVariantDefined in th-abstraction-0.7.2.0 · Language.Haskell.TH.Datatype
  • Ord DatatypeVariantDefined in th-abstraction-0.7.2.0 · Language.Haskell.TH.Datatype
  • Ord FieldStrictnessDefined in th-abstraction-0.7.2.0 · Language.Haskell.TH.Datatype
  • Ord StrictnessDefined in th-abstraction-0.7.2.0 · Language.Haskell.TH.Datatype
  • Ord UnpackednessDefined in th-abstraction-0.7.2.0 · Language.Haskell.TH.Datatype
  • Ord DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • Ord MonthDefined in time-1.16.0.1 · Data.Time.Calendar.Month
  • Ord QuarterDefined in time-1.16.0.1 · Data.Time.Calendar.Quarter
  • Ord QuarterOfYearDefined in time-1.16.0.1 · Data.Time.Calendar.Quarter
  • Ord DayOfWeekDefined in time-1.16.0.1 · Data.Time.Calendar.Week
  • Ord AbsoluteTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.AbsoluteTime
  • Ord DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Ord NominalDiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.NominalDiffTime
  • Ord SystemTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.SystemTime
  • Ord UTCTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.UTCTime
  • Ord UniversalTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.UniversalTime
  • Ord TimeLocaleDefined in time-1.16.0.1 · Data.Time.Format.Locale
  • Ord LocalTimeDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.LocalTime
  • Ord TimeOfDayDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.TimeOfDay
  • Ord TimeZoneDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.TimeZone
  • Ord DurationDefined in time-hourglass-0.3.0 · Time.Diff
  • Ord PeriodDefined in time-hourglass-0.3.0 · Time.Diff
  • Ord TimezoneMinutesDefined in time-hourglass-0.3.0 · Time.Timezone
  • Ord UTCDefined in time-hourglass-0.3.0 · Time.Timezone
  • Ord DateDefined in time-hourglass-0.3.0 · Time.Types
  • Ord DateTimeDefined in time-hourglass-0.3.0 · Time.Types
  • Ord ElapsedDefined in time-hourglass-0.3.0 · Time.Types
  • Ord ElapsedPDefined in time-hourglass-0.3.0 · Time.Types
  • Ord HoursDefined in time-hourglass-0.3.0 · Time.Types
  • Ord MinutesDefined in time-hourglass-0.3.0 · Time.Types
  • Ord MonthDefined in time-hourglass-0.3.0 · Time.Types
  • Ord NanoSecondsDefined in time-hourglass-0.3.0 · Time.Types
  • Ord SecondsDefined in time-hourglass-0.3.0 · Time.Types
  • Ord TimeOfDayDefined in time-hourglass-0.3.0 · Time.Types
  • Ord TimezoneOffsetDefined in time-hourglass-0.3.0 · Time.Types
  • Ord WeekDayDefined in time-hourglass-0.3.0 · Time.Types
  • Ord CertificateTypeDefined in tls-2.4.9 · Network.TLS.Struct
  • Ord CipherIdDefined in tls-2.4.9 · Network.TLS.Types.Cipher
  • Ord VersionDefined in tls-2.4.9 · Network.TLS.Types.Version
  • Ord DirTypeDefined in unix-2.8.8.0 · System.Posix.Directory.Common
  • Ord CAttributesDefined in unix-2.8.8.0 · System.Posix.Files.Common
  • Ord StatxFlagsDefined in unix-2.8.8.0 · System.Posix.Files.Common
  • Ord StatxMaskDefined in unix-2.8.8.0 · System.Posix.Files.Common
  • Ord OpenFileFlagsDefined in unix-2.8.8.0 · System.Posix.IO.Common
  • Ord OpenModeDefined in unix-2.8.8.0 · System.Posix.IO.Common
  • Ord ProcessStatusDefined in unix-2.8.8.0 · System.Posix.Process.Internals
  • Ord BaudRateDefined in unix-2.8.8.0 · System.Posix.Terminal.Common
  • Ord UnixDiffTimeDefined in unix-time-0.5.0 · Data.UnixTime.Types
  • Ord UnixTimeDefined in unix-time-0.5.0 · Data.UnixTime.Types
  • Ord UUIDDefined in uuid-types-1.0.6.1 · Data.UUID.Types.Internal
  • Ord UnpackedUUIDDefined in uuid-types-1.0.6.1 · Data.UUID.Types.Internal
  • Ord CompressParamsDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Internal
  • Ord DecompressErrorDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Internal
  • Ord DecompressParamsDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Internal
  • Ord CompressionLevelDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Ord CompressionStrategyDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Ord DictionaryHashDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Ord FormatDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Ord MemoryLevelDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Ord MethodDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Ord WindowBitsDefined in zlib-0.7.1.1 · Codec.Compression.Zlib.Stream
  • Ord ()Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord1 f => Ord (Fix f)Defined in data-fix-0.3.4 · Data.Fix
  • Ord (Digest t)Defined in SHA-1.6.4.4 · Data.Digest.Pure.SHA
  • Ord (Encoding' a)Defined in aeson-2.2.5.1 · Data.Aeson.Encoding.Internal
  • Ord (Async a)Defined in async-2.2.6 · Control.Concurrent.Async.Internal
  • Ord (Bits n)Defined in basement-0.0.16 · Basement.Bits
  • Ord (Zn n)Defined in basement-0.0.16 · Basement.Bounded
  • Ord (Zn64 n)Defined in basement-0.0.16 · Basement.Bounded
  • Ord (FinalPtr a)Defined in basement-0.0.16 · Basement.FinalPtr
  • Ord (CountOf ty)Defined in basement-0.0.16 · Basement.Types.OffsetSize
  • Ord (Offset ty)Defined in basement-0.0.16 · Basement.Types.OffsetSize
  • Ord (IV k)Defined in crypto-api-0.13.3 · Crypto.Types
  • Ord (Digest a)Defined in crypton-2.1.7 · Crypto.Hash.Types
  • Ord (ConstPtr a)Defined in ghc-internal-10.0.0 · GHC.Internal.Foreign.C.ConstPtr
  • Ord (ForeignPtr a)Defined in ghc-internal-10.0.0 · GHC.Internal.ForeignPtr
  • Ord (FunPtr a)Defined in ghc-internal-10.0.0 · GHC.Internal.Ptr
  • Ord (Ptr a)Defined in ghc-internal-10.0.0 · GHC.Internal.Ptr
  • Ord (SChar c)Defined in ghc-internal-10.0.0 · GHC.Internal.TypeLits
  • Ord (SSymbol s)Defined in ghc-internal-10.0.0 · GHC.Internal.TypeLits
  • Ord (SNat n)Defined in ghc-internal-10.0.0 · GHC.Internal.TypeNats
  • Ord (ElapsedSince epoch)Defined in hourglass-0.2.12 · Data.Hourglass.Epoch
  • Ord (ElapsedSinceP epoch)Defined in hourglass-0.2.12 · Data.Hourglass.Epoch
  • Ord (Token s) => Ord (ET s)Defined in megaparsec-9.5.0 · Text.Megaparsec.Error.Builder
  • Ord (CountOf ty)Defined in mlkem-0.2.3.0 · Base
  • Ord (Offset ty)Defined in mlkem-0.2.3.0 · Base
  • Ord (RText l)Defined in modern-uri-0.3.6.1 · Text.URI.Types
  • Ord (Seed g)Defined in random-1.3.1 · System.Random.Internal
  • Ord (EnumSet e)Defined in regex-tdfa-1.3.2.6 · Data.IntSet.EnumSet2
  • Ord (Url scheme)Defined in req-3.13.4 · Network.HTTP.Req
  • Ord (ElapsedSince epoch)Defined in time-hourglass-0.3.0 · Time.Epoch
  • Ord (ElapsedSinceP epoch)Defined in time-hourglass-0.3.0 · Time.Epoch
  • Ord a => Ord (Numbered a)Defined in Diff-2.0.1 · Data.Algorithm.DiffContext
  • Ord a => Ord (DiffOperation a)Defined in Diff-2.0.1 · Data.Algorithm.DiffOutput
  • Ord a => Ord (Only a)Defined in Only-0.1 · Data.Tuple.Only
  • Ord a => Ord (Blind a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (Fixed a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (Large a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (Negative a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (NoShrink a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (NonEmptyList a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (NonNegative a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (NonPositive a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (NonZero a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (OrderedList a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (Positive a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (Shrink2 a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (Small a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (SortedList a)Defined in QuickCheck-2.18.0.0 · Test.QuickCheck.Modifiers
  • Ord a => Ord (First a)Defined in base-4.23.0.0 · Data.Semigroup
  • Ord a => Ord (Last a)Defined in base-4.23.0.0 · Data.Semigroup
  • Ord a => Ord (Max a)Defined in base-4.23.0.0 · Data.Semigroup
  • Ord a => Ord (Min a)Defined in base-4.23.0.0 · Data.Semigroup
  • Ord a => Ord (Base16 a)Defined in base16-1.0 · Data.Base16.Types.Internal
  • Ord a => Ord (Array a)Defined in basement-0.0.16 · Basement.BoxedArray
  • Ord a => Ord (CmdArgs a)Defined in cmdargs-0.10.22 · System.Console.CmdArgs.Implicit.Type
  • Ord a => Ord (IntMap a)Defined in containers-0.8 · Data.IntMap.Internal
  • Ord a => Ord (Seq a)Defined in containers-0.8 · Data.Sequence.Internal
  • Ord a => Ord (ViewL a)Defined in containers-0.8 · Data.Sequence.Internal
  • Ord a => Ord (ViewR a)Defined in containers-0.8 · Data.Sequence.Internal
  • Ord a => Ord (Intersection a)Defined in containers-0.8 · Data.Set.Internal
  • Ord a => Ord (Set a)Defined in containers-0.8 · Data.Set.Internal
  • Ord a => Ord (PostOrder a)Defined in containers-0.8 · Data.Tree
  • Ord a => Ord (Tree a)Defined in containers-0.8 · Data.Tree
  • Ord a => Ord (DNonEmpty a)Defined in dlist-1.0 · Data.DList.DNonEmpty.Internal
  • Ord a => Ord (DList a)Defined in dlist-1.0 · Data.DList.Internal
  • Ord a => Ord (Doc a)Defined in doclayout-0.6 · Text.DocLayout
  • Ord a => Ord (FlatDoc a)Defined in doclayout-0.6 · Text.DocLayout
  • Ord a => Ord (Attr a)Defined in doclayout-0.6 · Text.DocLayout.Attributed
  • Ord a => Ord (Attributed a)Defined in doclayout-0.6 · Text.DocLayout.Attributed
  • Ord a => Ord (Trie a)Defined in emojis-0.1.5 · Trie
  • Ord a => Ord (NonEmpty a)Defined in ghc-internal-10.0.0 · GHC.Internal.Base
  • Ord a => Ord (Identity a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Identity
  • Ord a => Ord (First a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Ord a => Ord (Last a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Ord a => Ord (Down a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Ord
  • Ord a => Ord (Dual a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Ord a => Ord (Product a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Ord a => Ord (Sum a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Ord a => Ord (ZipList a)Defined in ghc-internal-10.0.0 · GHC.Internal.Functor.ZipList
  • Ord a => Ord (Maybe a)Defined in ghc-internal-10.0.0 · GHC.Internal.Maybe
  • Ord a => Ord (Hashed a)Defined in hashable-1.5.1.0 · Data.Hashable.Class
  • Ord a => Ord (FastTree a)Defined in hledger-lib-1.52.4 · Hledger.Data.Account
  • Ord a => Ord (PeriodData a)Defined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord a => Ord (LenientData a)Defined in http-api-data-0.7 · Web.Internal.HttpApiData
  • Ord a => Ord (AddrRange a)Defined in iproute-1.7.15 · Data.IP.Range
  • Ord a => Ord (Array a)Defined in primitive-0.9.1.0 · Data.Primitive.Array

    Lexicographic ordering. Subject to change between major versions.

  • Ord a => Ord (SmallArray a)Defined in primitive-0.9.1.0 · Data.Primitive.SmallArray

    Lexicographic ordering. Subject to change between major versions.

  • Ord a => Ord (CharMap a)Defined in regex-tdfa-1.3.2.6 · Data.IntMap.CharMap2
  • Ord a => Ord (Maybe a)Defined in strict-0.5.1 · Data.Strict.Maybe
  • Ord a => Ord (Stream a)Defined in text-2.1.4 · Data.Text.Internal.Fusion.Types
  • Ord a => Ord (HashSet a)Defined in unordered-containers-0.2.21 · Data.HashSet.Internal
  • Ord a => Ord (Vector a)Defined in vector-0.13.2.0 · Data.Vector
  • Ord a => Ord (Vector a)Defined in vector-0.13.2.0 · Data.Vector.Strict
  • Ord a => Ord (a)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord a => Ord [a]Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord ann => Ord (SimpleDocStream ann)Defined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Ord ann => Ord (SimpleDocTok ann)Defined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.SimpleDocTree
  • Ord ann => Ord (SimpleDocTree ann)Defined in prettyprinter-1.7.2 · Prettyprinter.Render.Util.SimpleDocTree
  • Ord e => Ord (ErrorFancy e)Defined in megaparsec-9.5.0 · Text.Megaparsec.Error
  • Ord e => Ord (EF e)Defined in megaparsec-9.5.0 · Text.Megaparsec.Error.Builder
  • Ord flag => Ord (TyVarBndr flag)Defined in ghc-internal-10.0.0 · GHC.Internal.TH.Syntax
  • Ord g => Ord (StateGen g)Defined in random-1.3.1 · System.Random.Internal
  • Ord g => Ord (AtomicGen g)Defined in random-1.3.1 · System.Random.Stateful
  • Ord g => Ord (IOGen g)Defined in random-1.3.1 · System.Random.Stateful
  • Ord g => Ord (STGen g)Defined in random-1.3.1 · System.Random.Stateful
  • Ord g => Ord (TGen g)Defined in random-1.3.1 · System.Random.Stateful
  • Ord lines => Ord (Border lines)Defined in hledger-lib-1.52.4 · Hledger.Write.Spreadsheet
  • Ord m => Ord (WrappedMonoid m)Defined in base-4.23.0.0 · Data.Semigroup
  • Ord p => Ord (Par1 p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord s => Ord (CI s)Defined in case-insensitive-1.2.1.0 · Data.CaseInsensitive.Internal
  • Ord string => Ord (UTF8 string)Defined in utf8-string-1.0.2 · Data.String.UTF8
  • Ord t => Ord (ErrorItem t)Defined in megaparsec-9.5.0 · Text.Megaparsec.Error
  • Ord v => Ord (KeyMap v)Defined in aeson-2.2.5.1 · Data.Aeson.KeyMap
  • Integral a => Ord (Ratio a)Defined in ghc-internal-10.0.0 · GHC.Internal.Real
  • Integral i => Ord (DecimalRaw i)Defined in Decimal-0.5.2 · Data.Decimal
  • ByteArrayAccess bytes => Ord (View bytes)Defined in memory-0.18.0 · Data.ByteArray.View
  • ByteArrayAccess bytes => Ord (View bytes)Defined in ram-0.22.1 · Data.ByteArray.View
  • (ByteSwap a, Ord a) => Ord (BE a)Defined in basement-0.0.16 · Basement.Endianness
  • (ByteSwap a, Ord a) => Ord (LE a)Defined in basement-0.0.16 · Basement.Endianness
  • (PrimType ty, Ord ty) => Ord (Block ty)Defined in basement-0.0.16 · Basement.Block.Base
  • (PrimType ty, Ord ty) => Ord (UArray ty)Defined in basement-0.0.16 · Basement.UArray.Base
  • (Functor f, Ord1 f) => Ord (Mu f)Defined in data-fix-0.3.4 · Data.Fix
  • (Functor f, Ord1 f) => Ord (Nu f)Defined in data-fix-0.3.4 · Data.Fix
  • (Ord a, Prim a) => Ord (PrimArray a)Defined in primitive-0.9.1.0 · Data.Primitive.PrimArray

    Lexicographic ordering. Subject to change between major versions.

  • (Ord t, Time t) => Ord (LocalTime t)Defined in hourglass-0.2.12 · Data.Hourglass.Local
  • (Ord t, Time t) => Ord (LocalTime t)Defined in time-hourglass-0.3.0 · Time.LocalTime
  • (Storable a, Ord a) => Ord (Vector a)Defined in vector-0.13.2.0 · Data.Vector.Storable
  • (Prim a, Ord a) => Ord (Vector a)Defined in vector-0.13.2.0 · Data.Vector.Primitive
  • (Unbox a, Ord a) => Ord (Vector a)Defined in vector-0.13.2.0 · Data.Vector.Unboxed · orphan
  • Ord (Fixed a)Defined in base-4.23.0.0 · Data.Fixed
  • Ord (MacKey c d)Defined in crypto-api-0.13.3 · Crypto.HMAC
  • Ord (Proxy s)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Proxy
  • Ord (TypeRep a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Typeable.Internal
  • Ord (U1 p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (V1 p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (ParseError Text HledgerParseErrorData)Defined in hledger-lib-1.52.4 · Hledger.Utils.Parse
  • Ord (f a) => Ord (Zippy f a)Defined in semialign-1.3.1.1 · Data.Zip
  • Ord a => Ord (Arg a b)Defined in base-4.23.0.0 · Data.Semigroup

    Note that Arg's Ord instance has min and max implementations that differ from the tie-breaking conventions of the default implementation of min and max in class Ord; Arg breaks ties by favoring the first argument in both functions.

  • Ord a => Ord (ListN n a)Defined in basement-0.0.16 · Basement.Sized.List
  • Ord a => Ord (EnumMap k a)Defined in regex-tdfa-1.3.2.6 · Data.IntMap.EnumMap2
  • Ord ba => Ord (SizedByteArray n ba)Defined in memory-0.18.0 · Data.ByteArray.Sized
  • Ord ba => Ord (SizedByteArray n ba)Defined in ram-0.22.1 · Data.ByteArray.Sized
  • (Ord1 f, Ord a) => Ord (Lift f a)Defined in transformers-0.6.3.0 · Control.Applicative.Lift
  • (Ord1 m, Ord a) => Ord (MaybeT m a)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Maybe
  • (PrimType a, Ord a) => Ord (BlockN n a)Defined in basement-0.0.16 · Basement.Sized.Block
  • (Ord a, Ord1 f) => Ord (Free f a)Defined in control-monad-free-0.6.2 · Control.Monad.Free
  • (Ord a, Ord b) => Ord (These a b)Defined in basement-0.0.16 · Basement.These
  • (Ord a, Ord b) => Ord (Either a b)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Either
  • (Ord a, Ord b) => Ord (Either a b)Defined in strict-0.5.1 · Data.Strict.Either
  • (Ord a, Ord b) => Ord (These a b)Defined in strict-0.5.1 · Data.Strict.These
  • (Ord a, Ord b) => Ord (Pair a b)Defined in strict-0.5.1 · Data.Strict.Tuple
  • (Ord a, Ord b) => Ord (These a b)Defined in these-1.2.1 · Data.These
  • (Ord a, Ord b) => Ord (a, b)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord k, Ord v) => Ord (Map k v)Defined in containers-0.8 · Data.Map.Internal
  • (Ord k, Ord v) => Ord (HashMap k v)Defined in unordered-containers-0.2.21 · Data.HashMap.Internal

    The ordering is total and consistent with the Eq instance. However, nothing else about the ordering is specified, and it may change from version to version of either this package or of hashable.

  • (Ix i, Ord e) => Ord (Array i e)Defined in ghc-internal-10.0.0 · GHC.Internal.Arr
  • (Ix ix, Ord e, IArray UArray e) => Ord (UArray ix e)Defined in array-0.5.8.0 · Data.Array.Base
  • (GOrd (Rep1 f a), Generic1 f) => Ord (FunctorClassesDefault f a)Defined in transformers-compat-0.7.2 · Data.Functor.Classes.Generic.Internal
  • Ord (Coercion a b)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Type.Coercion
  • Ord (URec Char p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (URec Double p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (URec Float p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (URec Int p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (URec Word p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (URec (Ptr ()) p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (a :~: b)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Type.Equality
  • Ord (bi a b) => Ord (Biap bi a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Biap
  • Ord (f a) => Ord (Ap f a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Monoid
  • Ord (f a) => Ord (Alt f a)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Semigroup.Internal
  • Ord (f p) => Ord (Rec1 f p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (p (Fix p a) a) => Ord (Fix p a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Fix
  • Ord (p a a) => Ord (Join p a)Defined in bifunctors-5.6.3 · Data.Bifunctor.Join
  • Ord a => Ord (Const a b)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Functor.Const
  • Ord a => Ord (Constant a b)Defined in transformers-0.6.3.0 · Data.Functor.Constant
  • Ord a => Ord (Bundle Id v a)Defined in vector-0.13.2.0 · Data.Vector.Fusion.Bundle · orphan
  • Ord b => Ord (Tagged s b)Defined in tagged-0.8.11 · Data.Tagged
  • (Ord1 f, Ord a) => Ord (Backwards f a)Defined in transformers-0.6.3.0 · Control.Applicative.Backwards
  • (Ord1 f, Ord a) => Ord (IdentityT f a)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Identity
  • (Ord1 f, Ord a) => Ord (Reverse f a)Defined in transformers-0.6.3.0 · Data.Functor.Reverse
  • (Ord (f a), Ord (g a), Ord a) => Ord (These1 f g a)Defined in these-1.2.1 · Data.Functor.These
  • (Ord a, Ord b, Ord c) => Ord (a, b, c)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord e, Ord1 m, Ord a) => Ord (ExceptT e m a)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Except
  • (Ord w, Ord1 m, Ord a) => Ord (WriterT w m a)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Lazy
  • (Ord w, Ord1 m, Ord a) => Ord (WriterT w m a)Defined in transformers-0.6.3.0 · Control.Monad.Trans.Writer.Strict
  • (Generic1 f, Ord (Rep1 f a)) => Ord (Generically1 f a)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (a :~~: b)Defined in ghc-internal-10.0.0 · GHC.Internal.Data.Type.Equality
  • Ord (f (g m) a) => Ord (ComposeT f g m a)Defined in mmorph-1.2.2 · Control.Monad.Trans.Compose
  • Ord c => Ord (K1 i c p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • (Ord (f a), Ord (g a)) => Ord (Product f g a)Defined in base-4.23.0.0 · Data.Functor.Product
  • (Ord (f a), Ord (g a)) => Ord (Sum f g a)Defined in base-4.23.0.0 · Data.Functor.Sum
  • (Ord (f p), Ord (g p)) => Ord ((:*:) f g p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • (Ord (f p), Ord (g p)) => Ord ((:+:) f g p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • (Ord a, Ord b, Ord c, Ord d) => Ord (a, b, c, d)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord (f (g a)) => Ord (Compose f g a)Defined in base-4.23.0.0 · Data.Functor.Compose
  • Ord (f (g p)) => Ord ((:.:) f g p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (f a) => Ord (Clown f a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Clown
  • Ord (f p) => Ord (M1 i c f p)Defined in ghc-internal-10.0.0 · GHC.Internal.Generics
  • Ord (g b) => Ord (Joker g a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Joker
  • Ord (p a b) => Ord (WrappedBifunctor p a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Wrapped
  • Ord (p b a) => Ord (Flip p a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Flip
  • (Ord a, Ord b, Ord c, Ord d, Ord e) => Ord (a, b, c, d, e)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord (f a b), Ord (g a b)) => Ord (Product f g a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Product
  • (Ord (p a b), Ord (q a b)) => Ord (Sum p q a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Sum
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f) => Ord (a, b, c, d, e, f)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord (f (p a b)) => Ord (Tannen f p a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Tannen
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g) => Ord (a, b, c, d, e, f, g)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h) => Ord (a, b, c, d, e, f, g, h)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • Ord (p (f a) (g b)) => Ord (Biff p f g a b)Defined in bifunctors-5.6.3 · Data.Bifunctor.Biff
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i) => Ord (a, b, c, d, e, f, g, h, i)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j) => Ord (a, b, c, d, e, f, g, h, i, j)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k) => Ord (a, b, c, d, e, f, g, h, i, j, k)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l) => Ord (a, b, c, d, e, f, g, h, i, j, k, l)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
  • (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n, Ord o) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)Defined in ghc-internal-10.0.0 · GHC.Internal.Classes
datadata ThreadId
#

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 would be difficult to correct while continuing to support threadStatus.

Instances5Eq, Ord, Show, NFData, Hashable
  • Eq ThreadIdDefined in ghc-internal-10.0.0 · GHC.Internal.Conc.Sync
  • Ord ThreadIdDefined in ghc-internal-10.0.0 · GHC.Internal.Conc.Sync
  • Show ThreadIdDefined in ghc-internal-10.0.0 · GHC.Internal.Conc.Sync
  • NFData ThreadIdDefined in deepseq-1.5.2.0 · Control.DeepSeq
  • Hashable ThreadIdDefined in hashable-1.5.1.0 · Data.Hashable.Class
classclass 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

fail s should be an action that runs in the monad itself, not an exception (except in instances of MonadIO). In particular, fail should not be implemented in terms of error.

Methods

Instances60MonadFail, …
datadata Either a b
#

The Either type represents values with two possibilities: a value of type Either a b is either Left a or 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 Either String Int is the type of values which can be either a String or an Int. The Left constructor can be used only on Strings, and the Right constructor can be used only on Ints:

Example6 expressions
let s = Left "foo" :: Either String IntsLeft "foo"let n = Right 3 :: Either String IntnRight 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:

Example4 expressions
let s = Left "foo" :: Either String Intlet n = Right 3 :: Either String Intfmap (*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.

Example3 expressions
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.

Example2 expressions
:{    let parseMultiple :: Either String Int        parseMultiple = do          x <- parseEither '1'          y <- parseEither '2'          return (x + y):}
Example1 expression
parseMultipleRight 3

But the following should fail overall, since the first operation where we attempt to parse 'm' as an Int will fail:

Example2 expressions
:{    let parseMultiple :: Either String Int        parseMultiple = do          x <- parseEither 'm'          y <- parseEither '2'          return (x + y):}
Example1 expression
parseMultipleLeft "parse error"

Constructors

Instances104Bifoldable, Bifoldable1, Bifunctor, Bitraversable, Eq2, Ord2, …
methodelem :: Eq a => a -> t a -> Bool
#

Does the element occur in the structure?

Note: elem is often used in infix form.

Examples

Basic usage:

Example1 expression
3 `elem` []False
Example1 expression
3 `elem` [1,2]False
Example1 expression
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:

Example1 expression
3 `elem` [1..]True
Example1 expression
3 `elem` ([4..] ++ [3])* Hangs forever *
methodfoldl :: (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 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 = foldl f z . toList
Examples

The first example is a strict fold, which in practice is best performed with foldl'.

Example1 expression
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.

Example1 expression
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:

Example1 expression
foldl (\a _ -> a) 0 $ repeat 1* Hangs forever *

WARNING: When it comes to lists, you always want to use either foldl' or foldr instead.

methodfoldl' :: (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
methodfoldl1 :: (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.

foldl1 f = foldl1 f . toList
Examples

Basic usage:

Example1 expression
foldl1 (+) [1..4]10
Example1 expression
foldl1 (+) []*** Exception: Prelude.foldl1: empty list
Example1 expression
foldl1 (+) Nothing*** Exception: foldl1: empty structure
Example1 expression
foldl1 (-) [1..4]-8
Example1 expression
foldl1 (&&) [True, False, True, True]False
Example1 expression
foldl1 (||) [False, False, True, True]True
Example1 expression
foldl1 (+) [1..]* Hangs forever *
methodfoldr :: (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 = foldr f z . toList
Examples

Basic usage:

Example1 expression
foldr (||) False [False, True, False]True
Example1 expression
foldr (||) False []False
Example1 expression
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:

Example1 expression
foldr (||) False (True : repeat False)True

But the following doesn't terminate:

Example1 expression
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):

Example1 expression
take 5 $ foldr (\i acc -> i : fmap (+3) acc) [] (repeat 1)[1,4,7,10,13]
methodfoldr1 :: (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:

Example1 expression
foldr1 (+) [1..4]10
Example1 expression
foldr1 (+) []Exception: Prelude.foldr1: empty list
Example1 expression
foldr1 (+) Nothing*** Exception: foldr1: empty structure
Example1 expression
foldr1 (-) [1..4]-2
Example1 expression
foldr1 (&&) [True, False, True, True]False
Example1 expression
foldr1 (||) [False, False, True, True]True
Example1 expression
foldr1 (+) [1..]* Hangs forever *
methodlength :: 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:

Example1 expression
length []0
Example2 expressions
length ['a', 'b', 'c']3length [1..]* Hangs forever *
methodmaximum :: Ord a => t a -> a
#

The largest element of a non-empty structure. This function is equivalent to foldr1 max, and its behavior on structures with multiple largest elements depends on the relevant implementation of max. For the default implementation of max (max x y = if x <= y then y else x), structure order is used as a tie-breaker: if there are multiple largest elements, the rightmost of them is chosen (this is equivalent to maximumBy compare).

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:

Example1 expression
maximum [1..10]10
Example1 expression
maximum []*** Exception: Prelude.maximum: empty list
Example1 expression
maximum Nothing*** Exception: maximum: empty structure

WARNING: This function is partial for possibly-empty structures like lists.

methodminimum :: Ord a => t a -> a
#

The least element of a non-empty structure. This function is equivalent to foldr1 min, and its behavior on structures with multiple largest elements depends on the relevant implementation of min. For the default implementation of min (min x y = if x <= y then x else y), structure order is used as a tie-breaker: if there are multiple least elements, the leftmost of them is chosen (this is equivalent to minimumBy compare).

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:

Example1 expression
minimum [1..10]1
Example1 expression
minimum []*** Exception: Prelude.minimum: empty list
Example1 expression
minimum Nothing*** Exception: minimum: empty structure

WARNING: This function is partial for possibly-empty structures like lists.

methodnull :: 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:

Example1 expression
null []True
Example1 expression
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).

Example1 expression
null [1..]False
methodproduct :: Num a => t a -> a
#

The product function computes the product of the numbers of a structure.

Examples

Basic usage:

Example1 expression
product []1
Example1 expression
product [42]42
Example1 expression
product [1..10]3628800
Example1 expression
product [4.1, 2.0, 1.7]13.939999999999998
Example1 expression
product [1..]* Hangs forever *
methodsum :: Num a => t a -> a
#

The sum function computes the sum of the numbers of a structure.

Examples

Basic usage:

Example1 expression
sum []0
Example1 expression
sum [42]42
Example1 expression
sum [1..10]55
Example1 expression
sum [4.1, 2.0, 1.7]7.8
Example1 expression
sum [1..]* Hangs forever *
newtypenewtype Const a (b :: k)
#

The Const functor.

Examples
Example1 expression
fmap (++ "World") (Const "Hello")Const "Hello"

Because we ignore the second type parameter to Const, the Applicative instance, which has (<*>) :: Monoid m => Const m (a -> b) -> Const m a -> Const m b essentially turns into Monoid m => m -> m -> m, which is (<>)

Example1 expression
Const [1, 2, 3] <*> Const [4, 5, 6]Const [1,2,3,4,5,6]

Constructors

Instances92Semigroupoid, Generic1, FoldableWithIndex, FunctorWithIndex, TraversableWithIndex, PrettyAnn, …
newtypenewtype Down a
#

The Down type allows you to reverse sort order conveniently. A value of type Down a contains a value of type a (represented as Down a).

If a has an Ord 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: then sortWith by Down x.

Example1 expression
compare True FalseGT
Example1 expression
compare (Down True) (Down False)LT

If a has a Bounded instance then the wrapped instance also respects the reversed ordering by exchanging the values of minBound and maxBound.

Example1 expression
minBound :: Int-9223372036854775808
Example1 expression
minBound :: Down IntDown 9223372036854775807

All other instances of Down a behave as they do for a.

Constructors

Instances53Monad, Functor, MonadFix, Applicative, Foldable, Traversable, …
methodmapM :: 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 Data.Foldable.mapM_.

Examples

mapM is literally a traverse with a type signature restricted to Monad. Its implementation may be more efficient due to additional power of Monad.

methodsequence :: 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 Data.Foldable.sequence_.

Examples

Basic usage:

The first two examples are instances where the input and and output of sequence are isomorphic.

Example1 expression
sequence $ Right [1,2,3,4][Right 1,Right 2,Right 3,Right 4]
Example1 expression
sequence $ [Right 1,Right 2,Right 3,Right 4]Right [1,2,3,4]

The following examples demonstrate short circuit behavior for sequence.

Example1 expression
sequence $ Left [1,2,3,4]Left [1,2,3,4]
Example1 expression
sequence $ [Left 0, Right 1,Right 2,Right 3,Right 4]Left 0
newtypenewtype ZipList a
#

Lists, but with an Applicative functor based on zipping.

Examples

In contrast to the Applicative for List:

Example1 expression
(+) <$> [1, 2, 3] <*> [4, 5, 6][5,6,7,6,7,8,7,8,9]

The Applicative instance of ZipList applies the operation by pairing up the elements, analogous to zipWithN

Example1 expression
(+) <$> ZipList [1, 2, 3] <*> ZipList [4, 5, 6]ZipList {getZipList = [5,7,9]}
Example1 expression
(,,,) <$> ZipList [1, 2] <*> ZipList [3, 4] <*> ZipList [5, 6] <*> ZipList [7, 8]ZipList {getZipList = [(1,3,5,7),(2,4,6,8)]}
Example1 expression
ZipList [(+1), (^2), (/ 2)] <*> ZipList [5, 5, 5]ZipList {getZipList = [6.0,25.0,2.5]}

Constructors

Instances39Functor, Applicative, Foldable, Traversable, Alternative, NFData1, …
typetype FilePath = String
#

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.

datadata SeekMode
#

A mode that determines the effect of GHC.Internal.System.IO.hSeek hdl mode i.

Constructors

  • AbsoluteSeek

    the position of hdl is set to i.

  • RelativeSeek

    the position of hdl is set to offset i from the current position.

  • SeekFromEnd

    the position of hdl is set to offset i from the end of the file.

Instances9Enum, Eq, Ord, Read, Show, Ix, …
  • Enum SeekModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Device
  • Eq SeekModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Device
  • Ord SeekModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Device
  • Read SeekModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Device
  • Show SeekModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Device
  • Ix SeekModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Device
  • Arbitrary SeekModeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
  • CoArbitrary SeekModeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
  • Function SeekModeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Function
datadata 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 GHC.Internal.System.IO.utf8.

Instances3Show, Arbitrary, CoArbitrary
datadata ExitCode
#

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).

Instances12Eq, Ord, Read, Show, Generic, Exception, …
typetype IOError = IOException
#

The Haskell 2010 type for exceptions in the IO monad. Any I/O operation may raise an IOError 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.

datadata IOErrorType
#

An abstract type that contains a value for each variant of IOError.

Instances2Eq, Show
  • Eq IOErrorTypeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Exception
  • Show IOErrorTypeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Exception
datadata 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 GHC.Internal.System.IO.hFlush is issued, or the handle is closed.

  • block-buffering: the entire buffer is written out whenever it overflows, a GHC.Internal.System.IO.hFlush is 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 GHC.Internal.System.IO.hLookAhead operation 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 n items if the argument is Just n and is otherwise implementation-dependent.

Instances7Eq, Ord, Read, Show, Arbitrary, CoArbitrary, …
datadata Handle
#

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.

Instances7Eq, Show, InputSource, OutputSink, HasBackend, ByteSink, …
datadata Newline
#

The representation of a newline in the external file or stream.

Constructors

Instances7Eq, Ord, Read, Show, Arbitrary, CoArbitrary, …
  • Eq NewlineDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Handle.Types
  • Ord NewlineDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Handle.Types
  • Read NewlineDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Handle.Types
  • Show NewlineDefined in ghc-internal-10.0.0 · GHC.Internal.IO.Handle.Types
  • Arbitrary NewlineDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
  • CoArbitrary NewlineDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
  • Function NewlineDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Function
datadata 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

Instances7Eq, Ord, Read, Show, Arbitrary, CoArbitrary, …
datadata IOMode
#

See GHC.Internal.System.IO.openFile

Instances9Enum, Eq, Ord, Read, Show, Ix, …
  • Enum IOModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.IOMode
  • Eq IOModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.IOMode
  • Ord IOModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.IOMode
  • Read IOModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.IOMode
  • Show IOModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.IOMode
  • Ix IOModeDefined in ghc-internal-10.0.0 · GHC.Internal.IO.IOMode
  • Arbitrary IOModeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
  • CoArbitrary IOModeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Arbitrary
  • Function IOModeDefined in QuickCheck-2.18.0.0 · Test.QuickCheck.Function
datadata MVar 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.

Instances3NFData1, Eq, NFData
  • NFData1 MVarDefined in deepseq-1.5.2.0 · Control.DeepSeq
  • Eq (MVar a)Defined in ghc-internal-10.0.0 · GHC.Internal.MVar

    Compares the underlying pointers.

  • NFData (MVar a)Defined in deepseq-1.5.2.0 · Control.DeepSeq

    NOTE: Only strict in the reference and not the referenced value.

typetype HasCallStack = IP "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.

newtypenewtype IO a
#

A value of type IO a is a computation which, when performed, does some I/O before returning a value of type a.

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 Prelude.>> and Prelude.>>= operations from the Prelude.Monad class.

Instances78Monad, Functor, MonadFix, MonadFail, Applicative, GHCiSandboxIO, …
datadata Ordering
#
Instances30Bounded, Enum, Eq, Data, Ord, Read, …
datadata 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:

Example1 expression
:t OtherLetterOtherLetter :: GeneralCategory

Eq instance:

Example2 expressions
UppercaseLetter == UppercaseLetterTrueUppercaseLetter == LowercaseLetterFalse

Ord instance:

Example1 expression
NonSpacingMark <= MathSymbolTrue

Enum instance:

Example1 expression
enumFromTo ModifierLetter SpacingCombiningMark[ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark]

Text.Read.Read instance:

Example2 expressions
read "DashPunctuation" :: GeneralCategoryDashPunctuationread "17" :: GeneralCategory*** Exception: Prelude.read: no parse

Show instance:

Example1 expression
show EnclosingMark"EnclosingMark"

Bounded instance:

Example2 expressions
minBound :: GeneralCategoryUppercaseLettermaxBound :: GeneralCategoryNotAssigned

Ix instance:

Example3 expressions
import GHC.Internal.Data.Ix ( index )index (OtherLetter,Control) FinalQuote12index (OtherLetter,Control) Format*** Exception: Error in array index

Constructors

Instances12Bounded, Enum, Eq, Ord, Read, Show, …
datadata AmountFormat
#

Formatting options available when displaying Amounts and MixedAmounts. Similar to AmountStyle but lower level, not attached to amounts or commodities, and can override it in some ways. See also hledger manual > "Amount formatting, parseability", which speaks of human, hledger, and machine output.

Constructors

Instances2Show, Default
  • Show AmountFormatDefined in hledger-lib-1.52.4 · Hledger.Data.Amount
  • Default AmountFormatDefined in hledger-lib-1.52.4 · Hledger.Data.Amount

    By default, display amounts using defaultFmt amount display options.

datadata BalancingOpts
#

Constructors

Instances4Eq, Ord, Show, HasBalancingOpts
classclass HasBalancingOpts c where
#
Instances3HasBalancingOpts
newtypenewtype DayPartition
#

A partition of time into one or more contiguous periods, plus a historical period that precedes them. Note DayPartition does not store per-period data - only the periods' start/end dates.

Instances3Eq, Ord, Show
newtypenewtype RawOpts
#

The result of running cmdargs: an association list of option names to string values.

Instances2Show, Default
  • Show RawOptsDefined in hledger-lib-1.52.4 · Hledger.Data.RawOptions
  • Default RawOptsDefined in hledger-lib-1.52.4 · Hledger.Data.RawOptions
datadata 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.

Instances2Eq, Show
datadata 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

Instances3Eq, Show, Default

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:

    • Left justify ? Right justified if false

    • Minimum width ? Will be space-padded if narrower than this

    • Maximum width ? Will be clipped if wider than this

    • Which of the standard hledger report item fields to interpolate

Instances2Eq, Show

How to determine the precision used for checking that transactions are balanced. See #2402.

Constructors

  • TBPOld

    Legacy behaviour, as in hledger <1.50, included to ease upgrades. use precision inferred from the whole journal, overridable by commodity directive or -c. Display precision is also transaction balancing precision; increasing it can break journal reading. Some valid journals are rejected until commodity directives are added. Small unbalanced remainders can be hidden, and in accounts that are never reconciled, can accumulate over time.

  • TBPExact

    Simpler, more robust behaviour, as in Ledger: use precision inferred from the transaction. Display precision and transaction balancing precision are independent; display precision never affects journal reading. Valid journals from ledger or beancount are accepted without needing commodity directives. Every imbalance in a transaction is visibly accounted for in that transaction's journal entry.

Instances6Bounded, Enum, Eq, Ord, Read, Show
datadata Account a
#

An account within a hierarchy, with references to its parent and subaccounts if any, and with per-report-period data of type a. Only the name is required; the other fields may or may not be present.

Constructors

Instances8Functor, Eq, Show, Generic, FromJSON, ToJSON, …
datadata AccountAlias
#
Instances8Eq, Ord, Read, Show, Generic, NFData, …

Extra information about an account that can be derived from its account directive (and the other account directives).

Constructors

Instances7Eq, Show, Generic, NFData, FromJSON, ToJSON, …
datadata 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 with which to balance commodity conversions

  • Gain

    a subtype of Revenue - realised capital gains/losses

  • UnrealisedGain

    a subtype of Equity - accumulated unrealised capital gains/losses (used by hledger 2)

Instances8Eq, Ord, Show, Generic, NFData, ToJSON, …
datadata Amount
#

Constructors

Instances10Eq, Num, Ord, Show, Generic, NFData, …
datadata AmountCost
#

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.

Instances8Eq, Ord, Show, Generic, NFData, FromJSON, …
datadata 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

Instances9Eq, Ord, Read, Show, Generic, NFData, …
datadata AmountStyle
#

Display styles for amounts - things which can be detected during parsing, such as commodity side and spacing, digit group marks, decimal mark, number of decimal digits etc. Every Amount has an AmountStyle. After amounts are parsed from the input, for each Commodity a standard style is inferred and then used when displaying amounts in that commodity. Related to AmountFormat but higher level.

See also: - hledger manual > Commodity styles - hledger manual > Amounts - hledger manual > Commodity display style

Constructors

Instances9Eq, Ord, Read, Show, Generic, NFData, …
datadata 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

Instances8Eq, Show, Generic, NFData, FromJSON, ToJSON, …
datadata BalanceData
#

Data that's useful in "balance" reports: subaccount-exclusive and -inclusive amounts, typically representing either a balance change or an end balance; and a count of postings.

Constructors

Instances9Eq, Show, Generic, Semigroup, Monoid, FromJSON, …
datadata Commodity
#

Constructors

Instances6Eq, Show, Generic, NFData, ToJSON, Rep
datadata CostBasis
#

The cost basis of an individual lot - some quantity of an asset acquired at a given date and time. This can represent a definite cost basis, which must have a cost and date; the label is optional. Or it can represent a cost basis matcher for selecting lots. Note: cost is always stored as a per-unit cost, even if the user specified total cost with {{}}.

Constructors

Instances8Eq, Ord, Show, Generic, NFData, FromJSON, …
datadata DateSpan
#

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.

Constructors

Instances8Eq, Ord, Show, Generic, NFData, ToJSON, …
typetype DecimalMark = Char
#

One of the decimal marks we support: either period or comma.

datadata 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

Instances9Eq, Ord, Read, Show, Generic, NFData, …
datadata EFDay
#

A date which is either exact or flexible. Flexible dates are allowed to be adjusted in certain situations.

Constructors

Instances7Eq, Ord, Show, Generic, NFData, ToJSON, …
classclass HasAmounts a where
#

Types with this class have one or more amounts, which can have display styles applied to them.

Instances19HasAmounts, …
datadata Interval
#
Instances8Eq, Ord, Show, Generic, NFData, ToJSON, …
datadata Journal
#

A journal, containing general ledger transactions; also directives and various other things. This is hledger's main data model.

During parsing, it is used as the type alias ParsedJournal. The jparse* fields are mainly used during parsing and included here for convenience. The list fields described as "in parse order" are usually reversed for efficiency during parsing. After parsing, "journalFinalise" converts ParsedJournal to a finalised Journal, which has all lists correctly ordered, and much data inference and validation applied.

Constructors

Instances9Eq, Show, Generic, Semigroup, NFData, ToJSON, …
datadata Ledger
#

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.

Instances4Show, Generic, ToJSON, Rep
datadata 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

Instances8Eq, Ord, Show, Generic, NFData, FromJSON, …
newtypenewtype MixedAmount
#
Instances15Eq, Num, Ord, Show, Generic, Semigroup, …
datadata 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

Instances2Eq, Show
  • Eq NormalSignDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Show NormalSignDefined in hledger-lib-1.52.4 · Hledger.Data.Types
typetype ParsedJournal = Journal
#

A journal in the process of being parsed, not yet finalised. The data is partial, and list fields are in reverse order.

datadata PayeeDeclarationInfo
#

Extra information found in a payee directive.

Constructors

Instances6Eq, Show, Generic, NFData, ToJSON, Rep
datadata Period
#
Instances8Eq, Ord, Show, Generic, ToJSON, Default, …
datadata PeriodData a
#

A general container for storing data values associated with zero or more contiguous report (sub)periods, and with the (open ended) pre-report period. The report periods are typically all the same length, but need not be.

Report periods are represented only by their start dates, used as the keys of a Map.

Constructors

Instances14Functor, Foldable, Traversable, Foldable1, Eq, Ord, …
datadata PeriodicTransaction
#

A periodic transaction rule, describing a transaction that recurs.

Constructors

Instances6Eq, Show, Generic, NFData, ToJSON, Rep
datadata Posting
#

Constructors

Instances10Eq, Show, Generic, NFData, FromJSON, ToJSON, …
datadata PostingType
#
Instances7Eq, Show, Generic, NFData, FromJSON, ToJSON, …
datadata 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.

Instances8Eq, Ord, Show, Generic, NFData, ToJSON, …
datadata Rounding
#

"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

Instances9Eq, Ord, Read, Show, Generic, NFData, …
datadata SepFormat
#

One of the standard *-separated value file types known by hledger,

Instances3Eq, Ord, Show
  • Eq SepFormatDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord SepFormatDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Show SepFormatDefined in hledger-lib-1.52.4 · Hledger.Data.Types
datadata Side
#
Instances9Eq, Ord, Read, Show, Generic, NFData, …
  • Eq SideDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Ord SideDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Read SideDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Show SideDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • Generic SideDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • NFData SideDefined in hledger-lib-1.52.4 · Hledger.Data.Types
  • FromJSON SideDefined in hledger-lib-1.52.4 · Hledger.Data.Json · orphan
  • ToJSON SideDefined in hledger-lib-1.52.4 · Hledger.Data.Json · orphan
  • type Rep Side = D1 ('MetaData "Side" "Hledger.Data.Types" "hledger-lib-1.52.4-9hXfdej3TnZFrbN8mI8ppA" 'False) (C1 ('MetaCons "L" 'PrefixI 'False) U1 :+: C1 ('MetaCons "R" 'PrefixI 'False) U1)Defined in hledger-lib-1.52.4 · Hledger.Data.Types
datadata SmartDate
#

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 a numeric offset relative to the reference date: (last|this|next) (day|week|month|quarter|year), where "this" means the period containing the reference date.

Or, (last|this|next) weekdayname, where "this" "next".

Or, (last|this|next) monthname, where "this" means the previous 1st if in that month, otherwise the start of the next occurrence of that month.

Instances1Show
  • Show SmartDateDefined in hledger-lib-1.52.4 · Hledger.Data.Types
datadata Status
#

The status of a transaction or posting, recorded with a status mark (nothing, !, or *). What these mean is ultimately user defined.

Instances10Bounded, Enum, Eq, Ord, Show, Generic, …
datadata 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.

Instances6Eq, Show, Generic, NFData, ToJSON, Rep
newtypenewtype TagDeclarationInfo
#

Extra information found in a tag directive.

Constructors

Instances6Eq, Show, Generic, NFData, ToJSON, Rep
datadata TimeclockCode
#
Instances8Eq, Ord, Read, Show, Generic, NFData, …
datadata TimeclockEntry
#
Instances7Eq, Ord, Show, Generic, NFData, ToJSON, …
datadata Transaction
#

Constructors

Instances10Eq, Show, Generic, NFData, FromJSON, ToJSON, …
datadata 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.

Instances6Eq, Show, Generic, NFData, ToJSON, Rep
datadata 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.)

Instances2Eq, Show
datadata ValuationType
#

What kind of value conversion should be done on amounts ? CLI: --value=then|end|now|DATE[,COMM]

Constructors

Instances2Eq, Show
datadata Query
#

A query is a composition of search criteria, which can be used to match postings, transactions, accounts and more.

Constructors

  • 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)

  • DepthAcct Regexp Int

    match if the account matches and account depth is less than or equal to this value (usually 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 compound queries (expr:)

  • Not Query

    negate this match

  • And [Query]

    match if all of these match

  • Or [Query]

    match if any of these match compound queries for transactions (any:, all:) If used in a non transaction-matching context, these are equivalent to And.

  • AnyPosting [Query]

    match if any one posting is matched by all of these

  • AllPostings [Query]

    match if all of one or more postings are matched by all of these

Instances3Eq, Show, Default
  • Eq QueryDefined in hledger-lib-1.52.4 · Hledger.Query
  • Show QueryDefined in hledger-lib-1.52.4 · Hledger.Query
  • Default QueryDefined in hledger-lib-1.52.4 · Hledger.Query
datadata QueryOpt
#

A query option changes a query's/report's behaviour and output in some way.

Constructors

Instances2Eq, Show
  • Eq QueryOptDefined in hledger-lib-1.52.4 · Hledger.Query
  • Show QueryOptDefined in hledger-lib-1.52.4 · Hledger.Query
typetype PrefixedFilePath = FilePath
#

A file path optionally prefixed by a reader name and colon (journal:, csv:, timedot:, etc.). The file path part can also be - meaning standard input.

datadata Reader (m :: Type -> Type)
#

A hledger journal reader is a storage format name, a list of file extensions assumed to be in this format, and an IO action that reads data in this format, returning a Journal.

The journal parser used by the latter is also stored separately for direct use by the journal reader's includedirectivep to parse included files. The type variable m is needed for this parser. Lately it requires an InputOpts, basically to support --old-timeclock.

Instances1Show
  • Show (Reader m)Defined in hledger-lib-1.52.4 · Hledger.Read.Common
classclass HasInputOpts c where
#
Instances2HasInputOpts
datadata InputOpts
#

Constructors

  • InputOpts
    • mformat_ :: Maybe StorageFormat

      a file/storage format to try, unless overridden by a filename prefix. Nothing means try all.

    • mrules_file_ :: Maybe FilePath

      a conversion rules file to use (when reading CSV)

    • aliases_ :: [String]

      account name aliases to apply

    • anon_ :: Bool

      do light obfuscation of the data ? Now corresponds to --obfuscate, not the old --anon flag.

    • new_ :: Bool

      read only new transactions since this file was last read ?

    • new_save_ :: Bool

      save latest new transactions state for next time ?

    • pivot_ :: String

      use the given field's value as the account name

    • forecast_ :: Maybe DateSpan

      span in which to generate forecast transactions

    • auto_posting_tags_ :: Bool

      propagate commodity and account tags to postings ? Can be disabled (for beancount export).

    • verbose_tags_ :: Bool

      add user-visible tags when generating/modifying transactions & postings ?

    • reportspan_ :: DateSpan

      a dirty hack keeping the query dates in InputOpts. This rightfully lives in ReportSpec, but is duplicated here.

    • auto_ :: Bool

      generate extra postings according to auto posting rules ?

    • infer_equity_ :: Bool

      infer equity conversion postings from costs ?

    • infer_costs_ :: Bool

      infer costs from equity conversion postings ? distinct from BalancingOpts{infer_balancing_costs_}

    • balancingopts_ :: BalancingOpts

      options for transaction balancing

    • strict_ :: Bool

      do extra correctness checks ?

    • _defer :: Bool

      internal flag: postpone checks, because we are processing multiple files ?

    • _ioDay :: Day

      today's date, for use with forecast transactions XXX this duplicates _rsDay, and should eventually be removed when it's not needed anymore.

    • _oldtimeclock :: Bool

      parse with the old timeclock pairing rules?

Instances5Eq, Ord, Show, HasBalancingOpts, HasInputOpts

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.

A simple balance report. It has:

  1. 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

  1. the total of all amounts

A budget report tracks expected and actual changes per account and subperiod. Each table cell has an actual change amount and/or a budget goal amount.

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.

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:

  1. a list of each column's period (date span)

  2. 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

  1. the column totals, and the overall grand total (or zero for cumulative/historical reports) and grand average.

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.

datadata 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.

Instances3Eq, Show, Default
datadata 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.

Instances3Eq, Show, Default
classclass 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:
Example5 expressions
import Lens.Micro (set)_rsQuery <$> setEither querystring ["assets"] defreportspecRight (Acct (RegexpCI "assets"))_rsQuery <$> setEither querystring ["(assets"] defreportspecLeft "This regular expression is invalid or unsupported, please correct it:\n(assets"_rsQuery $ set querystring ["assets"] defreportspecAcct (RegexpCI "assets")_rsQuery $ set period (MonthPeriod 2021 08) defreportspecDate DateSpan 2021-08

XXX testing error output isn't working since adding color to it: > import System.Environment > setEnv NO_COLOR "1" >> return (_rsQuery $ set querystring ["(assets"] defreportspec) *** Exception: Error: Updating ReportSpec failed: try using overEither instead of over or setEither instead of set

Methods

Instances3HasReportOpts
classclass HasReportOptsNoUpdate c where
#
Instances3HasReportOptsNoUpdate
datadata 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

Instances4Show, Default, HasReportOpts, HasReportOptsNoUpdate
datadata 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

Instances5Show, Default, HasReportOpts, HasReportOptsNoUpdate, HasReportSpec
datadata CBCSubreportSpec a
#

Description of one subreport within a compound balance report. Part of a CompoundBalanceCommandSpec, but also used in hledger-lib.

Constructors

datadata 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.

Instances6Functor, Show, Generic, ToJSON, HasAmounts, Rep
datadata DisplayName
#

A full name, display name, and indent level for an account.

Instances4Eq, Ord, Show, ToJSON
  • Eq DisplayNameDefined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • Ord DisplayNameDefined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • Show DisplayNameDefined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • ToJSON DisplayNameDefined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
datadata 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:

  1. a list of each column's period (date span)

  2. 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 BalanceAccumulation and 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

  1. the column totals, and the overall grand total (or zero for cumulative/historical reports) and grand average.

Instances8Bifunctor, Functor, Show, Generic, ToJSON, HasAmounts, …
datadata PeriodicReportRow a b
#
Instances8Bifunctor, Functor, Show, Generic, Semigroup, ToJSON, …
datadata GhcDebugMode
#

Whether ghc-debug support is included in this build, and if so, how it will behave. When hledger is built with the ghcdebug cabal flag (off by default, because of extra deps), it can listen (on unix ?) for connections from ghc-debug clients like ghc-debug-brick, for pausing/resuming the program and inspecting memory usage and profile information.

With a ghc-debug-supporting build, ghc-debug can be enabled by running hledger with a negative --debug level. There are three different modes: --debug=-1 - run normally (can be paused/resumed by a ghc-debug client), --debug=-2 - pause and await client commands at program start (not useful currently), --debug=-3 - pause and await client commands at program end.

Instances3Eq, Ord, Show
datadata YNA
#
Instances2Eq, Show
  • Eq YNADefined in hledger-lib-1.52.4 · Hledger.Utils.IO
  • Show YNADefined in hledger-lib-1.52.4 · Hledger.Utils.IO
datadata FinalParseError' e
#

A type representing "final" parse errors that cannot be backtracked from and are guaranteed to halt parsing. The anti-backtracking behaviour is implemented by an ExceptT layer in the parser's monad stack, using this type as the ExceptT error type.

We have three goals for this type: (1) it should be possible to convert any parse error into a "final" parse error, (2) it should be possible to take a parse error thrown from an include file and re-throw it in the context of the parent file, and (3) the pretty-printing of "final" parse errors should be consistent with that of ordinary parse errors, but should also report the stack of parent files when errors are thrown from included files.

In order to pretty-print a "final" parse error (goal 3), it must be bundled with include filepaths and its full source text. When a "final" parse error is thrown from within a parser, we do not have access to the full source, so we must hold the parse error (FinalParseError) until it can be combined with the full source (and any parent file paths) by the parser's caller (FinalParseErrorBundle).

Instances3Show, Semigroup, Monoid
datadata FinalParseErrorBundle' e
#

A type bundling a ParseError with its full source text, filepath, and stack of include files. Suitable for pretty-printing.

Megaparsec's ParseErrorBundle type already bundles a parse error with its full source text and filepath, so we just add a stack of include files.

Instances1Show

Custom error data for hledger parsers. Specialised for a Text parse stream. ReparseableTextParseErrorData ?

Instances5Eq, Show, ShowErrorComponent, Ord
datadata SourceExcerpt
#

A fragment of source suitable for "re-parsing". The purpose of this data type is to preserve the content and source position of the excerpt so that parse errors raised during "re-parsing" may properly reference the original source.

typetype 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.

datadata Regexp
#

Regular expression. Extended regular expression-ish syntax ? But does not support eg (?i) syntax.

Instances8Eq, Ord, Read, Show, NFData, ToJSON, …
typetype Replacement = String
#

A replacement pattern. May include numeric backreferences (N).

datadata SourcePos
#

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

Instances10Eq, Data, Ord, Read, Show, Generic, …
typetype Pid = CPid
#

The platform specific type for a process identifier.

This is always an integral type. Width and signedness are platform specific.

datadata CmdSpec
#

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 FilePath argument names the executable, and is interpreted according to the platform's standard policy for searching for executables. Specifically:

    • on Unix systems the execvp(3) semantics is used, where if the executable filename does not contain a slash (/) then the PATH environment variable is searched for the executable.

    • on Windows systems the Win32 CreateProcess semantics is used. Briefly: if the filename does not contain a path, then the directory containing the parent executable is searched, followed by the current directory, then some standard locations, and finally the current PATH. An .exe extension is added if the filename does not already have an extension. For full details see the documentation for the Windows SearchPath API.

    Windows does not have a mechanism for passing multiple arguments. When using RawCommand on Windows, the command line is serialised into a string, with arguments quoted separately. Command line parsing is up individual programs, so the default behaviour may not work for some programs. If you are not getting the desired results, construct the command line yourself and use ShellCommand.

Instances3Eq, Show, IsString
  • Eq CmdSpecDefined in process-1.6.30.0 · System.Process.Common
  • Show CmdSpecDefined in process-1.6.30.0 · System.Process.Common
  • IsString CmdSpecDefined in process-1.6.30.0 · System.Process.Common

    construct a ShellCommand from a string literal

datadata CreateProcess
#

Constructors

  • CreateProcess
    • cmdspec :: CmdSpec

      Executable & arguments, or shell command. If cwd is Nothing, relative paths are resolved with respect to the current working directory. If cwd is provided, it is implementation-dependent whether relative paths are resolved with respect to cwd or the current working directory, so absolute paths should be used to ensure portability.

    • cwd :: Maybe FilePath

      Optional path to the working directory for the new process

    • env :: Maybe [(String, String)]

      Optional environment (otherwise inherit from the current process)

    • std_in :: StdStream

      How to determine stdin

    • std_out :: StdStream

      How to determine stdout

    • std_err :: StdStream

      How to determine stderr XXX verify what happens with fds in nodejs child processes

    • close_fds :: Bool

      Close all file descriptors except stdin, stdout and stderr in the new process (on Windows, only works if std_in, std_out, and std_err are all Inherit). This implementation will call close on every fd from 3 to the maximum of open files, which can be slow for high maximum of open files.

    • create_group :: Bool

      Create a new process group. On JavaScript this also creates a new session.

    • delegate_ctlc :: Bool

      Delegate control-C handling. Use this for interactive console processes to let them handle control-C themselves (see below for details).

    • detach_console :: Bool

      Use the windows DETACHED_PROCESS flag when creating the process; does nothing on other platforms.

    • create_new_console :: Bool

      Use the windows CREATE_NEW_CONSOLE flag when creating the process; does nothing on other platforms.

      Default: False

    • new_session :: Bool

      Use posix setsid to start the new process in a new session; starts process in a new session on JavaScript; does nothing on other platforms.

    • child_group :: Maybe GroupID

      Use posix setgid to set child process's group id; works for JavaScript when system running nodejs is posix. does nothing on other platforms.

      Default: Nothing

    • child_user :: Maybe UserID

      Use posix setuid to set child process's user id; works for JavaScript when system running nodejs is posix. does nothing on other platforms.

      Default: Nothing

    • use_process_jobs :: Bool

      On Windows systems this flag indicates that we should wait for the entire process tree to finish before unblocking. On POSIX systems this flag is ignored. See $exec-on-windows for details.

      Default: False

Instances2Eq, Show
datadata 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.

datadata StdStream
#

Constructors

  • Inherit

    Inherit Handle from parent

  • UseHandle Handle

    Use the supplied Handle

  • CreatePipe

    Create a new pipe. The returned Handle will use the default encoding and newline translation mode (just like Handles created by openFile).

  • 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 Handle that writes to /dev/null.

Instances2Eq, Show
  • Eq StdStreamDefined in process-1.6.30.0 · System.Process.Common
  • Show StdStreamDefined in process-1.6.30.0 · System.Process.Common
datadata 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.

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.

Instances3Eq, Read, Show
datadata TestTree
#

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.

datadata Timeout
#

Timeout to be applied to individual tests.

Constructors

Instances4Eq, Ord, Show, IsOption
  • Eq TimeoutDefined in tasty-1.5.4 · Test.Tasty.Options.Core

    Auto-derived instance, just to allow storing in a Data.Map.Map and such.

  • Ord TimeoutDefined in tasty-1.5.4 · Test.Tasty.Options.Core

    Auto-derived instance, just to allow storing in a Data.Map.Map and such.

  • Show TimeoutDefined in tasty-1.5.4 · Test.Tasty.Options.Core
  • IsOption TimeoutDefined in tasty-1.5.4 · Test.Tasty.Options.Core
classclass Assertable t where
#

Deprecated. This class or type seems dubious. If you have a good use case for it, please create an issue for tasty. Otherwise, it may be removed in a future version.

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.

Methods

Instances4Assertable
typetype Assertion = IO ()
#

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.

typetype AssertionPredicate = IO Bool
#

Deprecated. This class or type seems dubious. If you have a good use case for it, please create an issue for tasty. Otherwise, it may be removed in a future version.

The result of an assertion that hasn't been evaluated yet.

Most test cases follow the following steps:

  1. Do some processing or an action.

  2. 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:

  1. Write data to a file.

  2. Read data from a file, evaluate conditions.

  3. Clean up the file.

  4. Assert that the side effects of the read operation meet certain conditions.

  5. Assert that the conditions evaluated in step 2 are met.

datadata Text
#

A space efficient, packed, unboxed Unicode text type.

Instances77IsList, Eq, Data, Read, Show, Semigroup, …
  • IsList TextDefined in text-2.1.4 · Data.Text · orphan

    Performs replacement on invalid scalar values:

    Example2 expressions
    :set -XOverloadedLists['\55555'] :: Text"\65533"
  • Eq CsvRulesDefined in hledger-lib-1.52.4 · Hledger.Read.RulesReader
  • Eq TextDefined in text-2.1.4 · Data.Text · orphan
  • Data TextDefined in text-2.1.4 · Data.Text · orphan

    This instance preserves data abstraction at the cost of inefficiency. We omit reflection services for the sake of data abstraction.

    This instance was created by copying the updated behavior of Data.Set.Set and Data.Map.Data.Map.Map. If you feel a mistake has been made, please feel free to submit improvements.

    The original discussion is archived here: could we get a Data instance for Data.Text.Text?

    The followup discussion that changed the behavior of Set and Data.Map.Map is archived here: Proposal: Allow gunfold for Data.Map, ...

  • Ord TextDefined in text-2.1.4 · Data.Text · orphan
  • Read TextDefined in text-2.1.4 · Data.Text · orphan
  • Show CsvRulesDefined in hledger-lib-1.52.4 · Hledger.Read.RulesReader
  • Show TextDefined in text-2.1.4 · Data.Text.Show · orphan
  • IsString TextDefined in text-2.1.4 · Data.Text · orphan

    Performs replacement on invalid scalar values:

    Example2 expressions
    :set -XOverloadedStrings"\55555" :: Text"\65533"
  • Semigroup TextDefined in text-2.1.4 · Data.Text · orphan

    Beware: stimes will crash if the given number does not fit into an Int.

  • Monoid TextDefined in text-2.1.4 · Data.Text · orphan
  • PrintfArg TextDefined in text-2.1.4 · Data.Text · orphan
  • NFData TextDefined in text-2.1.4 · Data.Text · orphan
  • Binary TextDefined in text-2.1.4 · Data.Text · orphan
  • Hashable TextDefined in hashable-1.5.1.0 · Data.Hashable.Class
  • FromJSON TextDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON
  • FromJSONKey TextDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON
  • ToJSON TextDefined in aeson-2.2.5.1 · Data.Aeson.Types.ToJSON
  • ToJSONKey TextDefined in aeson-2.2.5.1 · Data.Aeson.Types.ToJSON
  • ToMarkup TextDefined in blaze-markup-0.8.3.0 · Text.Blaze
  • ToValue TextDefined in blaze-markup-0.8.3.0 · Text.Blaze
  • FoldCase TextDefined in case-insensitive-1.2.1.0 · Data.CaseInsensitive.Internal
  • Extract TextDefined in regex-base-0.94.0.3 · Text.Regex.Base.RegexLike
  • Uncons TextDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.NewDFA.Uncons
  • Pretty TextDefined in prettyprinter-1.7.2 · Prettyprinter.Internal

    Automatically converts all newlines to line.

    Example1 expression
    pretty ("hello\nworld" :: Text)helloworld

    Note that line can be undone by group:

    Example1 expression
    group (pretty ("hello\nworld" :: Text))hello world

    Manually use hardline if you definitely want newlines.

  • Chunk TextDefined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
  • QueryKeyLike TextDefined in http-types-0.12.6 · Network.HTTP.Types.QueryLike
  • QueryValueLike TextDefined in http-types-0.12.6 · Network.HTTP.Types.QueryLike
  • FromFormKey TextDefined in http-api-data-0.7 · Web.Internal.FormUrlEncoded
  • ToFormKey TextDefined in http-api-data-0.7 · Web.Internal.FormUrlEncoded
  • FromHttpApiData TextDefined in http-api-data-0.7 · Web.Internal.HttpApiData
  • ToHttpApiData TextDefined in http-api-data-0.7 · Web.Internal.HttpApiData
  • Serialise TextDefined in serialise-0.2.6.1 · Codec.Serialise.Class
  • Stream TextDefined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • TraversableStream TextDefined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • VisualStream TextDefined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • FromField TextDefined in cassava-0.5.4.1 · Data.Csv.Conversion

    Assumes UTF-8 encoding. Fails on invalid byte sequences.

  • ToField TextDefined in cassava-0.5.4.1 · Data.Csv.Conversion

    Uses UTF-8 encoding.

  • HasChars TextDefined in doclayout-0.6 · Text.DocLayout.HasChars
  • ToHtml TextDefined in lucid-2.11.20260427 · Lucid.Base
  • HasAmounts AccountTransactionsReportItemDefined in hledger-lib-1.52.4 · Hledger.Reports.AccountTransactionsReport · orphan
  • HasAmounts BalanceReportItemDefined in hledger-lib-1.52.4 · Hledger.Reports.BalanceReport · orphan
  • HasAmounts PostingsReportItemDefined in hledger-lib-1.52.4 · Hledger.Reports.PostingsReport · orphan
  • ToCss TextDefined in shakespeare-2.2.0 · Text.Internal.Css
  • ToHamletData TextDefined in shakespeare-2.2.0 · Text.Hamlet.Runtime
  • RawJS TextDefined in shakespeare-2.2.0 · Text.Julius
  • ToJavascript TextDefined in shakespeare-2.2.0 · Text.Julius
  • ToMessage TextDefined in shakespeare-2.2.0 · Text.Shakespeare.I18N
  • ToText TextDefined in shakespeare-2.2.0 · Text.Shakespeare.Text
  • Anon TextDefined in hledger-1.52.4 · Hledger.Cli.Anon
  • Lift TextDefined in text-2.1.4 · Data.Text · orphan
  • Strict Text TextDefined in strict-0.5.1 · Data.Strict.Classes
  • RegexLike Regex TextDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Text · orphan
  • PrettyAnn ann TextDefined in prettyprinter-1.7.2 · Prettyprinter.Internal
  • Term Text AttributeDefined in lucid-2.11.20260427 · Lucid.Base

    Some terms (like style_, title_) can be used for attributes as well as elements.

  • TermRaw Text AttributeDefined in lucid-2.11.20260427 · Lucid.Base

    Some termRaws (like style_, title_) can be used for attributes as well as elements.

  • RenderMessage master TextDefined in shakespeare-2.2.0 · Text.Shakespeare.I18N
  • Monad m => Stream Text m CharDefined in parsec-3.1.18.0 · Text.Parsec.Prim
  • RegexContext Regex Text TextDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Text · orphan
  • RegexMaker Regex CompOption ExecOption TextDefined in regex-tdfa-1.3.2.6 · Text.Regex.TDFA.Text · orphan
  • (Monad m, a ~ ()) => TermRaw Text (HtmlT m a)Defined in lucid-2.11.20260427 · Lucid.Base

    Given children immediately, just use that and expect no attributes.

  • a ~ Text => IsString (Parser a)Defined in attoparsec-0.14.4 · Data.Attoparsec.Text.Internal · orphan
  • Stream (NoShareInput Text)Defined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • Stream (ShareInput Text)Defined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • ToAttributes [(Text, Text)]Defined in shakespeare-2.2.0 · Text.Hamlet
  • Ord (ParseError Text HledgerParseErrorData)Defined in hledger-lib-1.52.4 · Hledger.Utils.Parse
  • ToAttributes (Text, Text)Defined in shakespeare-2.2.0 · Text.Hamlet
  • HasAmounts b => HasAmounts (Text, PeriodicReport a b, Bool)Defined in hledger-lib-1.52.4 · Hledger.Reports.ReportTypes
  • type Item Text = CharDefined in text-2.1.4 · Data.Text · orphan
  • type State Text = BufferDefined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
  • type ChunkElem Text = CharDefined in attoparsec-0.14.4 · Data.Attoparsec.Internal.Types
  • type Token Text = Token (ShareInput Text)Defined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • type Token (NoShareInput Text) = CharDefined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • type Token (ShareInput Text) = CharDefined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • type Tokens Text = Tokens (ShareInput Text)Defined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • type Tokens (NoShareInput Text) = TextDefined in megaparsec-9.5.0 · Text.Megaparsec.Stream
  • type Tokens (ShareInput Text) = TextDefined in megaparsec-9.5.0 · Text.Megaparsec.Stream
datadata CalendarDiffDays
#
Instances15Eq, Data, Read, Show, Generic, Semigroup, …
newtypenewtype Day
#

The Modified Julian Day is a standard count of days, with zero being the day 1858-11-17.

Instances25Enum, Eq, Data, Ord, Read, Show, …
  • Enum DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • Eq DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • Data DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • Ord DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • Read DayDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan
  • Show DayDefined in time-1.16.0.1 · Data.Time.Calendar.Gregorian · orphan
  • Ix DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • Generic DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • NFData DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • Hashable DayDefined in time-compat-1.9.9 · Data.Time.Orphans · orphan
  • DayPeriod DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • FormatTime DayDefined in time-1.16.0.1 · Data.Time.Format.Format.Instances · orphan
  • ParseTime DayDefined in time-1.16.0.1 · Data.Time.Format.Parse.Instances · orphan
  • ISO8601 DayDefined in time-1.16.0.1 · Data.Time.Format.ISO8601

    yyyy-mm-dd [ISO 8601:2004(E) sec. 4.1.2.2 extended format]

  • FromJSON DayDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON
  • FromJSONKey DayDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON
  • ToJSON DayDefined in aeson-2.2.5.1 · Data.Aeson.Types.ToJSON
  • ToJSONKey DayDefined in aeson-2.2.5.1 · Data.Aeson.Types.ToJSON
  • FromFormKey DayDefined in http-api-data-0.7 · Web.Internal.FormUrlEncoded
  • ToFormKey DayDefined in http-api-data-0.7 · Web.Internal.FormUrlEncoded
  • FromHttpApiData DayDefined in http-api-data-0.7 · Web.Internal.HttpApiData
    Example1 expression
    toGregorian <$> parseUrlPiece "2016-12-01"Right (2016,12,1)
  • ToHttpApiData DayDefined in http-api-data-0.7 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece (fromGregorian 2015 10 03)"2015-10-03"
  • HasAmounts PostingsReportItemDefined in hledger-lib-1.52.4 · Hledger.Reports.PostingsReport · orphan
  • Lift DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • type Rep Day = D1 ('MetaData "Day" "Data.Time.Calendar.Days" "time-1.16.0.1-dda8" 'True) (C1 ('MetaCons "ModifiedJulianDay" 'PrefixI 'True) (S1 ('MetaSel ('Just "toModifiedJulianDay") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Integer)))Defined in time-1.16.0.1 · Data.Time.Calendar.Days
classclass Ord p => DayPeriod p where
#

The class of types which can be represented as a period of days.

Methods

Instances4DayPeriod
  • DayPeriod DayDefined in time-1.16.0.1 · Data.Time.Calendar.Days
  • DayPeriod MonthDefined in time-1.16.0.1 · Data.Time.Calendar.Month
  • DayPeriod QuarterDefined in time-1.16.0.1 · Data.Time.Calendar.Quarter
  • DayPeriod YearDefined in time-1.16.0.1 · Data.Time.Calendar.Gregorian · orphan
typetype MonthOfYear = Int
#

Month of year, in range 1 (January) to 12 (December).

typetype Year = Integer
#

Year of Common Era (when positive).

datadata DayOfWeek
#
Instances20Enum, Eq, Data, Ord, Read, Show, …
newtypenewtype DiffTime
#

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.

Instances17Enum, Eq, Fractional, Data, Num, Ord, …
  • Enum DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Eq DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Fractional DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Data DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Num DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Ord DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Read DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Real DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • RealFrac DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Show DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • NFData DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
  • Hashable DiffTimeDefined in time-compat-1.9.9 · Data.Time.Orphans · orphan
  • FormatTime DiffTimeDefined in time-1.16.0.1 · Data.Time.Format.Format.Instances · orphan
  • ParseTime DiffTimeDefined in time-1.16.0.1 · Data.Time.Format.Parse.Instances · orphan
  • FromJSON DiffTimeDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON

    This instance includes a bounds check to prevent maliciously large inputs to fill up the memory of the target system. You can newtype Scientific and provide your own instance using withScientific if you want to allow larger inputs.

  • ToJSON DiffTimeDefined in aeson-2.2.5.1 · Data.Aeson.Types.ToJSON
  • Lift DiffTimeDefined in time-1.16.0.1 · Data.Time.Clock.Internal.DiffTime
newtypenewtype NominalDiffTime
#

This is a length of time, as measured by UTC. It has a precision of one picosecond (10^-12 s).

Conversion functions such as fromInteger and realToFrac will treat it as seconds. For example, (0.010 :: NominalDiffTime) corresponds to 10 milliseconds.

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.

Instances21Enum, Eq, Fractional, Data, Num, Ord, …
datadata UTCTime
#

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

Instances22Eq, Data, Ord, Read, Show, Generic, …
newtypenewtype 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.

Instances12Eq, Data, Ord, Read, Show, Generic, …
classclass FormatTime t where
#
Instances16FormatTime, …
datadata TimeLocale
#

Constructors

Instances4Eq, Ord, Show, Hashable
classclass ParseTime t where
#

The class of types which can be parsed given a UNIX-style time format string.

Instances15ParseTime, …
datadata CalendarDiffTime
#
Instances15Eq, Data, Read, Show, Generic, Semigroup, …
datadata LocalTime
#

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.

Instances21Eq, Data, Ord, Read, Show, Generic, …
datadata TimeOfDay
#

Time of day as represented in hour, minute and second (with picoseconds), typically used to express local time of day.

TimeOfDay 24 0 0 is considered invalid for the purposes of makeTimeOfDayValid, as well as reading and parsing, but valid for ISO 8601 parsing in Data.Time.Format.ISO8601.

Constructors

  • TimeOfDay
    • todHour :: Int

      range 0 - 23

    • todMin :: Int

      range 0 - 59

    • todSec :: Pico

      Note that 0 <= todSec < 61, accommodating leap seconds. Any local minute may have a leap second, since leap seconds happen in all zones simultaneously

Instances19Eq, Data, Ord, Read, Show, Generic, …
datadata TimeZone
#

A TimeZone is a whole number of minutes offset from UTC, together with a name and a "just for summer" flag.

Constructors

Instances13Eq, Data, Ord, Read, Show, Generic, …
datadata ZonedTime
#

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.

Instances18Data, Read, Show, Generic, NFData, FormatTime, …
  • Data ZonedTimeDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.ZonedTime
  • Read ZonedTimeDefined in time-1.16.0.1 · Data.Time.Format.Parse · orphan

    This only works for a zonedTimeZone in ±HHMM format, single-letter military time-zones, and these time-zones: "UTC", "UT", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT", per RFC 822 section 5.

  • Show ZonedTimeDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.ZonedTime

    For the time zone, this only shows the name, or offset if the name is empty.

  • Generic ZonedTimeDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.ZonedTime
  • NFData ZonedTimeDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.ZonedTime
  • FormatTime ZonedTimeDefined in time-1.16.0.1 · Data.Time.Format.Format.Instances · orphan
  • ParseTime ZonedTimeDefined in time-1.16.0.1 · Data.Time.Format.Parse.Instances · orphan
  • ISO8601 ZonedTimeDefined in time-1.16.0.1 · Data.Time.Format.ISO8601

    yyyy-mm-ddThh:mm:ss[.ss]±hh:mm [ISO 8601:2004(E) sec. 4.3.2 extended format]

  • FromJSON ZonedTimeDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON

    Supported string formats:

    YYYY-MM-DD HH:MMZ YYYY-MM-DD HH:MM:SSZ YYYY-MM-DD HH:MM:SS.SSSZ

    The first space may instead be a T, and the second space is optional. The Z represents UTC. The Z may be replaced with a time zone offset of the form +0000 or -08:00, where the first two digits are hours, the : is optional and the second two digits (also optional) are minutes.

  • FromJSONKey ZonedTimeDefined in aeson-2.2.5.1 · Data.Aeson.Types.FromJSON
  • ToJSON ZonedTimeDefined in aeson-2.2.5.1 · Data.Aeson.Types.ToJSON
  • ToJSONKey ZonedTimeDefined in aeson-2.2.5.1 · Data.Aeson.Types.ToJSON
  • FromFormKey ZonedTimeDefined in http-api-data-0.7 · Web.Internal.FormUrlEncoded
  • ToFormKey ZonedTimeDefined in http-api-data-0.7 · Web.Internal.FormUrlEncoded
  • FromHttpApiData ZonedTimeDefined in http-api-data-0.7 · Web.Internal.HttpApiData
    Example1 expression
    parseUrlPiece "2015-10-03T14:55:01+0000" :: Either Text ZonedTimeRight 2015-10-03 14:55:01 +0000
    Example1 expression
    parseQueryParam "2016-12-31T01:00:00Z" :: Either Text ZonedTimeRight 2016-12-31 01:00:00 +0000
  • ToHttpApiData ZonedTimeDefined in http-api-data-0.7 · Web.Internal.HttpApiData
    Example1 expression
    toUrlPiece $ ZonedTime (LocalTime (fromGregorian 2015 10 03) (TimeOfDay 14 55 51.001)) utc"2015-10-03T14:55:51.001Z"
    Example1 expression
    toUrlPiece $ ZonedTime (LocalTime (fromGregorian 2015 10 03) (TimeOfDay 14 55 51.001)) (TimeZone 120 True "EET")"2015-10-03T14:55:51.001+02:00"
  • Lift ZonedTimeDefined in time-1.16.0.1 · Data.Time.LocalTime.Internal.ZonedTime
  • type Rep ZonedTime = D1 ('MetaData "ZonedTime" "Data.Time.LocalTime.Internal.ZonedTime" "time-1.16.0.1-dda8" 'False) (C1 ('MetaCons "ZonedTime" 'PrefixI 'True) (S1 ('MetaSel ('Just "zonedTimeToLocalTime") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 LocalTime) :*: S1 ('MetaSel ('Just "zonedTimeZone") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 TimeZone)))Defined in time-1.16.0.1 · Data.Time.LocalTime.Internal.ZonedTime
datadata Maybe a
#

The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a), or it is empty (represented as Nothing). 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.

Constructors

Instances103Monad, Functor, MonadFix, MonadFail, Applicative, Foldable, …
datadata Char
#

The character type Char represents Unicode codespace and its elements are code points as in definitions D9 and D10 of the Unicode Standard.

Character literals in Haskell are single-quoted: 'Q', 'Я' or 'Ω'. To represent a single quote itself use '\'', and to represent a backslash use '\\'. The full grammar can be found in the section 2.6 of the Haskell 2010 Language Report.

To specify a character by its code point one can use decimal, hexadecimal or octal notation: '\65', '\x41' and '\o101' are all alternative forms of 'A'. The largest code point is '\x10ffff'.

There is a special escape syntax for ASCII control characters:

Escape

Alternatives

Meaning

'\NUL'

'\0'

null character

'\SOH'

'\1'

start of heading

'\STX'

'\2'

start of text

'\ETX'

'\3'

end of text

'\EOT'

'\4'

end of transmission

'\ENQ'

'\5'

enquiry

'\ACK'

'\6'

acknowledge

'\BEL'

'\7'

,

'\a'

bell (alert)

'\BS'

'\8'

,

'\b'

backspace

'\HT'

'\9'

,

'\t'

horizontal tab

'\LF'

'\10'

,

'\n'

line feed (new line)

'\VT'

'\11'

,

'\v'

vertical tab

'\FF'

'\12'

,

'\f'

form feed

'\CR'

'\13'

,

'\r'

carriage return

'\SO'

'\14'

shift out

'\SI'

'\15'

shift in

'\DLE'

'\16'

data link escape

'\DC1'

'\17'

device control 1

'\DC2'

'\18'

device control 2

'\DC3'

'\19'

device control 3

'\DC4'

'\20'

device control 4

'\NAK'

'\21'

negative acknowledge

'\SYN'

'\22'

synchronous idle

'\ETB'

'\23'

end of transmission block

'\CAN'

'\24'

cancel

'\EM'

'\25'

end of medium

'\SUB'

'\26'

substitute

'\ESC'

'\27'

escape

'\FS'

'\28'

file separator

'\GS'

'\29'

group separator

'\RS'

'\30'

record separator

'\US'

'\31'

unit separator

'\SP'

'\32'

,

' '

space

'\DEL'

'\127'

delete

Data.Char provides utilities to work with Char.

Instances106Bounded, Enum, Data, Read, Ix, Storable, …
datadata List a
#

The builtin linked list type.

In Haskell, lists are one of the most important data types as they are often used analogous to loops in imperative programming languages. These lists are singly linked, which makes them unsuited for operations that require \mathcal{O}(1) access. Instead, they are intended to be traversed.

You can use List a or [a] in type signatures:

length :: [a] -> Int

or

length :: List a -> Int

They are fully equivalent, and List a will be normalised to [a].

Usage

Lists are constructed recursively using the right-associative constructor operator (or cons) (:) :: a -> [a] -> [a], which prepends an element to a list, and the empty list [].

(1 : 2 : 3 : []) == (1 : (2 : (3 : []))) == [1, 2, 3]

Lists can also be constructed using list literals of the form [x_1, x_2, ..., x_n] which are syntactic sugar and, unless -XOverloadedLists is enabled, are translated into uses of (:) and []

String literals, like "I 💜 hs", are translated into Lists of characters, ['I', ' ', '💜', ' ', 'h', 's'].

Implementation

Internally and in memory, all the above are represented like this, with arrows being pointers to locations in memory.

╭───┬───┬──╮   ╭───┬───┬──╮   ╭───┬───┬──╮   ╭────╮
│(:)│   │ ─┼──>│(:)│   │ ─┼──>│(:)│   │ ─┼──>│ [] │
╰───┴─┼─┴──╯   ╰───┴─┼─┴──╯   ╰───┴─┼─┴──╯   ╰────╯
      v              v              v
      1              2              3
Examples
>>> ['H', 'a', 's', 'k', 'e', 'l', 'l']
"Haskell"
>>> 1 : [4, 1, 5, 9]
[1,4,1,5,9]
>>> [] : [] : []
[[],[]]
Instances155Monad, Functor, MonadFix, MonadFail, Applicative, Foldable, …