Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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?

like image 347
Nair Avatar asked Jan 19 '26 14:01

Nair


1 Answers

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.

like image 164
sepp2k Avatar answered Jan 21 '26 05:01

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!