beginner question

Daniel Fischer daniel.is.fischer at web.de
Wed Oct 14 04:37:24 EDT 2009


Am Mittwoch 14 Oktober 2009 08:26:10 schrieb Luca Ciciriello:
> Just a Haskell beginner question.

This sort of generic question has a higher probability of receiving a quick answer on 
haskell-cafe at haskell.org or beginners at haskell.org, where more people are reading.

>
> If I load in GHCi the code below all works fine, I load a file and its
> content is shown on screen. But if I use the second version of my
> "load_by_key" (the commented one) no error is reported loading and
> executing this code, but nothing is shown on screen. Where is my mistake?

You're bitten by laziness. It's a very common problem you're having.

In the working version, you explicitly open the file, lazily get its contents, then print 
it out and after that is done, close the file.
>
> load_by_key table key = do
>                           inh <- openFile table ReadMode
>                           contents <- hGetContents inh
>                           get_record (get_string contents) key
>                           hClose inh
>
>

Here you use bracket, which doesn't interact well with hGetContents.
hGetContents is lazy and returns immediately, without reading any of the file's contents 
yet. Once hGetContents returns, bracket performs its exit action, here it closes the file 
- before you've read anything from it. Then you try to print the file contents and 
hGetContents tries to read the file. That is now closed, hence hGetContents can't read 
anything and returns "", which then is output.

Don't mix bracket and hGetContents. Consider using readFile instead.

>
> {-
> load_by_key table key = do
>                           contents <- getTableContent table
>                           get_record (get_string contents) key
> -}
>
>
>
> get_string :: String -> String
> get_string = (\x -> x)
>
>
>
> get_record :: String -> String -> IO ()
> get_record contents key = putStr( contents )
>
>
>
> getTableContent :: String -> IO String
> getTableContent table = bracket (openFile table ReadMode)
>                                 hClose
>                                 (\h -> (hGetContents h))
>



More information about the Glasgow-haskell-users mailing list