gpt4 book ai didi

parsing - Haskell 的 Parsec <|> 运算符的问题

转载 作者:行者123 更新时间:2023-12-02 12:21:31 25 4
gpt4 key购买 nike

我对 Haskell 和 Parsec 都是新手。为了更多地了解该语言,特别是该库,我正在尝试创建一个可以解析 Lua 保存的变量文件的解析器。在这些文件中,变量可以采用以下形式:

变量名=值

varname = {值,值,...}

varname = {{值, 值},{值,值,...}}

我已经为每种类型创建了解析器,但是当我将它们与选择 <|> 运算符串在一起时,我收到类型错误。

Couldn't match expected type `[Char]' against inferred type `Char'
Expected type: GenParser Char st [[[Char]]]
Inferred type: GenParser Char st [[Char]]
In the first argument of `try', namely `lList'
In the first argument of `(<|>)', namely `try lList'

我的假设是(尽管我在文档中找不到它)传递给选择运算符的每个解析器必须返回相同的类型。这是有问题的代码:

data Variable = LuaString ([Char], [Char])
| LuaList ([Char], [[Char]])
| NestedLuaList ([Char], [[[Char]]])
deriving (Show)

main:: IO()
main = do
case (parse varName "" "variable = {{1234,\"Josh\"},{123,222}}") of
Left err -> print err
Right xs -> print xs

varName :: GenParser Char st Variable
varName = do{
vName <- (many letter);
eq <- string " = ";
vCon <- try nestList
<|> try lList
<|> varContent;
return (vName, vCon)}

varContent :: GenParser Char st [Char]
varContent = quotedString
<|> many1 letter
<|> many1 digit

quotedString :: GenParser Char st [Char]
quotedString = do{
s1 <- string "\"";
s2 <- varContent;
s3 <- string "\"";
return (s1++s2++s3)}

lList :: GenParser Char st [[Char]]
lList = between (string "{") (string "}") (sepBy varContent (string ","))

nestList :: GenParser Char st [[[Char]]]
nestList = between (string "{") (string "}") (sepBy lList (string ","))

最佳答案

这是正确的。

(<|>) :: (Alternative f) => f a -> f a -> f a

请注意两个参数的类型完全相同。

我不太了解您的Variable数据类型。我就是这样做的:

data LuaValue = LuaString String | LuaList [LuaValue]
data Binding = Binding String LuaValue

这允许值任意嵌套,而不仅仅是像您的那样嵌套两层。然后写:

luaValue :: GenParser Char st LuaValue
luaValue = (LuaString <$> identifier)
<|> (LuaList <$> between (string "{") (string "}") (sepBy (string ",") luaValue))

这是 luaValue 的解析器。然后你只需要写:

binding :: GenParser Char st Binding
content :: GenParser Char st [Binding]

你就会得到它。使用准确表示可能性的数据类型非常重要。

关于parsing - Haskell 的 Parsec <|> 运算符的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4231796/

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