【问题标题】:How to parse unordered syntax如何解析无序语法
【发布时间】:2021-02-04 23:43:59
【问题描述】:
newtype Program = Program [Global] [Function]

我在 Haskell 中使用类 C 语法解析源文件,其中全局变量和函数位于顶层。如果它们必须按顺序排列,例如所有全局变量之后的函数,解析起来很简单。但它们可以按任何顺序出现,如下所示。如何处理这样的语法?

全局0

函数0

全球1

函数1

函数2

全球2

似乎可以使用 Parsec.Perm,但 the example 在所有选择返回相同类型(十进制)时有效,而我的情况返回 Global功能

【问题讨论】:

  • data Declaration = DeclGlobal Global | DeclFunction Function.
  • 至于排列解析:它适用于你最多想要每件事一个,以任何顺序。由于您希望允许任意数量的每个,这实际上是一个更容易解决的问题。

标签: haskell parsec


【解决方案1】:

您不需要排列解析器。简单的旧many 很好。您可以使用Either 暂时将它们设为同一类型,然后使用partitionEithers 将它们拆分出来。

uncurry Program . partitionEithers
    <$> many (  (Left  <$> parseGlobal)
            <|> (Right <$> parseFunction)
             )

编辑:或者,您可以将它们全部设为Programs,然后将它们组合起来。类似的东西

instance Monoid Program where mempty = Program [] []
instance Semigroup Program where
    Program gs fs <> Program gs' fs' = Program (gs <> gs') (fs <> fs')

global x = Program [x] []
function x = Program [] [x]

然后使用:

fold <$> many ((global <$> parseGlobal) <|> (function <$> parseFunction))

非常相似的程序结构,但也许其中一个更吸引您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多