On Wed, Sep 4, 2013 at 10:21 AM, yi lu <zhiwudazhanjiang...@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
whatever)

    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
allber...@gmail.com                                  ballb...@sinenomine.net
unix, openafs, kerberos, infrastructure, xmonad        http://sinenomine.net
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to