Implement the Bin function, which returns the binary digits of a non-negative integer in reverse order!
Example:
- Bin 0 == []
- Bin 1 == [1]
- Bin 2 == [0,1]
- Bin 10 == [0, 1, 0, 1]
Bin :: Integer -> [Int]
Bin 0 = []
Bin a `div` 2 = b
Bin a `mod` 2 = c
I would like to give back my divide result to the Bin function and mod it again and etc.. How can I solve this ? Can I get some help ?
CodePudding user response:
There is only one parameter, so the implementation of bin looks like:
bin :: Integer -> [Int]
bin 0 = []
bin n = …
we can determine the modulo and divide the number by two with divMod :: Integral a => a -> a -> (a, a), we can use a where clause to set variables d and m:
bin :: Integer -> [Int]
bin 0 = []
bin n = …
where (d, m) = divMod n 2
we can not use m directly, since this is an Integer, and not an Int, we can work with fromIntegral :: (Integral a, Num b) => a -> b to convert the Integer to an Int.
We thus will need to construct a list with m as an element of that list, and use recursion to determine the other items of the list. The … part should thus construct such list. I leave that as an exercise. Hint: you can construct a list with x as first item and xs as a list of remaining items with (x:xs).
