haskellhaskell-turtle

how to drop lines when streaming from a file using Haskell and the turtle library


Let's say I want to stream from one file to another file but I want to skip the first n lines of the input file. How do I do this without first collapsing the whole first file using 'fold' ?

import Turtle
main = output "/tmp/b.txt" (f (input "/tmp/a.txt"))

What should 'f' be here to accomplish this ?

ps: I don't have enough reputation to create the 'haskell-turtle' tag.


Solution

  • I think this is the correct code:

    import Data.IORef
    import Turtle
    
    drop :: Int -> Shell a -> Shell a
    drop n s = Shell (\(FoldM step begin done) -> do
        ref <- newIORef 0
        let step' x a = do
                n' <- readIORef ref
                writeIORef ref (n' + 1)
                if n' < n then return x else step x a
        foldIO s (FoldM step' begin done) )
    

    ... except I'd probably call it something other than drop to avoid clashing with the Prelude.

    It's almost identical to Turtle.Prelude.limit (See source code for comparison). The only difference is that I've reversed the then and else clause of the if statement.

    If that solves your problem then I'll add it to Turtle.Prelude.