I am new to Haskell and working on an assignment where I'm trying to make a parsing function for a simple calculator language.
I have been given a grammar, and I am not allowed to change it. I have tried to solve it by going thru the string and using my parsing function recursively.
The grammar is supposed to be
Expr -> Int | -Expr | + Expr Expr | * Expr Expr
Int -> Digit | Digit Int
Digit -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
So my function takes a string in the language Expr as an argument and produces an abstract syntax tree in this format
data Ast = Tall Int | Sum Ast Ast | Mult Ast Ast| Min Ast| Var String deriving (Eq, Show)
Ast is supposed to be an abstract syntax tree
And this is what I have got so far in my parsing function
parseEx :: [String] -> (Ast, [String])
parseEx [] = error "empty string"
parseEx (s:ss) | all isDigit s = (Tall (read s), ss)
| s == "-" = let (ast, ss') = parseEx ss in (Min ast, ss')
| s == "+" = let (ast, ss'), let(ast',ss'') = parseEx ss in (Sum ast ast', ss') parseEx ss' (ast', ss'')
| s == "*" = (Mult ast ast', ss'') where
(ast, ss'') = parseEx ss'
(ast', ss''') = parseEx ss''
I can see clearly that the conditional with the + is wrong, and that I can not have two let's there. Also I am kind of lost in all of those lists. I was thinking that a map-function might be a solution to my problem, and maybe it would make my code look a bit more neat. But I am not sure how to begin on that, since it would have to be on the form [String]->Ast. And is it easier to simply stick with the code that I have, and try to make it work?