Attoparsec - 确保使用 sepBy1 消耗全部内容
Attoparsec - ensure entire contents consumed with sepBy1
我想将下面的代码 return [LoadInt 1,LoadDub 2.5,LoadInt 3]
,但在解析 [LoadInt 1,LoadDub 2]
并面对 .5,3
后它失败了。我该怎么做才能使它必须一直解析到逗号才能成功解析,而 2.5
上的 int
解析失败?
import qualified Data.Attoparsec.ByteString.Char8 as A
import Data.Attoparsec.ByteString.Char8 (Parser)
import Data.ByteString.Char8 (pack)
import Data.Attoparsec.Combinator
import Control.Applicative ((*>),(<$>),(<|>))
data LoadNum = LoadInt Int | LoadDub Double deriving (Show)
someFunc :: IO ()
someFunc = putStrLn . show $ A.parseOnly (lnParser <* A.endOfInput) (pack testString)
testString :: String
testString = "1,2.5,3"
lnParser :: Parser [LoadNum]
lnParser = (sepBy1' (ld <* A.atEnd) (A.char ','))
double :: Parser Double
double = A.double
int :: Parser Int
int = A.signed A.decimal
ld :: Parser LoadNum
ld = ((LoadInt <$> int ) <|> (LoadDub <$> double))
您可以使用一点点前瞻来确定您是否到达了列表元素的末尾。所以:
int :: Parser Int
int = do
i <- A.signed A.decimal
next <- A.peekChar
case next of
Nothing -> pure i
Just ',' -> pure i
_ -> fail "nah"
我想将下面的代码 return [LoadInt 1,LoadDub 2.5,LoadInt 3]
,但在解析 [LoadInt 1,LoadDub 2]
并面对 .5,3
后它失败了。我该怎么做才能使它必须一直解析到逗号才能成功解析,而 2.5
上的 int
解析失败?
import qualified Data.Attoparsec.ByteString.Char8 as A
import Data.Attoparsec.ByteString.Char8 (Parser)
import Data.ByteString.Char8 (pack)
import Data.Attoparsec.Combinator
import Control.Applicative ((*>),(<$>),(<|>))
data LoadNum = LoadInt Int | LoadDub Double deriving (Show)
someFunc :: IO ()
someFunc = putStrLn . show $ A.parseOnly (lnParser <* A.endOfInput) (pack testString)
testString :: String
testString = "1,2.5,3"
lnParser :: Parser [LoadNum]
lnParser = (sepBy1' (ld <* A.atEnd) (A.char ','))
double :: Parser Double
double = A.double
int :: Parser Int
int = A.signed A.decimal
ld :: Parser LoadNum
ld = ((LoadInt <$> int ) <|> (LoadDub <$> double))
您可以使用一点点前瞻来确定您是否到达了列表元素的末尾。所以:
int :: Parser Int
int = do
i <- A.signed A.decimal
next <- A.peekChar
case next of
Nothing -> pure i
Just ',' -> pure i
_ -> fail "nah"