如何使用 attoparsec 解析固定长度、非定界整数?

How can I parse fixed-length, non-delimited integers with attoparsec?

我正在尝试使用 attoparsec 从 3 个字符中解析两个整数。示例输入可能如下所示:

341

... 我想将其解析为:

Constructor 34 1

我有两个可行但有些笨拙的解决方案:

stdK :: P.Parser Packet
stdK = do
    P.char '1'
    qstr <- P.take 2
    let q = rExt $ P.parseOnly P.decimal qstr
    n <- P.decimal
    return $ Std q n

stdK2 :: P.Parser Packet
stdK2 = do
    P.char '1'
    qn <- P.decimal
    let q = div qn 10
    let n = rem qn 10
    return $ Std q n

一定有更好的方法来实现这么简单的事情。我错过了什么吗?

您的代码片段远非独立的(特别是缺少导入和 Packet 数据类型的定义),但您似乎过于复杂了。

首先,为一位整数定义一个解析器。然后,将后者用作两位整数解析器的构建块。之后,使用应用运算符组合这两个解析器并为您的自定义 Packet 数据类型定义一个解析器。见下文。

请注意,您不需要 monad 的全部功能;应用解析就足够了,这里。

-- test_attoparsec.hs

{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative ((<$>))
import Data.Attoparsec.Text
import Data.Char

data Packet = Std {-# UNPACK #-} !Int
                  {-# UNPACK #-} !Int
  deriving (Show)

stdK :: Parser Packet
stdK = char '1' *> (Std <$> twoDigitInt <*> oneDigitInt)

twoDigitInt :: Parser Int
twoDigitInt = timesTenPlus <$> oneDigitInt <*> oneDigitInt
  where
    timesTenPlus x y = 10 * x + y

oneDigitInt :: Parser Int
oneDigitInt = digitToInt <$> digit

GHCi 中的测试:

λ> :l test_attoparsec.hs
[1 of 1] Compiling Main             ( test_attoparsec.hs, interpreted )
Ok, modules loaded: Main.

λ> :set -XOverloadedStrings 

λ> parseOnly stdK "1341"
Right (Std 34 1)

λ> parseOnly stdK "212"
Left "1: Failed reading: satisfyWith"