3

我在 Scheme 中实现这个程序时遇到了一些麻烦,尽管我认为我已经完成了 90% 的工作。不幸的是,我需要对此有点模糊,因为这是一项家庭作业。我想(ABCD)返回(BD)。但我收到一条错误消息,指出作为参数传递给安全车的对象 () 不是一对 | “这是我的代码:

(DEFINE (other_el lis)
  (COND
   (( NULL? lis ) '())
   ((LIST? lis)
    (append (CADR lis) (other_el (CDR lis))))
   (ELSE (show " USAGE: (other_el [LIST])"))))
4

2 回答 2

2

这个比你问的上一个问题要简单得多。请记住,您不必在每一步都计算长度(这可能非常低效),或者使用附加操作来解决它(使用 acons代替);这是答案的结构,因为它看起来像家庭作业,所以我让您填写空白:

(define (every-other lst)
  (if (or <???>                    ; if the list is empty 
          <???>)                   ; or the list has a single element
      <???>                        ; then return the empty list
      (cons <???>                  ; otherwise `cons` the second element
            (every-other <???>)))) ; and recursively advance two elements

如果您需要先进行一些错误检查,请在确定参数正确后使用另一个函数并调用上述过程:

(define (other_el lst)
  (if (list? lst)
      (every-other lst)
      (error "USAGE: (other_el [LIST])")))

像这样使用它:

(other_el '(A B C D E G))
=> '(B D G)
于 2012-11-10T04:01:05.453 回答
1

在我演示正确的代码之前,应该提到此代码的一些小问题。

  1. 不要大写过程的名称,例如 cdr 和 Scheme 中的 define。
  2. 不要手动显示错误消息。使用例外。
  3. 你应该总是缩进你的代码。(编辑:看起来有人编辑了问题的代码以包含缩进)

无论如何,这是您正在寻找的功能:

(define (evens lst)
  (if (or (null? lst)             ; if the list is empty 
          (null? (cdr lst)))      ; or the list has a single element
      '()                         ; then return the empty list
      (cons (cadr lst)            ; otherwise `cons` the second element
            (evens (cddr lst))))) ; and recursively advance two elements

我在 DrRacket 5.3 中测试了该函数,并且 (evens '(ABCD)) 返回 '(BD),如您指定的那样。如果您有任何问题,请告诉我。祝你的家庭作业好运!

于 2012-11-10T02:28:40.807 回答