開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Scheme (プログラミング言語)
- Gauche (処理系)
計算機プログラムの構造と解釈(Gerald Jay Sussman(原著)、Julie Sussman(原著)、Harold Abelson(原著)、和田 英一(翻訳)、ピアソンエデュケーション、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の2(データによる抽象の構築)、2.3(記号データ)、2.3.2(例: 記号微分)、問題 2.58-a.を解いてみる。
その他参考書籍
- Instructor's Manual to Accompany Structure & Interpretation of Computer Programs
- プログラミングGauche (Kahuaプロジェクト (著), 川合 史朗 (監修), オライリージャパン)
問題 2.58-a.
コード(BBEdit, Emacs)
sample.scm
#!/usr/bin/env gosh ;; -*- coding: utf-8 -*- ;; これまでに書いた手続き (load "./procedures.scm") (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 (addend s) (car s)) (define (augend s) (caddr s)) (define (sum? x) (and (pair? x) (eq? (cadr x) '+))) (define (product? x) (and (pair? x) (eq? (cadr x) '*))) (define (multiplier p) (car p)) (define (multiplicand p) (caddr 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 (exponent exp) (caddr exp)) (define (exponentiation? exp) (and (pair? exp) (eq? (cadr exp) '**))) (define (deriv exp var) (cond ((number? 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) (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))))))
入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))
$ ./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 $
0 コメント:
コメントを投稿