Text.Printf (original) (raw)
printf :: PrintfType r => String -> r Source #
Format a variable number of arguments with the C-style formatting string.
>>>
**printf "%s, %d, %.4f" "hello" 123 pi** **
**hello, 123, 3.1416
The return value is either [String](Data-String.html#t:String "Data.String")
or (`[IO](Prelude.html#t:IO "Prelude")` a)
(which should be (`[IO](Prelude.html#t:IO "Prelude")` ())
, 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](Text-Printf.html#v:printf "Text.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](Text-Printf.html#v:printf "Text.Printf")
is driven by the argument type; formatting is type specific. The types formatted by [printf](Text-Printf.html#v:printf "Text.Printf")
"out of the box" are:
[Integral](Prelude.html#t:Integral "Prelude")
types, including[Char](Data-Char.html#t:Char "Data.Char")
[String](Data-String.html#t:String "Data.String")
[RealFloat](Prelude.html#t:RealFloat "Prelude")
types
[printf](Text-Printf.html#v:printf "Text.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](Prelude.html#t:RealFloat "Prelude")
types is currently a bit different from that of C printf(3)
, conforming instead to [showEFloat](/package/ghc-internal-9.1201.0/docs/GHC-Internal-Numeric.html#v:showEFloat "GHC.Internal.Numeric")
,[showFFloat](/package/ghc-internal-9.1201.0/docs/GHC-Internal-Numeric.html#v:showFFloat "GHC.Internal.Numeric")
and [showGFloat](/package/ghc-internal-9.1201.0/docs/GHC-Internal-Numeric.html#v:showGFloat "GHC.Internal.Numeric")
(and their alternate versions [showFFloatAlt](/package/ghc-internal-9.1201.0/docs/GHC-Internal-Numeric.html#v:showFFloatAlt "GHC.Internal.Numeric")
and[showGFloatAlt](/package/ghc-internal-9.1201.0/docs/GHC-Internal-Numeric.html#v:showGFloatAlt "GHC.Internal.Numeric")
). 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](Text-Printf.html#v:printf "Text.Printf")
never uses the default "6-digit" precision used by C printf. - Haskell
[printf](Text-Printf.html#v:printf "Text.Printf")
treats the "precision" specifier as indicating the number of digits after the decimal point. - Haskell
[printf](Text-Printf.html#v:printf "Text.Printf")
prints the exponent of e-format numbers without a gratuitous plus sign, and with the minimum possible number of digits. - Haskell
[printf](Text-Printf.html#v:printf "Text.Printf")
will place a zero after a decimal point when possible.
This [printf](Text-Printf.html#v:printf "Text.Printf")
can be extended to format types other than those provided for by default. This is done by instantiating [PrintfArg](Text-Printf.html#t:PrintfArg "Text.Printf")
and providing a [formatArg](Text-Printf.html#v:formatArg "Text.Printf")
for the type. It is possible to provide a [parseFormat](Text-Printf.html#v:parseFormat "Text.Printf")
to process type-specific modifiers, but the default instance is usually the best choice.
For example:
instance PrintfArg () where formatArg x fmt | fmtChar (vFmt 'U' fmt) == 'U' = formatString "()" (fmt { fmtChar = 's', fmtPrecision = Nothing }) formatArg _ fmt = errorBadFormat $ fmtChar fmt
main :: IO () main = printf "[%-3.1U]\n" ()
prints "[() ]
". Note the use of [formatString](Text-Printf.html#v:formatString "Text.Printf")
to take care of field formatting specifications in a convenient way.
class PrintfArg a where Source #
Typeclass of [printf](Text-Printf.html#v:printf "Text.Printf")
-formattable values. The [formatArg](Text-Printf.html#v:formatArg "Text.Printf")
method takes a value and a field format descriptor and either fails due to a bad descriptor or produces a [ShowS](Prelude.html#t:ShowS "Prelude")
as the result. The default [parseFormat](Text-Printf.html#v:parseFormat "Text.Printf")
expects no modifiers: this is the normal case. Minimal instance: [formatArg](Text-Printf.html#v:formatArg "Text.Printf")
.
How to handle the sign of a numeric field. These are mutually exclusive, with [SignPlus](Text-Printf.html#v:SignPlus "Text.Printf")
taking precedence.
Since: base-4.7.0.0
Handling Type-specific Modifiers
In the unlikely case that modifier characters of some kind are desirable for a user-provided type, a [ModifierParser](Text-Printf.html#t:ModifierParser "Text.Printf")
can be provided to process these characters. The resulting modifiers will appear in the [FieldFormat](Text-Printf.html#t:FieldFormat "Text.Printf")
for use by the type-specific formatter.
The "format parser" walks over argument-type-specific modifier characters to find the primary format character. This is the type of its result.
Since: base-4.7.0.0
These formatters for standard types are provided for convenience in writing new type-specific formatters: a common pattern is to throw to [formatString](Text-Printf.html#v:formatString "Text.Printf")
or[formatInteger](Text-Printf.html#v:formatInteger "Text.Printf")
to do most of the format handling for a new type.
These functions are used internally to raise various errors, and are exported for use by new type-specific formatters.
perror :: String -> a Source #
Raises an [error](Prelude.html#v:error "Prelude")
with a printf-specific prefix on the message string.
Since: base-4.7.0.0
These types are needed for implementing processing variable numbers of arguments to [printf](Text-Printf.html#v:printf "Text.Printf")
and [hPrintf](Text-Printf.html#v:hPrintf "Text.Printf")
. Their implementation is intentionally not visible from this module. If you attempt to pass an argument of a type which is not an instance of the appropriate class to[printf](Text-Printf.html#v:printf "Text.Printf")
or [hPrintf](Text-Printf.html#v:hPrintf "Text.Printf")
, then the compiler will report it as a missing instance of [PrintfArg](Text-Printf.html#t:PrintfArg "Text.Printf")
. (All [PrintfArg](Text-Printf.html#t:PrintfArg "Text.Printf")
instances are [PrintfType](Text-Printf.html#t:PrintfType "Text.Printf")
instances.)
The [PrintfType](Text-Printf.html#t:PrintfType "Text.Printf")
class provides the variable argument magic for[printf](Text-Printf.html#v:printf "Text.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](Text-Printf.html#v:printf "Text.Printf")
or [hPrintf](Text-Printf.html#v:hPrintf "Text.Printf")
, then the compiler will report it as a missing instance of [PrintfArg](Text-Printf.html#t:PrintfArg "Text.Printf")
.
Minimal complete definition
spr
The [HPrintfType](Text-Printf.html#t:HPrintfType "Text.Printf")
class provides the variable argument magic for[hPrintf](Text-Printf.html#v:hPrintf "Text.Printf")
. Its implementation is intentionally not visible from this module.
Minimal complete definition
hspr
Instances
Instances details
This class is needed as a Haskell98 compatibility workaround for the lack of FlexibleInstances.
This class, with only the one instance, is used as a workaround for the fact that [String](Data-String.html#t:String "Data.String")
, as a concrete type, is not allowable as a typeclass instance. [IsChar](Text-Printf.html#t:IsChar "Text.Printf")
is exported for backward-compatibility.
Instances
Instances details