Remove file if it exists

前端 未结 2 1739
遇见更好的自我
遇见更好的自我 2021-02-05 02:49

What is the right way of doing this in Haskell?

if exists \"foo.txt\" then delete \"foo.txt\"
doSomethingElse

So far I have:

im         


        
2条回答
  •  走了就别回头了
    2021-02-05 03:24

    (Note: ehird's answer makes a very good point regarding a race condition. It should be kept in mind when reading my answer, which ignores the issue. Do note also that the imperative pseudo-code presented in the question also suffers from the same problem.)

    What defines the filename? Is it given in the program, or supplied by the user? In your imperative pseudo-code, it's a constant string in the program. I'll assume you want the user to supply it by passing it as the first command line argument to the program.

    Then I suggest something like this:

    import Control.Monad    
    import System.Directory
    import System.Environment
    
    doSomethingElse :: IO ()
    
    main = do
      args <- getArgs
      fileExists <- doesFileExist (head args)
      when fileExists (removeFile (head args))
      doSomethingElse
    

    (As you can see, I added the type signature of doSomethingElse to avoid confusion).

    I import System.Environment for the getArgs function. In case the file in question is simply given by a constant string (such as in your imperative pseudo-code), just remove all the args stuff and fill in the constant string wherever I have head args.

    Control.Monad is imported to get the when function. Note that this useful function is not a keyword (like if), but an ordinary function. Let's look at its type:

    when :: Monad m => Bool -> m () -> m ()
    

    In your case m is IO, so you can think of when as a function that takes a Bool and an IO action and performs the action only if the Bool is True. Of course you could solve your problem with ifs, but in your case when reads a lot clearer. At least I think so.

    Addendum: If you, like I did at first, get the feeling that when is some magical and difficult machinery, it's very instructive to try to define the function yourself. I promise you, it's dead simple...

提交回复
热议问题