Haskell read/show hex
Someone, somewhere wondered about converting integers to and from Hexadecimal in Haskell. Their weblog had yet another "sign up for a new account in order to comment" form, and, well, I'm all accounted out, so my reply is here:
read_h :: String -> Integer -- inferrable
read_h = fst . head . readHex
main = let iVal = 123456
hstr = showHex iVal ""
hiv = read_h hstr in
putStrLn $ show iVal
putStrLn $ show hiv
The weird thing about it was that I kept trying to assign to iVal inside the "do" section, and I never did figure out how to do it that way. Seems like it ought to be easy, but it wasn't being easy for me.
Part of the issue is that there doesn't appear to be a simple "read one hex value from a string" function. Instead, there's this parser thing (readHex), that returns a List of Pairs. That's what the "fst . head . readHex" is about -- head takes the first part of the List; and then fst takes the first element of the Pair. (I think the second element of the Pair is the rest of the string that didn't get parsed.)