gpt4 book ai didi

haskell - 跳过管道 attoparsec 中的第一行

转载 作者:行者123 更新时间:2023-12-02 16:10:51 26 4
gpt4 key购买 nike

我的类型:

data Test = Test {
a :: Int,
b :: Int
} deriving (Show)

我的解析器:

testParser :: Parser Test
testParser = do
a <- decimal
tab
b <- decimal
return $ Test a b

tab = char '\t'

现在为了跳过第一行,我做了这样的事情:

import qualified System.IO as IO    

parser :: Parser Test
parser = manyTill anyChar endOfLine *> testParser

main = IO.withFile testFile IO.ReadMode $ \testHandle -> runEffect $
for (parsed (parser <* endOfLine) (fromHandle testHandle)) (lift . print)

但是上面的parser函数使每个备用链接都跳过(这是显而易见的)。如何仅跳过第一行以使其与 Pipes 生态系统配合使用(Producer 应生成单个 Test 值。)这是一个我不认为的明显解决方案不想要(以下代码仅在我修改 testParser 以读取换行符时才有效),因为它返回整个 [Test] 而不是单个值:

tests :: Parser [Test]
tests = manyTill anyChar endOfLine *>
many1 testParser

有什么想法可以解决这个问题吗?

最佳答案

您可以像这样在恒定空间中有效地删除第一行:

import Lens.Family (over)
import Pipes.Group (drops)
import Pipes.ByteString (lines)
import Prelude hiding (lines)

dropLine :: Monad m => Producer ByteString m r -> Producer ByteString m r
dropLine = over lines (drops 1)

您可以在解析 Producer 之前将 dropLine 应用于您的 Producer,如下所示:

main = IO.withFile testFile IO.ReadMode $ \testHandle -> runEffect $
let p = dropLine (fromHandle testHandle)
for (parsed (parser <* endOfLine) p) (lift . print)

关于haskell - 跳过管道 attoparsec 中的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com