Binary to Decimal in Haskell without using recursion or list comprehensions

cluuu

I am currently working on a homework assignment that requires me to implement a function that converts binary to decimal without using list comprehensions or recursion.

I've tried using folds, explicitly using foldr, to implement this, but can't quite get correct results. In a related thread I have found the following

bintodec :: [Bool] -> Int
bintodec = foldr (\x y -> fromEnum x + 2*y) 0

which seems like a good starting point, but does not seem to produce correct results for me. It seems to work for any given odd number, where the list only consists of Trues, yet not for anything else.

The assigned function is also supposed to have this signature:

binarytoInteger :: [Bool] -> Integer

which I tried to achieve using the above definition by using the toInteger function at various points, but could never actually match the type of the function definition.

I would gladly appreciate a hint in the right direction!

Willem Van Onsem

which seems like a good starting point, but does not seem to produce correct results for me. It seems to work for any given uneven number, where the list only consists of Trues, yet not for anything else.

It works, in the sense that it indeed converts a binary list to an integer. But in your function the first element is the least significant bit (LSB).

We could for example use a fold here:

import Data.Bool(bool)

bin2dec :: (Foldable f, Integral i) => f Bool -> i
bin2dec = foldl (\a -> (+) (2*a) . bool 0 1) 0

For example:

Prelude Data.Bool> bin2dec [False]
0
Prelude Data.Bool> bin2dec [True]
1
Prelude Data.Bool> bin2dec [True, False]
2
Prelude Data.Bool> bin2dec [True, True]
3
Prelude Data.Bool> bin2dec [True, False, False]
4
Prelude Data.Bool> bin2dec [True, False, True]
5
Prelude Data.Bool> bin2dec [True, True, False]
6
Prelude Data.Bool> bin2dec [True, True, True]
7 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related