小编Nat*_*way的帖子

在Haskell中处理嵌套IO的惯用方法

我正在学习Haskell,并编写一个简短的解析脚本作为练习.我的大部分脚本都包含纯函数,但我有两个嵌套的IO组件:

  1. 从路径中读取文件列表.
  2. 读取每个文件的内容,这些内容反过来将成为程序其余部分的输入.

我的工作原理,但嵌套的IO和fmap图层"感觉"笨重,就像我应该避免嵌套IO(不知何故),或者更巧妙地使用do notation来避免所有的fmaps.我想知道我是否过于复杂,做错了等等.以下是一些相关的代码:

getPaths :: FilePath -> IO [String]
getPaths folder = do
    allFiles <- listDirectory folder
    let txtFiles = filter (isInfixOf ".txt") allFiles
        paths = map ((folder ++ "/") ++) txtFiles
    return paths

getConfig :: FilePath -> IO [String]
getConfig path = do
    config <- readFile path
    return $ lines config

main = do
    paths = getPaths "./configs"
    let flatConfigs = map getConfigs paths
        blockConfigs = map (fmap chunk) flatConfigs
    -- Parse and do stuff with config …
Run Code Online (Sandbox Code Playgroud)

haskell

10
推荐指数
2
解决办法
505
查看次数

标签 统计

haskell ×1