A simple binary expression tree in Haskell without operator precedence and without parentheses.

Any comments would be much appreciated.

data Tree a= Const a
       | X    
       | Plus (Tree a) (Tree a)
       | Mult (Tree a) (Tree a)
       | Minus (Tree a) (Tree a)
       | Div (Tree a) (Tree a)
       | Power (Tree a) (Tree a)
       | Cos (Tree a)
       | Sin (Tree a)
deriving Show

eval :: ( Eq t, Floating t) => Tree t-> t -> Maybe t
eval (Const a) x =  Just  (a)
eval X x =  Just x
eval (Plus a b) x = (+) <$> eval a x <*> eval b x
eval (Mult a b) x =  (*) <$> eval a x <*> eval b x
eval (Minus a b) x =  (-) <$> eval a x <*> eval b x
eval (Power a b) x =  (**) <$> eval a x <*> eval b x
eval (Div a b) x =  if (eval b x) == (Just 0) then Nothing else (/) <$> eval a x <*> eval b x
eval (Cos a) x =(cos) <$> eval a x
eval (Sin a) x = (cos) <$> eval a x

dif :: ( Eq t, Floating t) => Tree t->Tree t
dif (Const a)  = Const 0
dif X  =  Const 1
dif (Plus a b)  =Plus (dif a) (dif b )
dif (Mult a b)  =  Plus (Mult (dif a) b) (Mult  a (dif b))
dif (Minus a b)  =  Minus (dif a) (dif b)
dif (Div a b) =  Div (Minus (Mult (dif a) b) (Mult  a (dif b))) (Mult b b)
dif (Power (Const a) (Const b)) = Const 0
dif (Power a (Const b)) = Mult (Const b) (Power X (Minus (Const b) (Const 1)))
dif (Cos a) = Minus (Const 0) (Mult (dif a) (Sin a))
dif (Sin a) = (Mult (dif a) (Cos a))
  • \$\begingroup\$ "I couldn't fit the Floating constraint into the declaration." So we should suspect your code doesn't work as intended and that's off-topic here (not ready for review) \$\endgroup\$ – πάντα ῥεῖ Nov 7 '18 at 19:47
  • \$\begingroup\$ Of course it works, as per the guidelines, I think it makes more sense to put the constraint in the declaration but couldn't find a way to do it so I did something else. \$\endgroup\$ – Lumon Nov 7 '18 at 19:58
  • \$\begingroup\$ So finally does your code work as intended, or are you asking for more code not yet written do achieve that goal? This is essential for asking questions for improvement of working code at SE CR. \$\endgroup\$ – πάντα ῥεῖ Nov 7 '18 at 20:03
  • \$\begingroup\$ Yes, it works as intended (I checked it). I will remove my opinion to allow others to review the code as they see fit. \$\endgroup\$ – Lumon Nov 7 '18 at 20:07
  • 1
    \$\begingroup\$ Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Nov 15 '18 at 22:22

You have a copy-and-paste error here:

eval (Cos a) x =(cos) <$> eval a x
eval (Sin a) x = (cos) <$> eval a x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.