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

Christopher L Conway cconway at cs.nyu.edu
Thu Sep 27 18:30:36 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

IntToBin diverges for inputs <= 0. You could get 0 "for free" with

intToBin :: Int -> [Int]
intToBin 0 = []
intToBin n = (intToBin (n`div`2)) ++ [n `mod` 2]

And why not use [Bool] for the "Bin" type? Or

data Bin = Zero | One

Regards,
Chris


More information about the Haskell-Cafe mailing list