[Haskell-cafe] Haskell newbie indentation query.
Jules Bean
jules at jellybean.co.uk
Wed Oct 15 08:49:10 EDT 2008
Ramaswamy, Vivek wrote:
> Hello All~
>
> I have just started with Haskell, and I must confess; I am in love with it.
>
> However one area that I am really confused about is indentation.
>
> Lets take a look at if-else if- else block.
Important point 1.
There are two contexts in haskell programs. Layout and non-layout.
In a non-layout context you can do whatever you like with indentation.
You can put the newlines wherever you want.
In practice, almost everyone uses layout for the 'top-level' of a
module. That means that anything flush to the left margin starts a new
declaration. However, making sure we are not flush to the left margin,
the following are all fine
x = if True then 1 else 2
x = if True
then 1
else 2
x =
if True
then 1
else 2
x =
if True
then 1
else 2
because, layout is not relevant in expressions.
Now, "do blocks" are layout blocks. So what you really want us to look
at is the use of if/then/else in do blocks.
x =
do
if True
then (return 1)
else (return 2)
The first line in the do block defines the left margin for this block.
In this example, the first line is the "if" line, that defines the left
margin. Since the "then" and the "else" are also both on the left
margin, they are new statements. So, the layout interprets as:
do {if True; then (return 1); else (return 2)}
...which is a parse error, because a statement cannot begin with 'then'
or 'else'.
any pattern of indentation which keeps the if expression indented
further to the right will be OK, such as
x =
do
if True
then (return 1)
else (return 2)
x =
do
if True
then (return 1)
else (return 2)
..are both fine.
Does that help?
Jules
More information about the Haskell-Cafe
mailing list