[Haskell-cafe] IO and lazyness.

mm schneegloeckchen at gmx.li
Tue Mar 6 15:27:20 EST 2007


On Tue, Mar 06, 2007 at 07:37:38PM +0100, D.V. wrote:
> Hello,
> 
> I'm still learning Haskell and I am stuck on a probably simple problem.
> 
> Assume I have a file where lines are of the form "key=value"
> 
> I want to search a value in that file and came up with the following code.
> 
> >rechf :: String -> IO (Maybe String)
> >rechf r = bracket (openFile "liste" ReadMode)
>                  (hClose)
>                  (rechf2 r)
> >
> >rechf2 :: String -> Handle -> IO (Maybe String)
> >rechf2 r h= do
> >  f <- hGetContents h
> >  --print f
> >  return $ rech r $ lines f
> >
> >rech :: String -> [ String ] -> Maybe String
> >rech r l = lookup r $ map span2 l
> >
> >span2 :: String->(String,String)
> >span2 c = (a,b)
> >  where a=takeWhile (/='=') c
> >        b=drop 1 $ dropWhile (/='=') c
> 
> Now the problem is this :
> 1) if I try rechf, it returns nothing even for a key that exists in the 
> file.
> 2) if I uncomment the line where there is "print f", the key is found
> and the value returned.


I cannot help you with your question more than pointing you to 

http://bugs.darcs.net/issue391

where Simon Marlow explains how to avoid "IO.bracket".

But heres a hint: you can use ParserCombinators instead of rolling your own parser,
especially if the complexity of your input formats will increase.

mm

> 
> I'm guessing print forces f to be evaluated, so the file is actually
> read, but I was wondering why it doesn't work without it and how to
> correct that.
> 
> David.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe


More information about the Haskell-Cafe mailing list