I have a little problem understanding how to to the following in Haskell:
Lets say I have a statement similar to this ones:
- a * (b + c)
- a + (b * c)
- a + (b * ( c + d))
- a * (b + ( c * d))
- etc. etc.
I want to express these statements in a tree and evaluate the result of each, for starters I defined the following data structure:
data statement = Number Int
| Product statement statement
| Sum statement statement
deriving (Eq, Show)
For an example Tree to work with, I used the following function:
a :: statement
a = Product (Number 2) (Sum (Number 5) (Number 1))
Now I want to build a function treeResult which gives me the result of my statement defined, but I don’t know how to approach this problem. The integer returned for the above statement should be 12.
My first guess was to write a function that takes “statement” as a parameter and returns an int, for starters only with simple statements.
treeResult :: statement -> Int
treeResult (Number a) = a
treeResult (Product (Number a) (Number b)) = a*b
treeResult (Sum (Number a) (Number b)) = a+b
Now I know that I need something that works recursive but I don’t know how to write it in haskell, can someone help me out here, please?
First off:
statementneeds to be capitalized since it’s not a type variable. But that’s the least important thing.Obviously correct so far. We’re matching the
Numberconstructor, extract theIntand return that – well-typed and does what it should.This is well-typed, but it is not general enough. In this pattern, you are restricting the fields of
ProductandSumtoNumbers, but in fact they can be anyStatement. So you instead need to define theProduct/Sum:But we can’t just add/multiply the two
Statements.(+)and(*)are not defined for them (we’re kind of doing that right now). When one operand is aProduct, how do we get its value as anInt? By evaluating it.Statementis recursive, so we need recursion to evaluate it. Thus, the function becomes