Get the sum and product of integers defined in a tree

I have a little problem understanding how to do the following in Haskell:

Let's say I have a statement like these:

  • a * (b + c)
  • a + (b * c)
  • a + (b * (c + d))
  • a * (b + (c * d))
  • etc .. and others.

I want to express these instructions in a tree and evaluate the result of each, for the initial I defined the following data structure:

data statement = Number Int 
               | Product statement statement 
               | Sum statement statement
               deriving (Eq, Show)

For the 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 treeResult function that gives me the result of my definition, but I don’t know how to approach this problem. The integer returned for the above statement must be 12.

, , "" int, .

treeResult :: statement -> Int
treeResult (Number a) = a
treeResult (Product (Number a) (Number b)) = a*b
treeResult (Sum (Number a) (Number b)) = a+b

, -, , , haskell, - , ?

+3
2

: statement , . .

treeResult :: Statement -> Int
treeResult (Number x) = x

, . Number, Int - , .

treeResult (Product (Number a) (Number b)) = a*b
treeResult (Sum (Number a) (Number b)) = a+b

, . Product Sum Number s, statement. Product/Sum:

treeResult (Product a b) = ...
treeResult (Sum a b) = ...

/ Statements. (+) (*) ( ). Product, Int? . statement , . ,

treeResult (Product a b) = (treeResult a) * (treeResult b)
treeResult (Sum a b) = (treeResult a) + (treeResult b)
+10
treeResult (Sum statement1 statement2) = treeResult statement1 + treeResult statement2

.

  • (a + b) == + b

(BTW, Statement S.

data Statement = Number Int | Product Statement Statement | Sum Statement Statement
                 deriving (Eq, Show)

)

+4

Source: https://habr.com/ru/post/1773393/


All Articles