2014年4月22日火曜日

開発環境

計算機プログラムの構造と解釈(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.56.を解いてみる。

その他参考書籍

問題 2.56.

コード(BBEdit, Emacs)

sample.scm

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

;; これまでに書いた手続き
(load "./procedures.scm")

(define (exponentiation? exp)
  (and (pair? exp)
       (eq? (car exp) '**)))

(define (base exp) (cadr exp))

(define (exponent exp) (caddr exp))

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

(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 "(deriv " exp " 'x) = " (deriv exp 'x)))
          (list '(** x 0)
                '(** x 1)
                '(** x 2)
                '(** x 10)
                '(** x y)))

入出力結果(Terminal(gosh), REPL(Read, Eval, Print, Loop))

$ ./sample.scm
(deriv (** x 0) 'x) = 0
(deriv (** x 1) 'x) = 1
(deriv (** x 2) 'x) = (* 2 x)
(deriv (** x 10) 'x) = (* 10 (** x 9))
(deriv (** x y) 'x) = (* y (** x (+ y -1)))
$

0 コメント:

コメントを投稿