创建一个 lisp 函数,它给出一个列表中的偶数列表

creating a lisp function that gives a list of even number from a list

我想为 class 创建一个函数,它将两个参数 LL1 作为列表,并将 L 中的所有偶数放入 L1.

我已经尝试了几个小时让它工作,但不幸的是我做不到。

这是我的方案代码:

(define (pair L L1)
  (cond
   ((and (not (empty? L)) (= (modulo (first L) 2) 0))
    (begin (append (list (first L)) L1) (pair (rest L) L1)))
   ((and (not (empty? L)) (= (modulo (first L) 2) 1))
    (pair (rest L) L1))
   (else L1)
   ))

我假设您想使用 L1 作为累加器,最后 return 它的内容。

关于您的代码:

  1. 如果L为空(null?),在cond的第一个子句中检查一次就足够了。

  2. append 当你想附加一个列表时很好。在您的情况下,您附加了一个元素,因此 cons 更好。

  3. 您不必取 modulo 个数字来检查它是否为偶数。内置 even? 谓词。

所以,经过所有这些考虑,您的代码应该如下所示:

(define (pair L L1)
  (cond ((null? L) L1)
        ((even? (first L))
         (pair (rest L) (cons (first L) L1)))
        (else (pair (rest L) L1))))

现在让我们测试一下:

> (pair '(0 1 2 3 4 5 6 7) '())
(6 4 2 0)

如您所见,它 return 的数字顺序相反。这是因为当我们从头到尾向下移动列表 L 时,我们 cons 新值到列表 L1 的头部(而不是尾部,就像 append 那样) .要修复它,在第一个 cond 子句中 (reverse L1) 就足够了,而不是简单地 returning L1.

我强烈推荐 "Little Schemer" 这本书。读完之后,你即使在睡梦中也能写出任何类型的递归函数;)