mardi 31 janvier 2017

Haskell If Statement Condition

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.

Aucun commentaire:

Enregistrer un commentaire