0

以下代码:

import IO
import System(getArgs)

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

为 if-else 子句生成解析错误。我试过使用花括号无济于事。帮助!

4

2 回答 2

5

只是为了证明我对马克的回答的评论,

import System.Environment (getArgs)

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

是合法的 Haskell。


使用 GHC 7.0 的{-# LANGUAGE RebindableSyntax #-}扩展,您甚至可以摆脱

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"

(无耻地模仿blog.n-sch.de。)

于 2010-12-01T03:19:41.570 回答
1

两个问题:

  1. 您缺少该条款in一部分let-in(请参阅(并接受)@ephemient 的答案

  2. 你错过条款then的一部分if-then-else

所以它可能看起来像:

import IO import System(getArgs)

main = do
    args <- getArgs
    let l = length args in
        if l == 0 then
            putStrLn "foo"
        else
            putStrLn "bar"
于 2010-12-01T02:18:47.607 回答