[Haskell-beginners] Have I just broken Haskell?

Bob Ippolito bob at redivi.com
Tue Mar 17 22:16:25 UTC 2015


On Tue, Mar 17, 2015 at 2:55 PM, Mark Carter <alt.mcarter at gmail.com> wrote:

> 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.
>

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:

name <- getLine
h <- openFileWrite name

Which is equivalent to this:

h <- getLine >>= openFileWrite

or this (`=<<` is just a flipped `>>=` operator):

h <- openFileWrite =<< getLine

-bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150317/bede3c20/attachment.html>


More information about the Beginners mailing list