GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Wednesday 14 February 2007
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:

import Numeric

read_h :: String -> Integer -- inferrable read_h = fst . head . readHex

main = let iVal = 123456 hstr = showHex iVal "" hiv = read_h hstr in do putStrLn $ show iVal putStrLn hstr 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.)
1:35:28 AM   comment/     



Click here to visit the Radio UserLand website. Click to see the XML version of this web page. © Copyright 2007 Doug Landauer .
Last update: 07/3/1; 22:38:19 .
Click here to send an email to the editor of this weblog.

February 2007
Sun Mon Tue Wed Thu Fri Sat
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28      
Jan   Mar

Previous/Next