Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data Func = X | Const Double | Add Func Func | Sub Func Func | Mul Func Func | Div Func Func | Pow Func Func
- derive :: Func -> Func
- derive (Const _) = Const 0
- derive (X) = Const 1
- derive (Add u v) = Add (derive u) (derive v) -- u'(x) + v'(x)
- derive (Sub u v) = Sub (derive u) (derive v) -- u'(x) - v'(x)
- derive (Mul u v) = Add (Mul (derive u) v) (Mul u (derive v)) -- u'(x) * v(x) + u(x) * v'(x)
- 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)²
- derive (Pow f (Const x)) = Mul (Const x) (Mul (derive f) (Pow f (Sub (Const x) (Const 1))))
- -- very basic reduction by removing obvious stuff like x * 0
- cleanup :: Func -> Func
- cleanup (Add (Const 0) f) = cleanup f
- cleanup (Add f (Const 0)) = cleanup f
- cleanup (Sub f (Const 0)) = cleanup f
- cleanup (Mul (Const 1) f) = cleanup f
- cleanup (Mul f (Const 1)) = cleanup f
- cleanup (Mul (Const 0) f) = Const 0
- cleanup (Mul f (Const 0)) = Const 0
- cleanup (Pow f (Const 0)) = Const 1
- cleanup (Pow f (Const 1)) = cleanup f
- -- calculation
- cleanup (Add (Const a) (Const b)) = Const (a + b)
- cleanup (Sub (Const a) (Const b)) = Const (a - b)
- cleanup (Mul (Const a) (Const b)) = Const (a * b)
- cleanup (Div (Const a) (Const b)) = Const (a / b)
- cleanup (Pow (Const a) (Const b)) = Const (a ^ truncate b)
- -- catch-alls
- cleanup (Add u v) = Add (cleanup u) (cleanup v)
- cleanup (Sub u v) = Sub (cleanup u) (cleanup v)
- cleanup (Mul u v) = Mul (cleanup u) (cleanup v)
- cleanup (Div u v) = Div (cleanup u) (cleanup v)
- cleanup (Pow u v) = Pow (cleanup u) (cleanup v)
- cleanup f = f
- compute :: Func -> Double -> Double
- compute (Const c) _ = c
- compute (X) x = x
- compute (Add a b) x = compute a x + compute b x
- compute (Sub a b) x = compute a x - compute b x
- compute (Mul a b) x = compute a x * compute b x
- compute (Div u v) x = compute u x / compute v x
- compute (Pow a b) x = compute a x ^ (truncate $ compute b x)
- compute0 :: Func -> Double
- compute0 f = compute f 0
- -- output
- instance Show Func where
- show (Const c) = show c
- show (X) = "x"
- show (Add a b) = '(' : show a ++ '+' : show b ++ ")"
- show (Sub a b) = '(' : show a ++ '-' : show b ++ ")"
- show (Mul a b) = '(' : show a ++ '*' : show b ++ ")"
- show (Div a b) = '(' : show a ++ '/' : show b ++ ")"
- show (Pow a b) = '(' : show a ++ '^' : show b ++ ")"
Add Comment
Please, Sign In to add comment