I had an assignment problem were I had to parse a tokenized prefix calculator notation on a pre-defined AST. We were given a pretty complete algorithm for parsing (we had to add some stuff).
The algorithm and AST I submitted is as follows:
data Ast = Tall Int | Sum Ast Ast | Mult Ast Ast | Min Ast | Var String deriving (Eq, Show)
parseExpr :: [String] -> (Ast, [String])
parseExpr [] = error "Empty!"
parseExpr ("+":rs) = let (e1, r1) = parseExpr rs ;(e2, r2) = parseExpr r1 in (Sum e1 e2, r2)
parseExpr ("*":rs) = let (e1, r1) = parseExpr rs ;(e2, r2) = parseExpr r1 in (Mult e1 e2, r2)
parseExpr ("-":rs) = let (e1, r1) = parseExpr rs in (Min e1, r1)
parseExpr (x:rs)
| all isDigit x = (Tall (read x), rs)
| all isAlpha x = (Var x, rs)
| otherwise = error ("Syntax errors "++x)
Example of input/output:
parseExpr ["+","4","*","8","-","5"] =
(Sum (Tall 4) (Mult (Tall 8) (Min (Tall 5))),[])
What I needed in the continuation of my assignment was the first part of the tuple. This is correct, the assignment is handed in, and all is well for the purposes of the assignment.
Having said that, I don't know what is going on in the recursive function. Especially in these three lines:
parseExpr ("+":rs) = let (e1, r1) = parseExpr rs ;(e2, r2) = parseExpr r1 in (Sum e1 e2, r2)
parseExpr ("*":rs) = let (e1, r1) = parseExpr rs ;(e2, r2) = parseExpr r1 in (Mult e1 e2, r2)
parseExpr ("-":rs) = let (e1, r1) = parseExpr rs in (Min e1, r1)
Of course, I get the ("+":rs) notation. What I have difficulty understanding is the "let (e1, r1) = ....."etc.
And in the guards at the end, I don't see any recursive calls. Yet, recursion happens, right? How does this work?
parseExpron the right-hand side of the definitions? That's the recursion. Your question seems to be "What is aletexpression?"