[Haskell-cafe] IO and lazyness.

D.V. dav.vire+haskell at gmail.com
Tue Mar 6 13:37:38 EST 2007


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)
                  (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'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.


More information about the Haskell-Cafe mailing list