Haskell Program to convert Binary to Decimal


In Haskell, we can use functions like foldl, recursion, and list comprehension to convert a binary number to decimal. In the first example, we are going to use (binToDec = foldl (\acc x -> 2*acc + digitToInt x) 0) and in the second example, we are going to use base case, (binToDec "" = 0) and recursive case, (binToDec (x:xs) = 2 * binToDec xs + digitToInt x) function. And in the third example, we are going to use (binToDec = sum . zipWith (\x y -> 2^x * digitToInt y) [0..] . reverse).

Algorithm

  • Step 1 − The Data.Char library is imported.

  • Step 2 − Use the pre-defined function and it’s expressions.

  • Step 3 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do

  • Step 4 − The variable named, “input” is being initialized. It will hold the binary number that is to be converted to respective decimal number.

  • Step 5 − The resultant decimal number is printed to the console using ‘putStrLn’ statement after the function is called.

Example 1

In this example, the function is defined using fold1 function to convert the binary to decimal number.

import Data.Char (digitToInt)

binToDec :: String -> Int
binToDec = foldl (\acc x -> 2*acc + digitToInt x) 0

main :: IO ()
main = do
   let input = "1111"
   let decimal = binToDec input
   putStrLn $ "Decimal equivalent: " ++ show decimal

Output

Decimal equivalent: 15

Example 2

In this example, the recursive function is defined to convert the binary to decimal number.

import Data.Char (digitToInt)

binToDec :: String -> Int
binToDec "" = 0
binToDec (x:xs) = 2 * binToDec xs + digitToInt x

main :: IO ()
main = do
   let input = "1111"
   let decimal = binToDec input
   putStrLn $ "Decimal equivalent: " ++ show decimal

Output

Decimal equivalent: 15

Example 3

In this example, the function is defined using list comprehension to convert the binary to decimal number.

import Data.Char (digitToInt)

binToDec :: String -> Int
binToDec = sum . zipWith (\x y -> 2^x * digitToInt y) [0..] . reverse

main :: IO ()
main = do
   let input = "1111"
   let decimal = binToDec input
   putStrLn $ "Decimal equivalent: " ++ show decimal

Output

Decimal equivalent: 15

Conclusion

In Haskell, a binary number is converted to decimal number using recursion, list comprehension or by using fold1 function.

Updated on: 13-Mar-2023

499 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements