;; Copyright (C) 2009  Luca Saiu
;; 
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

(define (derivative expression variable)
  (if (or (symbol? expression)
          (number? expression))
      (if (eq? expression variable)
          1
          0)
      (derivative-of-application (car expression) (cdr expression) variable)))

(define (derivative-of-application function-name parameters variable)
  (case function-name
    ((+ -)
     (if (= (length parameters) 2)
         `(,function-name ,(derivative (car parameters) variable)
                          ,(derivative (cadr parameters) variable))
         (error function-name " must have two parameters")))
    ((*)
     (if (= (length parameters) 2)
         `(+ (* ,(derivative (car parameters) variable)
                ,(cadr parameters))
             (* ,(derivative (cadr parameters) variable)
                ,(car parameters)))
         (error "* must have two parameters")))
    ((/)
     (if (= (length parameters) 2)
         `(/ (- (* ,(derivative (car parameters) variable)
                   ,(cadr parameters))
                (* ,(derivative (cadr parameters) variable)
                   ,(car parameters)))
             (* ,(cadr parameters)
                ,(cadr parameters)))
         (error "/ must have two parameters")))
    ((sin)
     (if (= (length parameters) 1)
         `(* (cos ,(car parameters))
             ,(derivative (car parameters) variable))
         (error "sin must have one parameter")))
    ((cos)
     (if (= (length parameters) 1)
         `(- 0 (* (cos ,(car parameters))
                  ,(derivative (car parameters) variable)))
         (error "sin must have one parameter")))
    ((tan)
     (if (= (length parameters) 1)
         (derivative `(/ (sin ,(car parameters))
                         (cos ,(car parameters)))
                     variable)
         (error "tan must have one parameter")))
    (else
     (error "unknown function" function-name))))
