Search code examples
haskellparse-error

Parse error in Haskell


The following code:

import IO
import System(getArgs)

main = do
    args <- getArgs
    let l = length args
    if l == 0
        putStrLn "foo"
    else
        putStrLn "bar"

generates a parse error for the if-else clause. I have tried using curly braces to no avail. Help!


Solution

  • Just to demonstrate my comment to Mark's answer,

    import System.Environment (getArgs)
    
    main :: IO ()
    main = do
        args <- getArgs
        let l = length args
        if l == 0
          then putStrLn "foo"
          else putStrLn "bar"
    

    is legal Haskell.


    With GHC 7.0's {-# LANGUAGE RebindableSyntax #-} extension, you can even get away with

    class IfThenElse a b c d | a b c -> d where
        ifThenElse :: a -> b -> c -> d
    instance IfThenElse Bool a a a where
        ifThenElse True = const
        ifThenElse False = flip const
    instance (Monad m, IfThenElse a (m b) (m b) (m b))
          => IfThenElse (m a) (m b) (m b) (m b) where
        ifThenElse = liftM ifThenElse
    
    main =
        if liftM null getArgs
          then putStrLn "foo"
          else putStrLn "bar"
    

    (Shamelessly aped from blog.n-sch.de.)