What role does indentation play here? and why does one indentation not work?

Here is an example program from the RWH book. I wonder why the first one works fine and the second one doesn't even compile? The only difference is that the first uses 2 tabs after where mainWith func = do , while the second uses only 1. Not sure what that means? Why can't the second be compiled? And also why do construct can be empty?

Thanks a lot, Alex

 -- Real World Haskell Sample Code Chapter 4: -- http://book.realworldhaskell.org/read/functional-programming.html import System.Environment (getArgs) interactWith func input output = do s <- readFile input writeFile output (func s) main = mainWith myFunction where mainWith func = do args <- getArgs case args of [fin, fout] -> do interactWith func fin fout _ -> putStrLn "error: exactly two arguments needed" myFunction = id -- The following code has a compilation error -- % ghc --make interactWith.hs -- [1 of 1] Compiling Main ( interactWith.hs, interactWith.o ) -- -- interactWith.hs:8:26: Empty 'do' construct import System.Environment (getArgs) interactWith func input output = do s <- readFile input writeFile output (func s) main = mainWith myFunction where mainWith func = do args <- getArgs case args of [fin, fout] -> do interactWith func fin fout _ -> putStrLn "error: exactly two arguments needed" myFunction = id 
+4
source share
2 answers

The definition of the mainWith function is indented to column 10:

  where mainWith func = do ^ 

The contents of the do block running on this line only recede from column 8:

  args <- getArgs case args of ... ^ 

If you increase the indentation of the contents of the do block, which should also be indented, at least to column 10, the code is parsed correctly. With the current indentation, lines that should belong to the do block are treated as part of the where clause, but not the mainWith function.

+7
source

do -block cannot be empty, so you get an error. When using only one tab, args <- getArgs treated as part of the where -block, not do -block, so do -block is empty and you get an error message.

The fact is that if you do not use {} and ; To explicitly indicate which block comes from somewhere, haskell relies on indendation. And since you retreated from your line only one level, this was seen as part of where -block.

0
source

Source: https://habr.com/ru/post/1315332/


All Articles