使用 Haskell 和 turtle 库从文件流式传输时如何删除行
how to drop lines when streaming from a file using Haskell and the turtle library
假设我想从一个文件流式传输到另一个文件,但我想跳过输入文件的前 n 行。如何在不先使用 'fold' collapsing 整个第一个文件的情况下执行此操作?
import Turtle
main = output "/tmp/b.txt" (f (input "/tmp/a.txt"))
这里 'f' 应该做什么来完成这个?
ps:我没有足够的声誉来创建 'haskell-turtle' 标签。
我认为这是正确的代码:
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) )
...除了我可能会称它为 drop
以外的其他名称,以避免与 Prelude 发生冲突。
它几乎与 Turtle.Prelude.limit
相同(参见 source code 进行比较)。唯一的区别是我颠倒了 if
语句的 then
和 else
子句。
如果这能解决您的问题,那么我会将其添加到 Turtle.Prelude
。
假设我想从一个文件流式传输到另一个文件,但我想跳过输入文件的前 n 行。如何在不先使用 'fold' collapsing 整个第一个文件的情况下执行此操作?
import Turtle
main = output "/tmp/b.txt" (f (input "/tmp/a.txt"))
这里 'f' 应该做什么来完成这个?
ps:我没有足够的声誉来创建 'haskell-turtle' 标签。
我认为这是正确的代码:
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) )
...除了我可能会称它为 drop
以外的其他名称,以避免与 Prelude 发生冲突。
它几乎与 Turtle.Prelude.limit
相同(参见 source code 进行比较)。唯一的区别是我颠倒了 if
语句的 then
和 else
子句。
如果这能解决您的问题,那么我会将其添加到 Turtle.Prelude
。