Change chr output format to hexadecimal

Let's pretend that

print [chr 0x49, chr 0x9f]

which outputs

"I\159"

How to make printuse of hexadecimal numbers when it prints characters that should be displayed as escape sequences? So my conclusion reads:

"I\x9f"
+4
source share
1 answer

The short answer is that you cannot change it.

print xis the same as, putStrLn (show x)and you cannot change the method showfor types that already have a specific Show instance.

However, you can define your 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 to determine fmtChar:

import Numeric (showHex)

fmtChar ch =
  if length s == 1
    then s
    else "\\x" ++ showHex (fromEnum ch) ""
  where s = show ch

(: Numeric base, .)

+8

All Articles