On 9/27/07, PR Stanley <[EMAIL PROTECTED]> 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
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe