Converting Decimal to Binary in Haskell

binary, haskell, recursion

Solution

In short, it multiplies the accumulated result by `10` on each iteration.

To get a clearer understanding of what's going on we can divide your function into two simpler ones. The first one will convert an integer into a list of binary digits. The other will then do exactly the thing that bothers you: concat a list of binary digits into an integer.

extractBinDigits :: Int -> [Int]
extractBinDigits =
  unfoldr (\x -> if x == 0 then Nothing else Just (mod x 2, div x 2))

concatDigits :: [Int] -> Int
concatDigits =
  foldr (\a b -> a + b * 10) 0

As you see we simply fold the list multiplying the accumulator by `10` on each step and adding each digit to it.

Then your original function becomes just this:

repBinario :: Int -> Int
repBinario =
  concatDigits . extractBinDigits

Division now lets us inspect and reuse the finer pieces of our program providing us with greater flexibility. E.g., by adding another simple function you can now convert the integer into a string in one go:

showDigits :: [Int] -> String
showDigits =
  reverse . map (chr . (+ 48))

repStringyBinario :: Int -> String
repStringyBinario =
  showDigits . extractBinDigits

Problem

I found out this snippet of code which works, but I do not understand why it does. It converts an Int to its representation in binary. ``` repBinario::Int -> Int repBinario 0 = 0 repBinario x = 10 * repBinario (x `div` 2) + x `mod` 2 ``` I know what `div` and `mod` do. However, how does it place each number that comes from `mod` together?

Original source