Common Lisp - 将函数应用于列表中的每个其他元素

时间:2016-08-07 17:52:14

标签: loops lisp common-lisp

我想将函数(* x 2)应用于列表中的每个其他元素,并使用 loop 宏返回整个列表。我到目前为止提出的解决方案是:

(defun double-every-other (xs)
  (loop for x in xs by #'cddr collect (* x 2)))

但是,这将使每个其他元素加倍,并且只返回加倍的元素,所以如果我执行:

(double-every-other '(1 2 3 4))

结果将是:

'(4 8)

但我希望结果是:

'(1 4 3 8)

有没有办法可以使用(循环)?

5 个答案:

答案 0 :(得分:7)

另一个数学较少的版本:

(defun double-every-other (list)
  (loop
     for (a b) on list by #'cddr
     collect a
     when b collect (* b 2)))

(double-every-other '(1 2 3 4))
=> (1 4 3 8)

(double-every-other '(1 2 3 4 5))
=> (1 4 3 8 5)

显然,你不能像其他答案那样容易抽象N(如果你在想“宏”,现在就停止)。在这里,我们使用on关键字进行迭代,这意味着依次访问每个子列表。由于我们使用by #'cddr,因此会跳过其他每个子列表。解构语法(a b)绑定访问列表的第一个和第二个元素。

答案 1 :(得分:5)

例如,您可以在扫描列表时测试整数增加:

(defun double-every-other (xs)
  (loop for x in xs
     for i from 1
     if (oddp i)
     collect x
     else collect (* x 2)))

答案 2 :(得分:3)

(defun double-every-other (xs)
  (loop for x in xs
        for doublep = nil then (not doublep)
        collect (if doublep (* x 2) x)))

答案 3 :(得分:2)

另一个版本,完全没有循环:

(defun make-cycled (&rest items)
  (setf (cdr (last items)) items))

(mapcar #'funcall
        (make-cycled #'identity (lambda (x) (* 2 x)))
        '(10 9 8 7 6 5 4 3))

;;=> (10 18 8 14 6 10 4 6)

答案 4 :(得分:0)

您可以使用loop""列表迭代原语。这需要一个循环变量列表,这些循环变量将被涂抹"在列表中,最后一个是整个剩余列表的尾部。如果我们有奇数个参数,则必须使用条件loop for以避免乘以nil

(defun double-every-other (list)
  (loop for (single double tail) on list by #'cddr
    if (null double)
      collect single
    else
      append (list single (* 2 double))))

如果我们尝试运行它:

* (double-every-other '(1 2 3 4 5))

(1 4 3 8 5)
相关问题