<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Tue, Mar 17, 2015 at 2:55 PM, Mark Carter <span dir="ltr"><<a href="mailto:alt.mcarter@gmail.com" target="_blank">alt.mcarter@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">Persuant to my previous question, I have made some progress, but there is something odd going on.<br>
<br>
Suppose we want to implement the following algorithm, which is a little simpler than the original problem:<br>
<br>
The user types the name of a file as input. Haskell then puts the text "it works" to that file. I tried this:<br>
<br>
import System.IO<br>
let openFileWrite name = openFile name WriteMode<br>
h :: IO Handle<br>
h <- fmap openFileWrite getLine -- you need to type in a file name<br>
<br>
This looks wrong, because h presumably needs to be a fixed Handle. Being an IO Handle seems to imply it is mutable. Haskell doesn't complain, though.<br></blockquote><div><br></div><div>This is wrong because the type of `h` should be Handle, not IO Handle. `fmap` is not the correct function to use here, you use `fmap` to lift a pure function into some Functor. What you need to do is sequence these two IO actions, like this:</div><div><br></div><div>name <- getLine</div><div>h <- openFileWrite name</div><div><br></div><div>Which is equivalent to this:</div><div><br></div><div>h <- getLine >>= openFileWrite</div><div><br></div><div>or this (`=<<` is just a flipped `>>=` operator):</div><div><br></div><div>h <- openFileWrite =<< getLine</div><div><br></div><div>-bob</div><div><br></div></div></div></div>