JJ23
JJ23

Reputation: 1

convert binary to decimal

selectMenu :: Int->IO() 
selectMenu num
        |(num==2)=convertBinToDecimal



convertBinToDecimal:: IO()
convertBinToDecimal= do 
            putStrLn("\n\tConvert Binary To Decimal\n")
            putStrLn("----------------------------------------------------------\n")
            putStrLn("Enter 5 binary numbers [,,] : ") 
            input<-getLine
            let n=(read input)::Int
            --putStrLn (show n)
            let result = convertionTO binaryToDec n
            putStrLn(show result)

this code seems fine.but there is an error.

Any solutions to fix this error? Thank you

Upvotes: 0

Views: 2249

Answers (2)

Like hammar said you cannot reverse Int. You need to convert your number to list somehow with :: Int -> [Int]

Here is some kludges to do that.

listToNum :: [Int] -> Int
listToNum = foldl1 ( (+) . (*10) )

numToList :: Int -> [Int] 
numToList n | n <= 9    = [n]
            | otherwise = numToList (n `div` 10) ++ [n `mod` 10]

And then you can use it like reverse $ numToList x instead of reverse x.

And just a note. Your selectmenu function did not matches all possible cases. What if num is not equal to 2?

Upvotes: 1

hammar
hammar

Reputation: 139830

You're trying to use reverse on x, which is an Int (since it's the argument of binaryToDec, which you have given the type Int -> Int), but reverse has the type [a] -> [a], so it only works on lists.

This is basically what the compiler means when it says "cannot match expected type [a] with actual type Int in the first argument of reverse". It's a good idea to read the error messages carefully, they often provide good clues to what is wrong.

To fix this, you probably want to convert x to a list somehow, or change the function to take a list instead.

Upvotes: 3

Related Questions