Reputation: 29576
Suppose I have
print [chr 0x49, chr 0x9f]
which outputs
"I\159"
How do I make print
use hexadecimal numbers when it prints characters that have to be shown as escape sequences? So that my output reads:
"I\x9f"
Upvotes: 4
Views: 90
Reputation: 52057
The short answer is that you can't change it.
print x
is the same as putStrLn (show x)
and you can't change the way show
works for types which already have a Show instance defined.
You can, however, define you own formatting functions:
fmtChar :: Char -> String
fmtChar ch = ...
fmtString :: String -> String
fmtString s = "\"" ++ (concatMap fmtChar s) ++ "\""
and use them where you want to see your format:
putStrLn $ fmtString [ chr 0x49, chr 0x9f ]
One way of defining fmtChar
:
import Numeric (showHex)
fmtChar ch =
if length s == 1
then s
else "\\x" ++ showHex (fromEnum ch) ""
where s = show ch
(Note: Numeric
is in base
so you already have it.)
Upvotes: 8