解答例

■ ドリル

;(1) 
(define sum
  (lambda (lst)
    (if (null? lst)
      0
      (+ (car lst) (sum (cdr lst))))))

; 別解
(define sum
  (lambda (lst)
    (define sum2
      (lambda (lst1 ans)
        (if (null? lst1)
            ans
            (sum2 (cdr lst1) (+ ans (car lst1))))))
    (sum2 lst 0)))

;(2)
(define size
  (lambda (lst)
    (if (null? lst)
        0
        (+ 1 (size (cdr lst))))))

; 別解
(define size
  (lambda (lst)
    (define size2
      (lambda (lst1 ans)
        (if (null? lst1)
            ans
            (size2 (cdr lst1) (+ 1 ans)))))
    (size2 lst 0)))

; (3)
(define average
  (lambda (lst)
    (if (null? lst)
        #f
        (/ (sum lst) (size lst)))))

; (4)
(define even
  (lambda (lst)
    (if (null? lst)
        ()
        (if (even? (car lst))
            (cons (car lst) (even (cdr lst)))
            (even (cdr lst))))))

; (5)
(define skip
  (lambda (lst)
    (if (null? lst)
        ()
        (cons (car lst) (skip1 (cdr lst))))))

(define skip1
  (lambda (lst)
    (if (null? lst)
        ()
        (skip (cdr lst)))))

; (6)
(define my-reverse
  (lambda (lst)
    (define reverse2
      (lambda (lst stack)
        (if (null? lst)
            stack
            (reverse2 (cdr lst) (cons (car lst) stack)))))
    (reverse2 lst ())))

; (7)
(define draw-four
  (lambda (lst)
    (define draw-four3
      (lambda (lst1 sum max)
        (if (null? lst1)
            (if (< sum max)
                max
                sum)
            (if (= (car lst1) 4)
                (draw-four3 (cdr lst1) (+ sum 4) max)
                (if (< sum max)
                  (draw-four3 (cdr lst1) 0 max)
                  (draw-four3 (cdr lst1) 0 sum))))))
    (draw-four3 lst 0 0)))

■ A4用紙のサイズ

paper-a-size01 は途中に使う関数。
(define paper-a-size01
  (lambda (sl)
    (cons (truncate (/ (cdr sl) 2)) (car sl))))

(define paper-a-size
  (lambda (n)
    (if (= 0 n)
        (cons 841 1189)
        (paper-a-size01 (paper-a-size (- n 1))))))

下記は、途中に使う関数を内部に移したもの。
(define paper-a-size
  (lambda (n)
    (if (= 0 n)
        (cons 841 1189)
        ((lambda (sl)
           (cons (truncate (/ (cdr sl) 2)) (car sl)))
         (paper-a-size-b (- n 1))))))

■ パスカルの三角形

add-next とその改造版の add-next2 を見くらべてみよう。
(define add-next
  (lambda (lst)
    (if (null? lst)
        ()
        (if (null? (cdr lst))
          ()
          (cons (+ (car lst) (car (cdr lst))) (add-next (cdr lst)))))))

(define add-next2
  (lambda (lst)
    (if (null? (cdr lst))
        lst
        (cons (+ (car lst) (car (cdr lst))) (add-next2 (cdr lst))))))

(define pascal-list
 (lambda (n)
   (if (= 1 n)
       (list 1 1)
       (cons 1 (add-next2 (pascal-list (- n 1)))))))


2007.6.22 by tokuhisa