Question

How to indent correctly a nested case expression in haskell that would act like a nested loop in imperative programming ?

f x y = case x of
     1 -> case y of 
          1 -> 
          2 -> 
          ...        
     2 -> case y of 
       ...

The compiler gives me an indentation error at the start of the second x case, so i'm guessing it doesn't understand that the first x case is over

Was it helpful?

Solution 2

Your code seems ok. Haskell has a very simple rule of Indenation as explained in wikibooks:

Code which is part of some expression should be indented further in than the beginning of that expression.

This works for me:

f x y = case x of
     1 -> case y of 
       1 -> undefined
       2 -> undefined
     2 -> case y of
       1 -> undefined

You may want to check your editor to see if it is doing proper indentation. As @Tarmil suggested, always use spaces for indentation. More details on that here.

OTHER TIPS

Not directly an answer, but could maybe helpful nevertheless:

In this particular case, you could also write:

f 1 1 = ...
f 1 2 = ...
f 2 2 = ...

or, as a case expression:

f x y = case (x, y) of
   (1,1) -> ...
   (1,2) -> ...
   (2,1) -> ...

I had the same problem and it was due to that I was using tabs for identation. When I indentated the code with spaces, it worked!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top