Search code examples
haskellhaskell-src-exts

"parse" function in Language.Haskell.Exts.Parser?


There is a function called parse in the title module. It has a type signature

parse :: String -> ParseResult ast

I have been working at it for a while and I can't figure out how to use it. I'm sure its something obvious but I am just not seeing it. Thanks in advance!


Solution

  • The Language.Haskell.Exts.Parser module handles parsing Haskell source code into an appropriate syntax tree. parse is a general function to handle parsing a String of Haskell source into an instance of the Parseable class. For an Exp (a Haskell expression), parse is defined as:

    instance Parseable Exp where
        parse = parseExp
    

    So, to use the parse function, just provide a type declaration if one cannot be inferred. For example, to parse the expression "5 + 5":

    parse "5 + 5" :: ParseResult Exp
    

    Which is equivalent to:

    parseExp "5 + 5"
    

    In ghci, they both return:

    ParseOk (InfixApp (Lit (Int 5)) (QVarOp (UnQual (Symbol "+"))) (Lit (Int 5)))