[Haskell-beginners] Have I just broken Haskell?

Mark Carter alt.mcarter at gmail.com
Tue Mar 17 21:55:29 UTC 2015


Persuant to my previous question, I have made some progress, but there 
is something odd going on.

Suppose we want to implement the following algorithm, which is a little 
simpler than the original problem:

The user types the name of a file as input. Haskell then puts the text 
"it works" to that file. I tried this:

import System.IO
let openFileWrite name = openFile name WriteMode
h :: IO Handle
h <- fmap openFileWrite getLine -- you need to type in a file name

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.

We also have the problem of how we are going to use hPutStr to put a 
string to the file. We can't do
     hPutStr h "it works"
because h doesn't have the right type. I tried getting around it by 
creating a function
     let put  s h = hPutStr h s
     fmap (put "it works") h
But that doesn't work, it says
    *** Exception: wow: openFile: resource busy (file is locked)

I'm guessing what I've done is create a stream OUT OF the file handle, 
rather than FOR THE file handle.

Urgh! Any ideas what the fix is?


More information about the Beginners mailing list