目录中文件大小的总和
我很难弄清楚如何实现这一目标。我对使用 monad/IO 还比较陌生,所以如果我遗漏了一些明显的东西,请原谅。我在谷歌上搜索了一段时间,但一无所获,而且我读过的任何内容都无法让我弄清楚如何做到这一点。
这是我现在所拥有的:
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)
如您所见,这会获取尺寸并将其打印出来,但我一直不知道如何实际对它们求和。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你快到了。您可以让
fileS
返回文件大小而不是打印它:然后,执行
mapMmapM_
ing(这会丢弃结果) > (返回结果列表):现在
sizes
是与尺寸对应的数字列表。对它们进行求和应该很容易:-)为了加深您对这个示例的理解(并养成良好的习惯),请尝试为您的函数编写类型签名。使用
:t
咨询 ghci 以获得帮助。You're almost there. You can have
fileS
return the file size instead of printing it:Then, instead of
mapM_
ing (which throws away the result), do amapM
(which returns the list of results):Now
sizes
is a list of numbers corresponding to the sizes.sum
ming 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.