如何将 IO 操作插入到管道中
how to insert an IO operation into a Pipe
我有一个 Haskell 函数,它给出了一个目录,从中递归地获取所有文件并将文件名写入文件。这是一个简单的例子。在下一步中,我必须通过使用文件内容的操作替换从文件到文本的映射(transf
操作);这显然是 IO monad 中的一个操作。
我对Pipe
的理解很有限;我尝试了一个简单的操作 opex
,我试图将其 lift
放入管道中。我想删除当前的transf
这看起来是一个简单的问题,但是尽管在网上搜索过,我还是找不到解决方案。谢谢你的帮助!
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
。我希望这个解决方案可以帮助其他人找到这个 "obvious" 在网络上不容易检测到的解决方案;我在文件扩展名上添加了一个 filter
作为示例如何使用 filter
.
警告:toHandle
"Write Strings to a Handle using 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 ()
我有一个 Haskell 函数,它给出了一个目录,从中递归地获取所有文件并将文件名写入文件。这是一个简单的例子。在下一步中,我必须通过使用文件内容的操作替换从文件到文本的映射(transf
操作);这显然是 IO monad 中的一个操作。
我对Pipe
的理解很有限;我尝试了一个简单的操作 opex
,我试图将其 lift
放入管道中。我想删除当前的transf
这看起来是一个简单的问题,但是尽管在网上搜索过,我还是找不到解决方案。谢谢你的帮助!
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
。我希望这个解决方案可以帮助其他人找到这个 "obvious" 在网络上不容易检测到的解决方案;我在文件扩展名上添加了一个 filter
作为示例如何使用 filter
.
警告:toHandle
"Write Strings to a Handle using 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 ()