Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Last active October 31, 2019 14:50
Show Gist options
  • Save chelseatroy/2dff98b3fd4105588f2861396ec0c2b7 to your computer and use it in GitHub Desktop.
Save chelseatroy/2dff98b3fd4105588f2861396ec0c2b7 to your computer and use it in GitHub Desktop.
Derivative
(define (menq item sequence)
(cond ((null? sequence) false)
((eq? item (car sequence)) sequence)
(else (memq item (cdr sequence)))))
(list 'a 'b 'c)
(equal? '(this is a list) '(this is a list))
(equal? '(this is a list) '(this '(is a) list))
; 2.54
(define (append seq1 seq2)
(if (null? seq1)
seq2
(cons (car seq1) (append (cdr seq1) seq2))))
(append '(1 '(2 3)) '(4 5 6))
; 2.56
(define (variable? exp)
(symbol? exp))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2)))
(define (sum? exp)
(and (pair? exp) (eq? (car exp) '+)))
(define (addend exp)
(cadr exp))
(define (augend exp)
(caddr exp))
(define (make-sum a1 a2)
(list '+ a1 a2))
(define (make-exponentiation b n)
(cond ((=number? exponent 0) 1)
((=number? exponent 1) b)
(else (list( '^ base exponent))))
(define (product? exp)
(and (pair? exp) (eq? (car exp) '*)))
(define (multiplier exp)
(cadr exp))
(define (multiplicand exp)
(caddr exp))
(define (make-product m1 m2)
(list '* m1 m2))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (exponentiation? exp)
(and (pair? exp) (eq? (car exp) '**)))
(define (base exp)
(cadr exp))
(define (exponent exp)
(caddr exp))
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
((exponentiation? exp)
(make-product (exponent exp)
(make-product
(make-exponentiation (base exp) (- (exponent exp) 1))
(deriv (base exp) var))))
(else
(error "unknown expression type——DERIV" exp))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment