Guest User

Untitled

a guest
Jan 20th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. data Func = X | Const Double | Add Func Func | Sub Func Func | Mul Func Func | Div Func Func | Pow Func Func
  2.  
  3. derive :: Func -> Func
  4. derive (Const _) = Const 0
  5. derive (X) = Const 1
  6.  
  7. derive (Add u v) = Add (derive u) (derive v) -- u'(x) + v'(x)
  8. derive (Sub u v) = Sub (derive u) (derive v) -- u'(x) - v'(x)
  9. derive (Mul u v) = Add (Mul (derive u) v) (Mul u (derive v)) -- u'(x) * v(x) + u(x) * v'(x)
  10. derive (Div u v) = Div (Sub (Mul (derive u) v) (Mul u (derive v))) (Pow v (Const 2)) -- (u'(x) * v(x) - u(x) * v'(x)) / v'(x)²
  11. derive (Pow f (Const x)) = Mul (Const x) (Mul (derive f) (Pow f (Sub (Const x) (Const 1))))
  12.  
  13. -- very basic reduction by removing obvious stuff like x * 0
  14. cleanup :: Func -> Func
  15. cleanup (Add (Const 0) f) = cleanup f
  16. cleanup (Add f (Const 0)) = cleanup f
  17. cleanup (Sub f (Const 0)) = cleanup f
  18. cleanup (Mul (Const 1) f) = cleanup f
  19. cleanup (Mul f (Const 1)) = cleanup f
  20. cleanup (Mul (Const 0) f) = Const 0
  21. cleanup (Mul f (Const 0)) = Const 0
  22. cleanup (Pow f (Const 0)) = Const 1
  23. cleanup (Pow f (Const 1)) = cleanup f
  24.  
  25. -- calculation
  26. cleanup (Add (Const a) (Const b)) = Const (a + b)
  27. cleanup (Sub (Const a) (Const b)) = Const (a - b)
  28. cleanup (Mul (Const a) (Const b)) = Const (a * b)
  29. cleanup (Div (Const a) (Const b)) = Const (a / b)
  30. cleanup (Pow (Const a) (Const b)) = Const (a ^ truncate b)
  31.  
  32. -- catch-alls
  33. cleanup (Add u v) = Add (cleanup u) (cleanup v)
  34. cleanup (Sub u v) = Sub (cleanup u) (cleanup v)
  35. cleanup (Mul u v) = Mul (cleanup u) (cleanup v)
  36. cleanup (Div u v) = Div (cleanup u) (cleanup v)
  37. cleanup (Pow u v) = Pow (cleanup u) (cleanup v)
  38. cleanup f = f
  39.  
  40. compute :: Func -> Double -> Double
  41. compute (Const c) _ = c
  42. compute (X) x = x
  43. compute (Add a b) x = compute a x + compute b x
  44. compute (Sub a b) x = compute a x - compute b x
  45. compute (Mul a b) x = compute a x * compute b x
  46. compute (Div u v) x = compute u x / compute v x
  47. compute (Pow a b) x = compute a x ^ (truncate $ compute b x)
  48.  
  49. compute0 :: Func -> Double
  50. compute0 f = compute f 0
  51.  
  52. -- output
  53. instance Show Func where
  54. show (Const c) = show c
  55. show (X) = "x"
  56. show (Add a b) = '(' : show a ++ '+' : show b ++ ")"
  57. show (Sub a b) = '(' : show a ++ '-' : show b ++ ")"
  58. show (Mul a b) = '(' : show a ++ '*' : show b ++ ")"
  59. show (Div a b) = '(' : show a ++ '/' : show b ++ ")"
  60. show (Pow a b) = '(' : show a ++ '^' : show b ++ ")"
Add Comment
Please, Sign In to add comment