[Haskell-beginners] Question on monads and laziness
Lakshmi Narasimhan Vaikuntam
lakshminaras2002 at gmail.com
Sat Jul 25 23:53:33 EDT 2009
Hello
I am studying Real World Haskell chapter 9. Here is a snippet of code
data Info = Info {
infoPath :: FilePath
, infoPerms :: Maybe Permissions
, infoSize :: Maybe Integer
, infoModTime :: Maybe ClockTime
} deriving (Eq, Ord, Show)
getInfo :: FilePath -> IO Info
-- file: ch09/ControlledVisit.hs
traverse order path = do
names <- getUsefulContents path
contents <- mapM getInfo (path : map (path </>) names)
liftM concat $ forM (order contents) $ \info -> do
if isDirectory info && infoPath info /= path
then traverse order (infoPath info)
else return [info]
getUsefulContents :: FilePath -> IO [String]
getUsefulContents path = do
names <- getDirectoryContents path
return (filter (`notElem` [".", ".."]) names)
isDirectory :: Info -> Bool
isDirectory = maybe False searchable . infoPerms
When I read about IO in the previous chapter, I learnt that reading a file
can be done lazily.
Here my doubt is that whether the expression "order contents" would generate
a list of directory contents (held in memory) for use in forM construct.
Because in a subsequent para, I find this line.
"If we are traversing a directory containing 100,000 files of which we care
about three, we'll allocate a 100,000-element list before we have a chance
to trim it down to the three we really want"
Wouldn't laziness ensure that in the traverse function, when iterating
over directory contents using the list generated by "order contents",
it will generate just one element at a time and then free the memory
for that entry immediately since we are not using the referencing list
anymore in the rest of the function.
Not sure whether I have understood the concept of laziness w.r.t
monads correctly. Please clarify my doubts with regard to the code
snippet.
Thanks for your time.
--
Regards
Lakshmi Narasimhan T V
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090725/d58439a0/attachment.html
More information about the Beginners
mailing list