Reputation: 99
I am working on a project and having some diffuculties becauuse Im not used to Haskell and it's a somehow hard language for me to code.
I want a tree that has leaf and branches, leaves will be only inputs as an integer like 1,2,3. Branches will be chars only for operation1 and operation2.
these ops get inputs from leaves and do calculation and send the output to other branch and do calculation again until it goes to top one.
Code I have so far:
data Tree = Leaf Float | Branch Char Tree Tree deriving (Show,Eq,Ord)
insertElement x (Leaf y) = Leaf y
insertElement x (Branch a left right) = Branch a (insertElement x left) right
doIt (x:xs) (y:ys) = insertElement ((Branch y (Leaf x) (Leaf (head xs))))
op1 num1 num2 = 1+num1+num2*2
op2 num1 num2 = 1-num1*num2*2
Tree will be created recursively, I tried to use foldr for to do that but didnt work because its not a binary tree.
Any helps would be good.
Upvotes: 0
Views: 138
Reputation: 116174
I am not sure I understand the problem, but maybe you want something like this:
data Op = Op1 | Op2
data Tree = Leaf Float | Branch Op Tree Tree
eval :: Tree -> Float
eval (Leaf x) = x
eval (Branch Op1 l r) = op1 (eval l) (eval r)
eval (Branch Op2 l r) = op2 (eval l) (eval r)
op1 :: Float -> Float -> Float
op1 num1 num2 = 1+num1+num2*2
op2 :: Float -> Float -> Float
op2 num1 num2 = 1-num1*num2*2
example :: Float
example = eval (Branch Op1 (Leaf 3) (Branch Op2 (Leaf 2) (Leaf 1)))
If that is what you want to do, consider using a less general type than Tree
, such as
data Exp = Lit Float | Op1 Exp Exp | Op2 Exp Exp
eval :: Exp -> Float
eval (Lit x) = x
eval (Op1 l r) = op1 (eval l) (eval r)
...
Upvotes: 1