## 2014年4月24日木曜日

### Scheme - データによる抽象の構築(記号データ(記号微分(前置記法と中置記法)))

その他参考書籍

コード(BBEdit, Emacs)

sample.scm

```#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-

;; これまでに書いた手続き

(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2))
(+ a1 a2))
(else (list a1 '+ a2))))

(define (sum? x)
(and (pair? x) (eq? (cadr x) '+)))

(define (product? x)
(and (pair? x) (eq? (cadr x) '*)))

(define (multiplier p) (car p))

(define (make-product m1 m2)
(cond ((or (=number? m1 0)
(=number? m2 0))
0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1)
(number? m2))
(* m1 m2))
(else (list m1 '* m2))))

(define (make-exponentiation b e)
(cond ((=number? e 0) 1)
((=number? e 1) b)
(else
(list b '** e))))

(define (base exp) (car exp))

(define (exponentiation? exp)
(and (pair? exp)

(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp
var)
1
0))
((sum? 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)
(let ((n (exponent exp))
(u (base exp)))
(make-product
(make-product n
(make-exponentiation u
(make-sum  n -1)))
(deriv u var))))
(else
(error "unknown expression type -- DERIV" #?=exp))))

(for-each (lambda (exp)
(print "(derive " exp " x) = "
(deriv exp 'x)))
(list '(x + 3)
'(x * y)
'((x * y) * (x + 3))
'(x + (3 * (x + (y + 2))))))
```

```\$ ./sample.scm
(derive (x + 3) x) = 1
(derive (x * y) x) = y
(derive ((x * y) * (x + 3)) x) = ((x * y) + (y * (x + 3)))
(derive (x + (3 * (x + (y + 2)))) x) = 4
\$
```