JJ23
JJ23

Reputation: 1

Decimal and binary number handling

I'm working on a code which capable of converting decimal to a binary value. Comparing to other languages haskell needs few lines of code to bring this up. Below is the code i worked out.

binaryToDec :: [Int] -> Int
binaryToDec [] = []
binaryToDec (x:xs) = (+) (x * 2 ^(length xs))

this code gives an error which i tried so hard to figure out. but i couldn't.

Assignment.hs:61:18:
    Couldn't match expected type `Int' with actual type `[a0]'
    In the expression: []
    In an equation for `binaryToDec': binaryToDec [] = []

what should i do?

Upvotes: 0

Views: 1033

Answers (1)

dave4420
dave4420

Reputation: 47062

binaryToDec :: [Int] -> Int

That says that binaryToDec is a function, which takes a list of Ints as its parameter, and returns an Int as its result.

binaryToDec [] = []

That says that when binaryToDec's parameter is an empty list, its result is an empty list.

An empty list is not an Int, so this is an error.

Solution: decide what binaryToDec [] should evaluate to, and use that on the right hand side of the equation.

But that's not all...

binaryToDec (x:xs) = (+) (x * 2 ^(length xs))

That says that when binaryToDec's parameter is not an empty list, its result is a function that adds x * 2 ^(length xs) to its parameter.

A function is not an Int, so this is also an error.

Solution: work out what you want to add to x * 2 ^(length xs), and, er, add it.


You have been stumped by error messages like this before. So let's deconstruct the error message line-by-line:

  • Assignment.hs:61:18:

    This gives the filename, line number and approximate position on the line where the compiler decided there was an error.

  • Couldn't match expected type `Int' with actual type `[a0]'

    This means that the surrounding context expected a value of type Int, but the value provided was of type [a0]. (a0 here means "don't know", so the compiler's worked out that you provided a list, but hasn't worked out what it's a list of.)

  • In the expression: []

    This is the expression that has type [a0], but was expected to have type Int. This is not always where your mistake is --- just where the compiler was when it noticed something was wrong --- but in this case it is where your mistake is: [] is clearly not an Int.

    (n.b. If the error was the [] on the left of the equals sign, the error message would have referred to the pattern [] instead of the expression [].)

  • In an equation for `binaryToDec': binaryToDec [] = []

    This is just giving you a bit more context about where the compiler found the error.

Upvotes: 11

Related Questions