Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum the filesizes in a directory

Tags:

io

haskell

monads

I'm having trouble wrapping my head around how to accomplish this. I'm relatively new to working with monads/IO, so excuse me if I'm missing something obvious. I searched google for a while and came up with nothing, and nothing I've read is making me figure out how to do this.

Here is what I have now:

import System.Path.Glob (glob)
import System.Posix.Files (fileSize, getFileStatus)

dir = "/usr/bin/"
lof = do files <- (glob (dir++"*"))
         (mapM_ fileS files)

fileS file = do fs <- getFileStatus file
                print (fileSize fs)

As you can see, this gets the sizes and prints them out, but I'm stuck on how to actually sum them.


1 Answers

You're almost there. You can have fileS return the file size instead of printing it:

return (fileSize fs)

Then, instead of mapM_ing (which throws away the result), do a mapM (which returns the list of results):

sizes <- mapM fileS files

Now sizes is a list of numbers corresponding to the sizes. summing them should be easy :-)

To deepen your understanding of this example (and practice good habits), try to write type signatures for your functions. Consult ghci with :t for help.

like image 68
luqui Avatar answered Dec 30 '25 22:12

luqui