简体   繁体   English

如何将 IO 操作插入 Pipe

[英]how to insert an IO operation into a Pipe

I have a Haskell function which given a directory from which to get recursively all files and writes the filenames into a file.我有一个 Haskell function ,它给出了一个目录,从中递归地获取所有文件并将文件名写入文件。 This is a simple example to start with.这是一个简单的例子。 In the next step I must replace the mapping from file to a text (the transf operation) by an operation using the file content;在下一步中,我必须通过使用文件内容的操作替换从文件到文本的映射( transf操作); this is obviously an operation in the IO monad.这显然是 IO monad 中的一个操作。

My understanding of Pipe is very limited;我对Pipe的了解非常有限; I tried with a simplistic operation opex which I tried to lift into a pipe.我尝试了一个简单的操作opex ,我试图将其lift为 pipe。 I want to remove the current transf我想删除当前的传输

This looks like a simple problem but despite of searching the web, I cannot find a solution.这看起来像一个简单的问题,但尽管搜索了 web,但我找不到解决方案。 Thank you for help!谢谢你的帮助!

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 

Some more reading lead me to the simple answer: use mapM from the Path.Prelude.更多阅读使我得到简单的答案:使用mapM中的 mapM。 I hope this solution helps others to find this "obvious" solution not easily detected on the web;我希望这个解决方案可以帮助其他人找到这个在 web 上不容易检测到的“明显”解决方案; I added a filter on the file extension as an example how to use filter .我在文件扩展名上添加了一个filter作为如何使用filter的示例。

Caveat: the toHandle "Write Strings to a Handle using hPutStrLn", ie it inserts a \n after each insertion.警告: 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 ()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM