如何在haskell中退出main给出条件

mel*_*amy 6 io error-handling monads haskell exit-code

我有一个主要功能,可以完成很多IO.但是,有一点,我想检查一个变量,例如not (null shouldBeNull)退出整个程序,而不继续,使用linux exitcode 1并输出错误消息.

我试过玩,error "..."就像把它放在if:

if (not (null shouldBeNull)) error "something bad happened" else putStrLn "ok"

但我得到了parse error (possibly incorrect indentation):(.

这是一个改变的片段.

main :: IO ExitCode
main = do 
  --Get the file name using program argument
  args <- getArgs
  file <- readFile (args !! 0)
  putStrLn("\n")
  -- ... (some other io)
  -- [DO A CHECK HERE], exit according to check..
  -- ... (even more io)
  echotry <- system "echo success"
  rmtry <- system "rm -f test.txt"
  system "echo done."
Run Code Online (Sandbox Code Playgroud)

正如您可能注意到的那样,我想在[DO A CHECK HERE]上面发表评论的地方进行检查......

谢谢你的帮助!

ham*_*mar 12

解析错误是因为您thenif表达式中缺少关键字.

if condition then truePart else falsePart
Run Code Online (Sandbox Code Playgroud)

用于退出,更合适的选择,而不是error可能是使用从所述功能中的一个System.Exit,例如exitFailure.

所以,例如,

if not $ null shouldBeNull
    then do putStrLn "something bad happened"
            exitFailure
    else putStrLn "ok"
Run Code Online (Sandbox Code Playgroud)

  • 或者,不要打印出不重要的"ok","import Control.Monad"和"badThingHappened exitFailure". (7认同)