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

Rodrigo Queiro overdrigzed at gmail.com
Thu Sep 27 19:11:07 EDT 2007


If you don't like explicit recursion (or points):

intToBin = map (`mod` 2) . takeWhile (>0) . iterate (`div` 2)

binToInt = foldl' (\n d -> n*2+d) 0
or even:
binToInt = foldl' ((+).(*2)) 0

On 27/09/2007, 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
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list