tkkのページ
-個人ページです。-
今週は忙しくて参加できなかったのですがこれからはなんとか参加していきたいと思います
練習問題解答
Exercise1-2
(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7)))
;; 実行結果
gosh> -37/150
Exercise1-3
(define (square x)
(* x x))
(define (func x y z)
(if (> x y)
(if (> y z)
(+ (square x) (square y))
(+ (square x) (square z)))
(if (> z x)
(+ (square y) (square z))
(+ (square y) (square x)))))
;; 実行結果
(func 3 1 2)
gosh> 13
(func 3 4 9)
gosh> 97
Exercise1-4
(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))
;; 実行結果
(a-plus-abs-b 2 3)
gosh> 5
(a-plus-abs-b 2 -3)
gosh> 5
;; a-plus-abs-b はbが0より大きければa+b,
;; bが0以下であればa-b,つまりaとbの絶対値の和を返す
Exercise1-5
(define (p) (p))
(define (test x y)
(if (= x 0)
0
y))
;; 実行結果
(test 0 (p))
;; 終了しない
;; 作用的順序の評価を使う解釈系ではまず(test 0 (p))の0と(p)が評価され、
;; (p)は自分自身をさしているので無限ループに陥る.
;; 正規的順序の評価を使う解釈系では先に(if (= x 0)...が評価され
;; ここでは(= x 0)が真なので0が評価され0が返される。結果的に(p)は評価されず、無限ループには陥らない.
Exercise1-6
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
(define (sqrt-iter guess x)
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
(define (improve guess x)
(average guess (/ x guess)))
(define (average x y)
(/ (+ x y) 2))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
(define (sqrt x)
(sqrt-iter 1.0 x))
;; 実行結果
(sqrt 4)
;; 終了しない
最終更新:2007年12月01日 22:47