<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Thu, Feb 5, 2015 at 10:43 PM, Geoffrey Bays <span dir="ltr"><<a href="mailto:charioteer7@gmail.com" target="_blank">charioteer7@gmail.com</a>></span> wrote:<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr"><div><div>The problem also with using withFile and a lambda is that in my infinite Haskell beginnerness, I do not know how to get the<br></div>contents out of the lambda for use later for the second try of withFile in WriteMode.<br><br></div>As in LYAH<br><ol start="1"><li><span>    withFile <span>"girlfriend.txt"</span><span> </span><span>ReadMode</span><span> (\handle</span><span> -> </span><span>do</span><span>  </span></span></li><li><span>        contents<span> <- </span><span>hGetContents handle     </span></span></li><li><span>        putStr contents)</span></li></ol><p>how to retrieve contents for later use? Scope of contents variable in inside lambda only it would appear.</p></div></blockquote><div> <br></div><div>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 :<br><br></div><div> contents <- withFile fileName ReadMode $ \h -> do<br></div><div>   contentsInside <- hGetContents handle<br></div><div>   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<br></div><div>   return contentsInside<br></div></div><br></div><div class="gmail_extra">Note this is convoluted, using a strict variant of hGetContents would allows you to just go : contents <- withFile fileName ReadMode $ \h -> hGetContents h<br></div><div class="gmail_extra">Text for instance provide such a strict variant in <a href="http://Data.Text.IO">Data.Text.IO</a> (but you should then just use its strict variant of readFile which is exactly equivalent to what I just wrote).<br><br>-- <br></div><div class="gmail_extra">Jedaï<br></div></div>