如何解析无序语法

问题描述

newtype Program = Program [Global] [Function]

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

global0

函数0

全局1

功能1

功能2

global2

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

解决方法

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

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

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

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))

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