Get the sum and product of integres defined in a tree
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
开发者_如何学Python | 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: statement
needs to be capitalized since it's not a type variable. But that's the least important thing.
treeResult :: Statement -> Int
treeResult (Number x) = x
Obviously correct so far. We're matching the Number
constructor, extract the Int
and return that - well-typed and does what it should.
treeResult (Product (Number a) (Number b)) = a*b
treeResult (Sum (Number a) (Number b)) = a+b
This is well-typed, but it is not general enough. In this pattern, you are restricting the fields of Product
and Sum
to Number
s, but in fact they can be any Statement
. So you instead need to define the Product
/Sum
:
treeResult (Product a b) = ...
treeResult (Sum a b) = ...
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 a Product
, how do we get its value as an Int
? By evaluating it. Statement
is recursive, so we need recursion to evaluate it. Thus, the function becomes
treeResult (Product a b) = (treeResult a) * (treeResult b)
treeResult (Sum a b) = (treeResult a) + (treeResult b)
treeResult (Sum statement1 statement2) = treeResult statement1 + treeResult statement2
Similar for Product. This is simply recognizing
- result of (a + b) == result of a + result of b
(BTW, the data type should be called Statement
with an uppercase S.
data Statement = Number Int | Product Statement Statement | Sum Statement Statement
deriving (Eq, Show)
)
精彩评论