gpt4 book ai didi

parsing - 缩进解析器示例

转载 作者:行者123 更新时间:2023-12-04 08:50:22 26 4
gpt4 key购买 nike

有人可以发布一个 IndentParser 用法的小例子吗?我希望解析类似 YAML 的输入,如下所示:

fruits:
apples: yummy
watermelons: not so yummy

vegetables:
carrots: are orange
celery raw: good for the jaw

我知道有一个 YAML 包。我想学习 IndentParser 的用法。

最佳答案

我在下面勾勒出一个解析器,对于您的问题,您可能只需要 block
来自 IndentParser 的解析器。注意我没有尝试运行它,所以它可能有基本错误。

解析器最大的问题不是缩进,而是只有字符串和冒号作为标记。您可能会发现下面的代码需要进行大量调试,因为它必须对不消耗太多输入非常敏感,尽管我试图小心左因子。因为您只有两个 token ,所以您从 Parsec 的 token 模块中获得的好处并不多。

请注意,解析有一个奇怪的事实,即看起来简单的格式通常不容易解析。对于学习,为简单表达式编写解析器将比或多或少的任意文本格式(这可能只会让你感到沮丧)教给你更多的东西。

data DefinitionTree = Nested String [DefinitionTree]
| Def String String
deriving (Show)


-- Note - this might need some testing.
--
-- This is a tricky one, the parser has to parse trailing
-- spaces and tabs but not a new line.
--
category :: IndentCharParser st String
category = do
{ a <- body
; rest
; return a
}
where
body = manyTill1 (letter <|> space) (char ':')
rest = many (oneOf [' ', '\t'])

-- Because the DefinitionTree data type has two quite
-- different constructors, both sharing the same prefix
-- 'category' this combinator is a bit more complicated
-- than usual, and has to use an Either type to descriminate
-- between the options.
--
definition :: IndentCharParser st DefinitionTree
definition = do
{ a <- category
; b <- (textL <|> definitionsR)
; case b of
Left ss -> return (Def a ss)
Right ds -> return (Nested a ds)
}

-- Note this should parse a string *provided* it is on
-- the same line as the category.
--
-- However you might find this assumption needs verifying...
--
textL :: IndentCharParser st (Either DefinitionTrees a)
textL = do
{ ss <- manyTill1 anyChar "\n"
; return (Left ss)
}

-- Finally this one uses an indent parser.
--
definitionsR :: IndentCharParser st (Either a [DefinitionTree])
definitionsR = block body
where
body = do { a <- many1 definition; return (Right a) }

关于parsing - 缩进解析器示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4908398/

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