对于这个简化的问题,我试图解析一个看起来像
foo bar
baz quux
woo
hoo xyzzy
glulx
进入
[["foo", "bar", "baz", "quux", "woo"], ["hoo", "xyzzy", "glulx"]]
我试过的代码如下:
import qualified Text.Megaparsec.Lexer as L
import Text.Megaparsec hiding (space)
import Text.Megaparsec.Char hiding (space)
import Text.Megaparsec.String
import Control.Monad (void)
import Control.Applicative
space :: Parser ()
space = L.space (void spaceChar) empty empty
item :: Parser () -> Parser String
item sp = L.lexeme sp $ some letterChar
items :: Parser () -> Parser [String]
items sp = L.lineFold sp $ \sp' -> some (item sp')
items_ :: Parser [String]
items_ = items space
这适用于一个块items
:
λ» parseTest items_ "foo bar\n baz quux\n woo"
["foo","bar","baz","quux","woo"]
但是,一旦我尝试 parse many items
,它就会在第一条未缩进的行上失败:
λ» parseTest (many items_) "foo bar\n baz quux\n woo\nhoo xyzzy\n glulx"
4:1:
incorrect indentation (got 1, should be greater than 1)
或者,使用更简单的输入:
λ» parseTest (many items_) "a\nb"
2:1:
incorrect indentation (got 1, should be greater than 1)