[Haskell-cafe] How to read a file and return a String?

Brandon Allbery allbery.b at gmail.com
Wed Sep 4 16:32:07 CEST 2013

On Wed, Sep 4, 2013 at 10:21 AM, yi lu <zhiwudazhanjiangshi at gmail.com>wrote:

> I want to read a text file, and store it in a *String*. But readFile will
> get *IO String*. I search with google and they tell me it is not
> necessarily to do so. Can you explain to me why is this? Furthermore, How
> to read a file and store it in a String?

You do not do so directly. An IO action is a promise to produce a value,
not an actual value. (readFile contains a String in the same way the "ls"
or "dir" command contains a list of files.)

I suggest you take a look at
http://learnyouahaskell.com/input-and-output#files-and-streams to see how
IO works in Haskell.

tl;dr: use do notation (which lets you pretend to a limited extent that you
can see the String in an IO String) or >>= or fmap to attach a callback to
the IO "promise".

    readFile >>= (something that operates on a String and produces an IO

    do s <- readFile
       (something that operates on a String and produces an IO whatever)

Note that in the end it's still in IO. You can't escape it. (There are
actually ways to "escape" but they will get you into trouble fairly quickly
because they don't work the way you want them to.)

brandon s allbery kf8nh                               sine nomine associates
allbery.b at gmail.com                                  ballbery at sinenomine.net
unix, openafs, kerberos, infrastructure, xmonad        http://sinenomine.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130904/81f495fd/attachment.htm>

More information about the Haskell-Cafe mailing list