On Thu, Feb 5, 2015 at 10:43 PM, Geoffrey Bays <charioteer7@gmail.com> wrote:As in LYAHThe problem also with using withFile and a lambda is that in my infinite Haskell beginnerness, I do not know how to get thecontents out of the lambda for use later for the second try of withFile in WriteMode.
- withFile "girlfriend.txt" ReadMode (\handle -> do
- contents <- hGetContents handle
- 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 -> docontentsInside <- hGetContents handleevaluate (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 linereturn contentsInsideNote this is convoluted, using a strict variant of hGetContents would allows you to just go : contents <- withFile fileName ReadMode $ \h -> hGetContents hText 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