Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!
tweet

By: a guest on Apr 2nd, 2010  |  syntax: Haskell  |  size: 1.20 KB  |  views: 142  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1.
2.
3. data Func = Variable [Char] | Number Float | Plus Func Func | Pow Func Func | Minus Func | Mul Func Func | Div Func Func | Exp Func | Ln Func
4.
5. instance Show Func where
6.     show (Variable v) = v
7.     show (Number n) = show n
8.     show (Minus a) = "-" ++ show a
9.     show (Plus a b) = "(" ++ show a ++ "+" ++ show b ++ ")"
10.     show (Pow a b)  = "(" ++ show a ++ "^" ++ show b ++ ")"
11.     show (Mul a b)  = "(" ++ show a ++ "*" ++ show b ++ ")"
12.     show (Div a b)  = "(" ++ show a ++ "/" ++ show b ++ ")"
13.     show (Exp a)  = "(e^" ++ show a ++ ")"
14.     show (Ln a) = "ln(" ++ show a ++ ")"
15.
16. diff :: Func -> Func -> Func
17. diff _ (Number _) = Number 0
18. diff (Variable v) (Variable v2) = if v == v2 then Number 1 else Number 0
19. diff var (Plus a b) = Plus (diff var a) (diff var b)
20. diff var (Minus a) = Minus (diff var a)
21. diff var (Mul a b) = Plus (Mul a (diff var b)) (Mul (diff var a) b)
22. diff var (Div a b) = Div (Plus (Mul (diff var a) b) (Minus (Mul a (diff var b)))) (Pow b (Number 2))
23. diff var m@(Exp a) = Mul (diff var a) m
24. diff var (Ln a) = Mul (diff var a) (Div (Number 1) a)
25. diff var (Pow a b) = diff var \$ Exp \$ Mul b \$ Ln a
26.
27.
28. main = print \$ diff (Variable "x") \$ Ln \$ Pow (Variable "x") (Number 2)
clone this paste RAW Paste Data
Top