2015年2月4日水曜日

開発環境

計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原書: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の1(手続きによる抽象の構築)、1.2(手続きとその生成するプロセス)、1.2.4(べき乗)、問題 1.18.を解いてみる。

その他参考書籍

問題 1.18.

コード(BBEdit, Emacs)

sample18.scm

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

(define even? (lambda (n) (= (remainder n 2) 0)))
(define double (lambda (x) (+ x x)))
(define halve (lambda (x) (/ x 2)))

(define (fast-* a b result)
  (cond ((= b 0) result)
        ((even? b)
         (fast-* (double a)
                 (halve b)
                 result))
        (else
         (fast-* a
                 (- b 1)
                 (+ a result)))))
(define (* a b)
  (fast-* a b 0))

(print (* 0 10))
(print (* 10 0))
(print (* 0 11))
(print (* 11 0))       
(print (* 5 10))
(print (* 10 5))
(print (* 10 50))
(print (* 50 10))
(print (* 51 101))
(print (* 101 51))

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

$ ./sample18.scm
0
0
0
0
50
50
500
500
5151
5151
$

0 コメント:

コメントを投稿