0

我正在尝试编写一个函数,该函数接受一个或多个整数并返回与第一个参数具有相同奇偶校验的所有参数的列表,例如

(same-parity 1 2 3 4 5 6 7)->(1 3 5 7)
(same-parity 2 3 4 5 6)->(2 4 6). 

我的代码是

(define (same-parity g . w)
    (define (iter-parity items)
        (if (= (length items) 1)
            (if (= (remainder items 2) (remainder g 2))
                item
                '())
            (if (= (remainder g 2) (remainder (car items) 2))
                (cons (car items) (iter-parity (cdr items)))
                (iter-parity (cdr items)))))
    (cons g (iter-parity w)))

尝试此操作时(same-parity (list 1 2 3 4)),我收到一条错误消息:作为第一个参数传递给汽车的对象 () 不是正确的类型。

我可以告诉我发生了什么事吗?

4

1 回答 1

2

你的代码

这是一个重构建议,与您的基本结构保持一致:

(define (same-parity g . w)
  (define filter-predicate? (if (odd? g) odd? even?))

  (define (iter-parity items)
    (if (null? items)
        '()
        (if (filter-predicate? (car items))
            (cons (car items) (iter-parity (cdr items)))
            (iter-parity (cdr items)))))

  (cons g (iter-parity w)))

请注意,它更惯用

  • 使用程序odd?even?不是remainder
  • 当列表为空时作为基本情况,而不是当它只有一项时(在您的代码中,这显然避免了重复作为积极效果)。

此外,由于 Scheme 中有一个内置filter过程,您可以将其表示为:

(define (same-parity g . w)
  (cons g (filter (if (odd? g) odd? even?) w)))

你的问题

至于您的问题(same-parity (list 1 2 3 4)):您需要(如您的规范中所述)像这样使用您的程序

 (same-parity 1 2 3 4)

或在apply这里使用:

> (apply same-parity (list 1 2 3 4))
'(1 3)

因为apply会将(same-parity (list 1 2 3 4))(1个参数,一个列表)转换为(same-parity 1 2 3 4)(4个参数)。

于 2014-03-31T14:52:07.693 回答