Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change output format of chr to hexadecimal

Tags:

haskell

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"
like image 418
akonsu Avatar asked Feb 10 '23 05:02

akonsu


1 Answers

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

like image 53
ErikR Avatar answered Feb 20 '23 09:02

ErikR