Skip to content

Instantly share code, notes, and snippets.

@5outh
Last active December 16, 2015 20:10
Show Gist options
  • Save 5outh/5490810 to your computer and use it in GitHub Desktop.
Save 5outh/5490810 to your computer and use it in GitHub Desktop.
derivative function
derivative :: (Num a) => Expr a -> Expr a
derivative (Var c) = Const 1
derivative (Const x) = Const 0
--product rule (ab' + a'b)
derivative (a :*: b) = (a :*: (derivative b)) :+: (b :*: (derivative a)) -- product rule
--power rule (xa^(x-1) * a')
derivative (a :^: (Const x)) = ((Const x) :*: (a :^: (Const $ x-1))) :*: (derivative a)
derivative (a :+: b) = (derivative a) :+: (derivative b)
-- quotient rule ( (a'b - b'a) / b^2 )
derivative (a :/: b) = ((derivative a :*: b) :+: (negate' (derivative b :*: a)))
:/:
(b :^: (Const 2))
derivative expr = error "I'm not a part of your system!" -- unsupported operation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment