Haskell recursive problem, tiny parser. A few things

后端 未结 1 1886
青春惊慌失措
青春惊慌失措 2021-01-28 12:13
data Expr =  Var Char | Tall Int | Sum Expr Expr | Mult Expr Expr | Neg Expr | Let Expr Expr Expr
    deriving(Eq, Show) 

That is the datatype for

相关标签:
1条回答
  • 2021-01-28 12:44

    Your parseExpr function returns a pair, so of course you cannot use its result directly to construct an Expr. The way I would write this would be something like

    parseExpr ('*':'(':s) = (Mult x y, s'')
        where (x,',':s') = parseExpr s
              (y,')':s'') = parseExpr s'
    

    The basic idea is that, since parseExpr returns the leftover string as the second argument of the pair, you need to save that string in each recursive call you make, and when you've handled all the subexpressions, you need to return whatever is left over. And obviously the error handling here sucks, so you may want to think about that a bit more if this is intended to be a robust parser.

    Handling Var and Tall I would do by just extracting the first character as is and have an if to construct an Expr of the appropriate type.

    And if you want to write more complex parsers in Haskell, you'll want to look at the Parsec library, which lets you write a parser as pretty much the grammar of the language you're parsing.

    0 讨论(0)
提交回复
热议问题