[Haskell-beginners] Trouble with formatting, Real World Haskell example

Brent Yorgey byorgey at seas.upenn.edu
Mon Nov 24 12:22:28 EST 2008


On Sat, Nov 22, 2008 at 09:53:37PM -0500, Robert Kosara wrote:
> 
> main = mainWith myFunction
>     where mainWith function = do
>         args <- getArgs
>         case args of
>             [input, output] -> interactWith function input output
>             _ -> putStrLn "Usage: Interact inputFile outputFile"
> 
>         myFunction = id
> 

I think the point is that this 'where' block is supposed to introduce
two definitions: one for 'mainWith' and one for 'myFunction'.  The
'myFunction = id' should not be part of the do-block (it wouldn't make
sense, and isn't even syntactically correct).

The layout rule is this: the column of the first thing following the
'do' determines the indentation for the rest of the do-block.  The first
line which is indented *less* than that is the first line following
the end of the do-block.  So:


   do foo
      bar
      baz
     not part of the do-block!

or:

   mainWith function = do
       start of the do-block (doesn't necessarily need to be indented past 'mainWith')
       another line in the do-block
    this is not part of the do-block

I would indent the code like so:

> main = mainWith myFunction
>     where mainWith function = do
>               args <- getArgs
>               case args of
>                   [input, output] -> interactWith function input output
>                   _ -> putStrLn "Usage: Interact inputFile outputFile"
> 
>           myFunction = id

Also, you should never use tabs -- it's hard to predict how they will
be interpreted by the layout rule, and haskell files using tabs are
also non-portable, in the sense that if you send it to someone else
they may have different tab settings, etc.  It should be possible to
tell your favorite editor to automatically convert tabs into spaces.

-Brent


More information about the Beginners mailing list