Search code examples
haskell-pipes

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. 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; this is obviously an operation in the IO monad.

My understanding of Pipe is very limited; I tried with a simplistic operation opex which I tried to lift into a 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. 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 

Solution

  • Some more reading lead me to the simple answer: use mapM from the Path.Prelude. I hope this solution helps others to find this "obvious" solution not easily detected on the web; I added a filter on the file extension as an example how to use filter.

    Caveat: the toHandle "Write Strings to a Handle using hPutStrLn", i.e. it inserts a \n after each insertion.

    -- 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 ()