Why negative number in the following if condition throws error? [duplicate]

穿精又带淫゛_ 提交于 2020-01-02 10:04:06

问题


I am watching 'Haskell Fundamentals Part 1' in Pluralsight. In the second chapter, the author shows an very simple function with if in it. When I tried it, I am getting error everytime when I tried the function with negative number. Here is the function

posOrNeg x = 
    if x >= 0
    then "Positive"
    else "Negative"

When I tried the method with positive number it worked fine but when I call the method with negative number, winGHCi throws following error.
"No instance for (Show (a0 -> [Char]))) arising from a use of 'print'..."
Is it more to it then just the function here?


回答1:


There is no way that you'd get a type error for applying a function to a negative number when applying the same function to a positive number of the same type works fine.

Without seeing the code, the most likely explanation is that you wrote something like posOrNeg -42, which is the same as posOrNeg - 42 and tries to subtract 42 from posOrNeg (which isn't possible because, of course, you can't subtract a number from a function). The correct syntax to apply a function to a negative number is posOrNeg (-42) with parentheses around the number, so that's it's not possible to parse the - as an infix operator.



来源:https://stackoverflow.com/questions/25955604/why-negative-number-in-the-following-if-condition-throws-error

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