Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(<strong>Note:</strong> 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.)</p> <p>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.</p> <p>Then I suggest something like this:</p> <pre><code>import Control.Monad import System.Directory import System.Environment doSomethingElse :: IO () main = do args &lt;- getArgs fileExists &lt;- doesFileExist (head args) when fileExists (removeFile (head args)) doSomethingElse </code></pre> <p>(As you can see, I added the type signature of <code>doSomethingElse</code> to avoid confusion).</p> <p>I import <code>System.Environment</code> for the <code>getArgs</code> 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 <code>head args</code>.</p> <p><code>Control.Monad</code> is imported to get the <code>when</code> function. Note that this useful function is <em>not</em> a keyword (like <code>if</code>), but an ordinary function. Let's look at its type:</p> <pre><code>when :: Monad m =&gt; Bool -&gt; m () -&gt; m () </code></pre> <p>In your case <code>m</code> is <code>IO</code>, so you can think of <code>when</code> as a function that takes a <code>Bool</code> and an IO action and performs the action only if the <code>Bool</code> is <code>True</code>. Of course you could solve your problem with <code>if</code>s, but in your case <code>when</code> reads a lot clearer. At least I think so.</p> <p><strong>Addendum:</strong> If you, like I did at first, get the feeling that <code>when</code> is some magical and difficult machinery, it's very instructive to try to define the function yourself. I promise you, it's dead simple...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload