Decimal and binary number handling

徘徊边缘 提交于 2020-01-06 09:00:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9177222/decimal-and-binary-number-handling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!