Question

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!

Was it helpful?

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.)

OTHER TIPS

Two issues:

  1. You're missing the in part of the let-in clause (See (and accept) @ephemient's answer)

  2. You're missing the then part of the if-then-else clause

So it could look like:

import IO import System(getArgs)

main = do
    args <- getArgs
    let l = length args in
        if l == 0 then
            putStrLn "foo"
        else
            putStrLn "bar"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top