Let's look at an example, then:
repBinario 5
Replace the definition of repBinario 5 :
10 * repBinario (5 `div` 2) + 5 `mod` 2
Reduce div and mod :
10 * repBinario 2 + 1 ^
Here we produced the first digit, marked ^ .
Replace definition of repBinario 2 :
10 * (10 * repBinario (2 `div` 2) + 2 `mod` 2) + 1 ^
Reduce div and mod :
10 * (10 * repBinario 1 + 0) + 1 ^ ^
Replace the definition of repBinario 1 :
10 * (10 * (10 * repBinario (1 `div` 2) + 1 `mod` 2) + 0) + 1 ^ ^
Reduce div and mod :
10 * (10 * (10 * repBinario 0 + 1) + 0) + 1 ^ ^ ^
Replace definition of repBinario 0 :
10 * (10 * (10 * 0 + 1) + 0) + 1 ^ ^ ^
Decrease:
101
At each step (`mod` 2) gets the least significant binary digit, and (`div` 2) shifts the number to the right, discarding the digit and passing the rest of the number recursively to divBinario . At the end, we do the opposite process: (+ d) adds the current digit to the result, and (* 10) shifts the number to the left, so we can add more digits.
What you get is a decimal number that looks identical to the binary representation of the original input.
If you remove the multiplication by 10 , you get popCount , a function that gives you a count of the number - the number of bits 1 in its binary representation:
popCount 0 = 0 popCount x = popCount (x `div` 2) + x `mod` 2 popCount 5 == 2
Jon purdy
source share