nubz0r
nubz0r

Reputation: 75

Functional Programming: Odd number check

I was performing a odd number check on this Haskell function and although it does work with positive numbers when it comes to negative numbers it returns an error..

myodd :: Integer -> Bool
myodd = rem n 2 == 1

I thought it would work if I place the abs somewhere.. like this:

myodd :: Integer -> Bool
myodd = rem (abs(n)) 2 == 1

but I still receive an error when placing negative numbers..

I don't know what else I could do... any idea would be very appreciated :)

Upvotes: 0

Views: 2330

Answers (3)

Ingo
Ingo

Reputation: 36329

You could check if the result is not equal to 0 (instead if it is equal to 1).

myodd :: Integer -> Bool
myodd n = n `rem` 2 /= 0

Upvotes: 5

sepp2k
sepp2k

Reputation: 370112

As written, your code won't compile. myodd :: rem (abs(n)) 2 == 1 isn't legal syntax (and neither is myodd :: rem n 2 == 1) because :: should be followed by a type, not an expression (and anyway, you already gave a type signature in the preceding line). To define myodd you should use = and you should give it a parameter named n because you use n in the body:

myodd :: Integer -> Bool
myodd n = rem (abs(n)) 2 == 1

Now this code compiles and works exactly like you want it to. No runtime error will occur if you call it with a negative number.

Upvotes: 3

bennofs
bennofs

Reputation: 11963

The rem function doesn't change the sign of the result, so if you start with a negative number, you get a negative number back. If you want to get only positive numbers, use the mod function, which calculates the mathematically correct modulus:

>>> (-3) `rem` 4
-3
>>> (-3) `mod` 4
1

Upvotes: 4

Related Questions