更新:为更复杂的行包含一个自定义单子解析器。
使用 List Monad 进行简单解析
list monad 是比 Megaparsec 更好的回溯“解析器”。例如,要解析单元格:
row :: [String]
row = ["23", "95489", "0", "20", "9888"]
精确到满足特定界限(例如,小于 30)的三列值,您可以生成所有可能的解析:
{-# OPTIONS_GHC -Wall #-}
import Control.Monad
import Control.Applicative
rowResults :: [String] -> [[Double]]
rowResults = cols 3
where cols :: Int -> [String] -> [[Double]]
cols 0 [] = pure [] -- good, finished on time
cols 0 _ = empty -- bad, didn't use all the data
-- otherwise, parse exactly @n@ columns from cells @xs@
cols n xs = do
-- form @d@ from one or two cells
(d, ys) <- num1 xs <|> num2 xs
-- only accept @d < 30@
guard $ d < 30
ds <- cols (n-1) ys
return $ d : ds
-- read number from a single cell
num1 (x:xs) | ok1 x = pure (read x, xs)
num1 _ = empty
-- read number from two cells
num2 (x:y:zs) | ok1 x && ok2 y = pure (read (x ++ "." ++ y), zs)
num2 _ = empty
-- first cell: "0" is okay, but otherwise can't start with "0"
ok1 "0" = True
ok1 (c:_) | c /= '0' = True
ok1 _ = False
-- second cell: can't end with "0" (or *be* "0")
ok2 xs = last xs /= '0'
上面的基于列表的解析器试图通过假设如果“xxx,yyy”是一个数字,“xxx”不会以零开头(除非它只是“0”),而“yyy”不会以零开头以零结尾(或者,就此而言,是单个“0”)。如果这不正确,只需ok1
根据需要进行修改ok2
。
应用于row
,这给出了一个明确的解析:
> rowResults row
[[23.95489,0.0,20.9888]]
应用于模棱两可的行,它给出所有解析:
> rowResults ["0", "12", "5", "0", "8601"]
[[0.0,12.5,0.8601],[0.0,12.5,0.8601],[0.12,5.0,0.8601]]
无论如何,我建议使用标准 CSV 解析器将您的文件解析为一个String
单元格矩阵,如下所示:
dat :: [[String]]
dat = [ ["23", "95489", "0", "20", "9888"]
, ["0", "12", "5", "0", "8601"]
, ["23", "2611", "2", "233", "14", "422"]
]
然后rowResults
在上面使用获取不明确的行数:
> map fst . filter ((>1) . snd) . zip [1..] . map (length . rowResults) $ dat
[2]
>
或无法解析:
> map fst . filter ((==0) . snd) . zip [1..] . map (length . rowResults) $ dat
[]
>
假设没有不可解析的行,您可以重新生成一个可能的固定文件,即使某些行不明确,但只需为每一行获取第一个成功解析:
> putStr $ unlines . map (intercalate "," . map show . head . rowResults) $ dat
23.95489,0.0,20.9888
0.0,12.5,0.8601
23.2611,2.233,14.422
>
使用基于 List Monad 的自定义 Monad 进行更复杂的解析
对于更复杂的解析,例如,如果您想解析如下行:
type Stream = [String]
row0 :: Stream
row0 = ["Apple", "15", "1", "5016", "2", "5", "3", "1801", "11/13/2018", "X101"]
使用字符串和数字的混合,编写一个基于列表单子的单子解析器实际上并不难,它生成所有可能的解析。
关键思想是将解析器定义为一个函数,它接受一个流并生成一个可能的解析列表,每个可能的解析都表示为从流的开头成功解析的对象的元组,并与流的其余部分配对。包装在一个新类型中,我们的并行解析器看起来像:
newtype PParser a = PParser (Stream -> [(a, Stream)]) deriving (Functor)
请注意与 from 类型的相似性,ReadS
从Text.ParserCombinators.ReadP
技术上讲,它也是“所有可能的解析”解析器(尽管您通常只期望从reads
调用返回一个明确的解析):
type ReadS a = String -> [(a, String)]
无论如何,我们可以像这样定义一个Monad
实例PParser
:
instance Applicative PParser where
pure x = PParser (\s -> [(x, s)])
(<*>) = ap
instance Monad PParser where
PParser p >>= f = PParser $ \s1 -> do -- in list monad
(x, s2) <- p s1
let PParser q = f x
(y, s3) <- q s2
return (y, s3)
这里没有什么太棘手的地方: pure x
返回一个可能的解析,即x
具有未更改的流的结果s
,同时p >>= f
应用第一个解析器p
生成可能解析的列表,在列表 monad 中逐个获取它们以计算下一个q
要使用的解析器 (与通常的一元操作一样,它可以取决于第一次解析的结果),并生成一个可能返回的最终解析列表。
Alternative
and实例非常简单——它们只是从MonadPlus
list monad 中消除空虚和交替:
instance Alternative PParser where
empty = PParser (const empty)
PParser p <|> PParser q = PParser $ \s -> p s <|> q s
instance MonadPlus PParser where
要运行我们的解析器,我们有:
parse :: PParser a -> Stream -> [a]
parse (PParser p) s = map fst (p s)
现在我们可以引入原语:
-- read a token as-is
token :: PParser String
token = PParser $ \s -> case s of
(x:xs) -> pure (x, xs)
_ -> empty
-- require an end of stream
eof :: PParser ()
eof = PParser $ \s -> case s of
[] -> pure ((), s)
_ -> empty
和组合器:
-- combinator to convert a String to any readable type
convert :: (Read a) => PParser String -> PParser a
convert (PParser p) = PParser $ \s1 -> do
(x, s2) <- p s1 -- for each possible String
(y, "") <- reads x -- get each possible full read
-- (normally only one)
return (y, s2)
以及 CSV 行中各种“术语”的解析器:
-- read a string from a single cell
str :: PParser String
str = token
-- read an integer (any size) from a single cell
int :: PParser Int
int = convert (mfilter ok1 token)
-- read a double from one or two cells
dbl :: PParser Double
dbl = dbl1 <|> dbl2
where dbl1 = convert (mfilter ok1 token)
dbl2 = convert $ do
t1 <- mfilter ok1 token
t2 <- mfilter ok2 token
return $ t1 ++ "." ++ t2
-- read a double that's < 30
dbl30 :: PParser Double
dbl30 = do
x <- dbl
guard $ x < 30
return x
-- rules for first cell of numbers:
-- "0" is okay, but otherwise can't start with "0"
ok1 :: String -> Bool
ok1 "0" = True
ok1 (c:_) | c /= '0' = True
ok1 _ = False
-- rules for second cell of numbers:
-- can't be "0" or end in "0"
ok2 :: String -> Bool
ok2 xs = last xs /= '0'
然后,对于特定的行模式,我们可以编写一个行解析器,就像我们通常使用一元解析器一样:
-- a row
data Row = Row String Int Double Double Double
Int String String deriving (Show)
rowResults :: PParser Row
rowResults = Row <$> str <*> int <*> dbl30 <*> dbl30 <*> dbl30
<*> int <*> str <*> str <* eof
并获得所有可能的解析:
> parse rowResults row0
[Row "Apple" 15 1.5016 2.0 5.3 1801 "11/13/2018" "X101"
,Row "Apple" 15 1.5016 2.5 3.0 1801 "11/13/2018" "X101"]
>
完整的程序是:
{-# LANGUAGE DeriveFunctor #-}
{-# OPTIONS_GHC -Wall #-}
import Control.Monad
import Control.Applicative
type Stream = [String]
newtype PParser a = PParser (Stream -> [(a, Stream)]) deriving (Functor)
instance Applicative PParser where
pure x = PParser (\s -> [(x, s)])
(<*>) = ap
instance Monad PParser where
PParser p >>= f = PParser $ \s1 -> do -- in list monad
(x, s2) <- p s1
let PParser q = f x
(y, s3) <- q s2
return (y, s3)
instance Alternative PParser where
empty = PParser (const empty)
PParser p <|> PParser q = PParser $ \s -> p s <|> q s
instance MonadPlus PParser where
parse :: PParser a -> Stream -> [a]
parse (PParser p) s = map fst (p s)
-- read a token as-is
token :: PParser String
token = PParser $ \s -> case s of
(x:xs) -> pure (x, xs)
_ -> empty
-- require an end of stream
eof :: PParser ()
eof = PParser $ \s -> case s of
[] -> pure ((), s)
_ -> empty
-- combinator to convert a String to any readable type
convert :: (Read a) => PParser String -> PParser a
convert (PParser p) = PParser $ \s1 -> do
(x, s2) <- p s1 -- for each possible String
(y, "") <- reads x -- get each possible full read
-- (normally only one)
return (y, s2)
-- read a string from a single cell
str :: PParser String
str = token
-- read an integer (any size) from a single cell
int :: PParser Int
int = convert (mfilter ok1 token)
-- read a double from one or two cells
dbl :: PParser Double
dbl = dbl1 <|> dbl2
where dbl1 = convert (mfilter ok1 token)
dbl2 = convert $ do
t1 <- mfilter ok1 token
t2 <- mfilter ok2 token
return $ t1 ++ "." ++ t2
-- read a double that's < 30
dbl30 :: PParser Double
dbl30 = do
x <- dbl
guard $ x < 30
return x
-- rules for first cell of numbers:
-- "0" is okay, but otherwise can't start with "0"
ok1 :: String -> Bool
ok1 "0" = True
ok1 (c:_) | c /= '0' = True
ok1 _ = False
-- rules for second cell of numbers:
-- can't be "0" or end in "0"
ok2 :: String -> Bool
ok2 xs = last xs /= '0'
-- a row
data Row = Row String Int Double Double Double
Int String String deriving (Show)
rowResults :: PParser Row
rowResults = Row <$> str <*> int <*> dbl30 <*> dbl30 <*> dbl30
<*> int <*> str <*> str <* eof
row0 :: Stream
row0 = ["Apple", "15", "1", "5016", "2", "5", "3", "1801", "11/13/2018", "X101"]
main = print $ parse rowResults row0
现成的解决方案
我有点惊讶我找不到提供这种“所有可能的解析”解析器的现有解析器库。中的内容Text.ParserCombinators.ReadP
采用了正确的方法,但它假定您正在解析来自 a 的字符,String
而不是来自其他流(在我们的例子中String
是来自 a 的 s [String]
)的任意标记。
也许其他人可以指出一个现成的解决方案,使您不必扮演自己的解析器类型、实例和原语。