Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I indent nested case expressions?

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

like image 213
user3130051 Avatar asked Dec 03 '25 09:12

user3130051


2 Answers

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) -> ...
like image 114
Ingo Avatar answered Dec 04 '25 23:12

Ingo


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.

like image 33
Sibi Avatar answered Dec 04 '25 23:12

Sibi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!