如何将IO操作插入管道



我有一个Haskell函数,它给出了一个递归获取所有文件的目录,并将文件名写入文件中。这是一个简单的例子。在下一步中,我必须将从文件到文本的映射(transf操作(替换为使用文件内容的操作;这显然是IO monad中的一个操作。

我对Pipe的了解非常有限;我尝试了一个简单的操作opex,我尝试将lift放入管道中。我想删除当前的变压器

这看起来是一个简单的问题,但尽管在网上搜索,我还是找不到解决方案。谢谢你的帮助!

pipedDoIO2 :: Path Abs File -> Path Abs Dir -> (Path Abs File -> IO Text) -> ErrIO ()
pipedDoIO2 file path transf =  do
hand <-   openFile2handle file WriteMode
Pipe.runEffect $
getRecursiveContents path
>-> PipePrelude.map ( transf)  -- some IO type left?
-- >-> lift opex 
>-> PipePrelude.toHandle hand    
closeFile2 hand
return ()
opex :: (Path Abs File -> IO Text)
opex = return . showT 

更多的阅读让我找到了一个简单的答案:使用Path.Prelude中的mapM。我希望这个解决方案能帮助其他人找到这个在网络上不容易检测到的"显而易见"的解决方案;我在文件扩展名上添加了一个filter,作为如何使用filter的示例。

注意:toHandle"使用hPutStrLn将字符串写入句柄",即在每次插入后插入一个n

-- a convenient function to go through a directory and 
-- recursively apply a function to each file or directory
-- filters for extension md
pipedDoIO2 :: Path Abs File -> Path Abs Dir -> (Path Abs File -> ErrIO String) -> ErrIO ()
pipedDoIO2 file path opex =  do
hand <-   openFile2handle file WriteMode
Pipe.runEffect $
getRecursiveContents path
>-> PipePrelude.filter (hasExtension (Extension "md"))
>-> PipePrelude.mapM opex 
>-> PipePrelude.toHandle hand    
closeFile2 hand
return ()

最新更新