Home > Back-end >  Why do I get an error when I indent code after using "import" statement in Haskell?
Why do I get an error when I indent code after using "import" statement in Haskell?

Time:12-07

When I use the import statement I lose the ability to indent functions ahead of the import statement, for example:

import Data.Char
 
example = isLower 

This runs fine, but if I write:

import Data.Char

    example = isLower 

I get the following error: parse error on input ‘example’. (Whether i use tabs or spaces to indent)

However, if I use no import statement at all, I can indent the functions however I like

I would like to know why that happens and if there is anyway to solve the issue. Thanks in advance

CodePudding user response:

Because you set the top level indentation norm with your first import statement and ghc expects the rest of the top level statements to be on that level.

In other words, it doesn't matter if it's an import statement or anything else. What matters is that it is the first statement in the file and the first statement sets the norm/position that is expected of top level statements.

Consider the following examples:

  example = "hello"
  example2 = "good"

The above compiles just fine if you put it in a file while both lines are indented. But the below does not:

example = "hello"
  example2 = "good"

The following also compiles as you probably have already checked:

  import Data.Char
  example2 = "good"

Since both the first statement and the next are on the same level.

This property of the GHC empowers you to indent your code for maximum readability, of course within reason, meaning it must do sense to the compiler.

But it also can be confusing at times because it gives you so much power.

CodePudding user response:

Roughly speaking, a code line "ends" when we encounter a line which is as indented or less indented (or we reach the end of the file).

For instance

aaa
bbb
ccc

are parsed as three lines, while

aaa
  bbb
  ccc

is equivalent to

aaa bbb ccc

In particular,

import Data.Char

    example = isLower 

is equivalent to

import Data.Char example = isLower 

which is a parse error.

Similarly,

import Data.Char
    example :: Char -> Bool
    example = isLower 

means

import Data.Char example :: Char -> Bool example = isLower 

which is also a parse error.

Adding explicit semicolons can force a line to "end" and allow different indentations, but this is not a common style.

  • Related