
Thanks, Chaddai. It seems quite obvious once you explain it. And I now know
that ghci :t is my friend indeed.
Geoffrey
On Thu, Feb 5, 2015 at 4:55 PM, Chaddaï Fouché
On Thu, Feb 5, 2015 at 10:43 PM, Geoffrey Bays
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ï
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners