計算機プログラムの構造と解釈 第二版 P59 問題2.20

この問題はとてもおもしろい。
可変引数っていうんだっけか?そういうのを実装できていい。


そんでこの問題の目的は
・一つかそれを越える個数の整数をとり、先頭と同じ偶奇性をもつ引数のリストを返す手続きparityを定義する。


まずは、ドット末尾記法をつかって引数をリストにするってのをやる。
次に、手続きのなかで、リストの先頭の値を拾って、偶数か奇数か判断する。
そんで何とかする。


みたいな感じかな。


実装

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

(use ggc.debug.trace)
(use math.mt-random)

(define nil '())

(define (same-parity . w)
 (define (same-parity-in items result f)
    (if (null? items)
      result
      (if (f (car items))
        (same-parity-in (cdr items) (append  result (list (car items))) f)
        (same-parity-in (cdr items) result f))))
  (if (even? (car w)) 
    (same-parity-in w nil even?)
    (same-parity-in w nil odd?)))
 
;; main
(define (main args)
  (display "(same-parity 1 2 3 4 5 6 7 8 9 10): ")
  (display (same-parity 1 2 3 4 5 6 7 8 9 10))
  (newline)

  (display "(same-parity 2 3 4 5 6 7 8 9 10): ")
  (display (same-parity 2 3 4 5 6 7 8 9 10))
  (newline)
  0)


実行

(same-parity 1 2 3 4 5 6 7 8 9 10): (1 3 5 7 9)
(same-parity 2 3 4 5 6 7 8 9 10): (2 4 6 8 10)


OK