Understand haskell indentation

haskell

It’s quite common to get “parse error (possibly incorrect indentation...” when you start to write haskell. The code layout determines whether it could be compiled. And unlike other languages, semicolon and curly braces are used to separate the code into different blocks, haskell uses space indentation(semicolon and curly also supported but not common used). So what’s the rule of indentation?

We don’t need to refer to the language specification. The rule is quite simple as to haskell wiki.

  1. subpart of the expression should be indented further than the beginning of the expression
  2. all grouped expressions must be aligned

See below examples:

let expression

-- c is the start of the let expression
c = let
-- below are group of sub expressions, they are aligned.
  a = 1
  b = 2
  in a * b

-- a & b definiton are aligned
c' = let a = 1
         b = 2
-- in expr can be algined with let or indent further
     in a * b

where expression

c'' = a * b
-- where is indented, a & b definition are aligned
  where a = 1
        b = 2

long lambda expression

c''' = \a ->
-- \b is subpart of the lambda so it's indented
  \b -> a * b