Search code examples
listhaskellsyntaxmonadsdo-notation

Parse error in list monad's `do` notation


OK, so here's a weird one.

This works perfectly:

test = do
  x <- [1..5]
  y <- [1..5]
  [x+y, x-y]

But this:

test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
  ]

fails miserably. GHC utterly refuses to parse this. No matter how I fidget with it, I can't seem to convince GHC to allow me to spread the list across multiple lines. Which is a problem, because if you replace x+y and x-y with really big expressions, it quickly becomes hard to read...

Does anybody know why isn't this working, and how can I force it to work? (Or at least do something that looks legible?)


Solution

  • If I parse this, I get the following error:

    File.hs:10:3: error:
        parse error (possibly incorrect indentation or mismatched brackets)
    

    I think the parsers simply sees the closing square bracket ] as a new statement. And it complains that the previous statement had no closing bracket (and the new one a closing bracket without an opening bracket). If you push it one column to the right, it parses correctly (at least with GHC-8.0.2)

    test = do
      x <- [1..5]
      y <- [1..5]
      [
        x+y,
        x-y
       ] -- one space to the right
    

    As long as you do not go back to the previous indentation level (here one space to the left), it should probably be fine. Since the compiler will see it as one do-statement.