[Haskell-cafe] int to bin, bin to int

Brent Yorgey byorgey at gmail.com
Fri Sep 28 07:39:15 EDT 2007


On 9/27/07, PR Stanley <prstanley at ntlworld.com> wrote:
>
> Hi
> intToBin :: Int -> [Int]
> intToBin 1 = [1]
> intToBin n = (intToBin (n`div`2)) ++ [n `mod` 2]
>
> binToInt :: [Integer] -> Integer
> binToInt [] = 0
> binToInt (x:xs) = (x*2^(length xs)) + (binToInt xs)
> Any comments and/or criticisms on the above definitions would be
> appreciated.
> Thanks , Paul


Others have already given many good suggestions, but I'll add something
specifically about the order of the bits in the result. You have the
generated list of bits in "reading order", i.e. high-order bits first.  But
perhaps it would make more sense to have the low-order bits first?  At
least, it would be more efficient that way.  Then you could do

intToBin n = (n `mod` 2) : (intToBin (n `div` 2)

The way you have it now, you will end up with something like [1] ++ [0] ++
[0] ++ [1] ++ ... which ends up inefficiently traversing the list multiple
times.  To undo, just (for example)

binToInt xs = sum $ zipWith (*) xs (iterate (*2) 1).

-Brent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070928/94c528e5/attachment.htm


More information about the Haskell-Cafe mailing list