Reputation: 77
Hi I got a code like this:
data Digit = Zero | One | Two | Three | Four | Five | Six | Seven | Eight |
Nine
deriving (Eq, Show)
data Number = Single Digit | Many Digit Number deriving (Eq, Show)
data Expr = Lit Number
| Sub Expr
| Sum Expr Expr
| Mul Expr Expr
deriving (Eq, Show)
So the idea with this code is to have a string, like * + 2 3 * 2 + 6 - 2
, which will be represented as ((2 + 3) * (2 * (6 - 2)))
, and then use this to put parts of the string in there types. And of course at the end find the result, in this case 40. The problem is that I don't know much about parsing, so I really don't know how I could parse an expression like this. I have seen some simple parsing where strings are been parsed into types, like person or something. But I think this is a bit more complex. If anyone have any suggestions, I would be really interested.
Upvotes: 0
Views: 1598
Reputation: 91897
While sophisticated parsing libraries exist for Haskell, and would be great for this task, your input format is simple enough that it's not too imposing to parse by hand, with a recursive function consuming the input and returning both a parsed expression and the remainder of the string to continue parsing.
Here's a skeleton of what it would look like:
parse :: String -> (String, Expr)
parse (' ':more) = parse more
parse ('-':more) = let (remainder, e) = parse more
in (remainder, Sub e)
parse ('+':more) = undefined -- TODO
parse ('*':more) = undefined -- TODO
parse s@(num:more) | isDigit num = parseNumber s
parse s = error ("unexpected input: " ++ s)
parseNumber :: String -> (String, Expr)
parseNumber s = undefined
Upvotes: 6