LewisDavie
LewisDavie

Reputation: 75

Syntax of If-Else in Haskell?

I've been looking at other similar questions but I still can't work out the problem here. I'll preface this by saying that yes, this is homework, but I'm at the point where I don't know where I'm wrong. The task is to rewrite a recursive algorithm we were given, that returns 1 if n is 0, n if n is less than 5, else it does the last line of code here:

alg n = if (n == 0)
    then 1 
    else if (n<5) 
        then n
        else alg(n-1) * alg(n-2) * alg(n-3) * alg(n-4)

The error I get is a parse error (possibly incorrect indentation or mismatched brackets) in WinGHCi. I've checked lots of articles on how to properly structure if statements in Haskell but I'm still a beginner, so I have no idea where I'm going wrong. If somebody is able to tell me what in there is incorrect to avoid future mistakes, I'd be very grateful.

Upvotes: 2

Views: 6734

Answers (3)

MathematicalOrchid
MathematicalOrchid

Reputation: 62818

The answer is right there in the error message: your indentation is wrong. Specifically, you wrote

else if ...
  then ...
  else ...

The then and else keywords needs to be indented further than the matching if keyword:

else if ...
       then ...
       else ...

Edit: Nope, it turns it I'm wrong. I've tried with several different mis-indentations of if, and it all works fine. I have no idea what your original problem was. (Tab characters, maybe?)

Regardless, as @vikingsteve rightly points out, in this instance you can do it nicer with pattern guards:

alg n
    | condition1 = ...
    | condition2 = ...
    | condition3 = ...
    | condition4 = ...

It's usually much more readable to do it this way when possible. (It's not always so easy, of course...)

Upvotes: -3

vikingsteve
vikingsteve

Reputation: 40398

An alternative (and arguably more concise) approach could be considered, using guards:

alg n
    | n == 0 = 1 
    | n < 5 = n 
    | otherwise = alg(n-1) * alg(n-2) * alg(n-3) * alg(n-4)

Upvotes: 3

Reid Barton
Reid Barton

Reputation: 15009

There is nothing wrong with the lines you wrote in isolation, as you can check by copying them into a new Haskell source file. If GHC is reporting an error on one of these lines, then the real error is probably just before these lines, perhaps an unmatched parenthesis or if-then with no else or something similar.

Upvotes: 5

Related Questions