[Haskell-beginners] File I/O: reading from, writing to, same file in one function

Chaddaï Fouché chaddai.fouche at gmail.com
Thu Feb 5 21:55:08 UTC 2015


On Thu, Feb 5, 2015 at 10:43 PM, Geoffrey Bays <charioteer7 at gmail.com>
wrote:
>
> The problem also with using withFile and a lambda is that in my infinite
> Haskell beginnerness, I do not know how to get the
> contents out of the lambda for use later for the second try of withFile in
> WriteMode.
>
> As in LYAH
>
>    1.     withFile "girlfriend.txt" ReadMode (\handle -> do
>    2.         contents <- hGetContents handle
>    3.         putStr contents)
>
> how to retrieve contents for later use? Scope of contents variable in
> inside lambda only it would appear.
>

Well withFile type is "FilePath -> Mode -> (Handle -> IO a) -> IO a", note
that "IO a", this "a" is a type variable that can be any type, this means
that the action you do in your lambda may return any type, and the type
returned by the whole withFile action is also "a", since this can be
anything, withFile can't invent it, so this must be the same thing that the
action in your lambda returned. Thus you can return the content you wished
for :

  contents <- withFile fileName ReadMode $ \h -> do
    contentsInside <- hGetContents handle
    evaluate (length contentsInside) -- still the same, you have to
evaluate the whole contents now since withFile will close the handle as
soon as you exit your lambda, use a strict variant of hGetContents to avoid
this line
    return contentsInside

Note this is convoluted, using a strict variant of hGetContents would
allows you to just go : contents <- withFile fileName ReadMode $ \h ->
hGetContents h
Text for instance provide such a strict variant in Data.Text.IO (but you
should then just use its strict variant of readFile which is exactly
equivalent to what I just wrote).

-- 
Jedaï
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20150205/7b87556b/attachment.html>


More information about the Beginners mailing list