问题
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