Reputation: 183
This is my first time getting into the more "academic" programming languages. Coming from the land of Java/C, I'm having quite some issues with If statements in Haskell. It seems all the examples use a single argument, and a simple gt, ls, or eq for comparisons.
What I'm attempting to do is check if a function's argument is even or odd, then return a value based off that result. This is to speed up the calculation of an exponent, as:
n^k = (n^(k/2))^2 if k is even
n^k = n * n^(k-1) if k is odd
Here's what I have so far:
fastExp1 :: Integer -> Integer
fastExp1 x y =
if y `mod` 2 = 1
then x * x^(y-1)
else if y `mod` 2 = 0
then (x^(y/2))^2
else 0
I've tried to build it using guarded equations, but I just can't seem to get my head around how to build it:
fastExp2 :: Integer -> Integer
fastExp2 x y | (x `mod` 1) = 0 = (x^(y/2))^2
| (x `mod` 1) = 1 = x * x^(y-1)
| otherwise = 0
In Java, this isn't really any issue:
public static int fastExp1 (int x, int y) {
if (y%2 == 0) {
// The exponent was even.
return (int) Math.pow((Math.pow(x,(y/2))), 2);
} else if (y%2 == 1) {
// The exponent was odd.
return (int) Math.pow((x*x), (y-1));
} else {
return 0;
}
}
I can confirm that the Java code works as intended, but with the Haskell I get:
C:\hello.hs:16:5:
parse error in if statement: missing required then and else clauses
Failed, modules loaded: none.
Upvotes: 0
Views: 5065
Reputation: 183
As pointed out in the comments (chepner & Ben), Haskell uses ==
for comparison where as =
is used for definitions.
For future readers, here is the completed code:
fastExp1 :: Integer -> Integer -> Integer
fastExp1 x y =
if y `mod` 2 == 1
then x * x^(y-1)
else if y `mod` 2 == 0
then (x^(y `div` 2))^2
else 0
fastExp2 :: Integer -> Integer -> Integer
fastExp2 x y | (y `mod` 2 == 0) = (x^(y `div` 2))^2
| (y `mod` 2 == 1) = x * x^(y-1)
| otherwise = 0
As suggested by leftaroundabout, fastExp2 can also be done by:
fastExp2 x y | (y',0) <- y`divMod`2 = (x^y')^2
| otherwise = x * x^(y-1)
Upvotes: 2