arguments - Common Lisp - 给出 &rest 列表作为参数

标签 arguments lisp common-lisp sbcl

由于对一个运动问题的思考,我正在尝试编写一个函数,它接受一个输入数字和一个任意长度的除数列表来测试,以及作为 bool 值的预期整除率(即余数 0),返回如果满足所有期望,则为 true(如果未指定,则默认为 true)。

示例输入:

 (divisible-by 10 (5 t) (4 f) 2) => t

我的阅读导致了为函数创建输入的尝试:

(defun divisible-by (numerator &rest args (&key divisors (divisorp t)))
  (loop...))

我对此类输入类型的简单测试用例以各种方式出错,我通过 Google 和直接在 Stack Overflow 上进行的搜索都没有取得成果,这让我相信我的理解不足以生成正确的关键字。

如能提供有关如何实现此类功能、我的尝试失败的地方或为何无法按照我概述的方式实现此类功能的指示,我们将不胜感激。

最佳答案

除了&rest,你不需要任何东西:

(defun divisible-p (number &rest divisors)
  "Check whether number is divisible by divisors."
  (dolist (spec divisors t) ; For each 'divisor' in divisors
    (etypecase spec
      ;; If divisor is a list, test if modulus of first value is 0
      ;; then compare to second (boolean)
      (cons (unless (eq (zerop (mod number (first spec)))
                        (second spec))
              (return nil)))
      ;; If divisor is an integer, return t if modulus == 0
      (integer (unless (zerop (mod number spec))
                 (return nil))))))

(divisible-p 10 '(5 t) '(4 nil) 2)
==> T
(divisible-p 10 '(5 t) '(4 nil) 2 3)
==> NIL

注意你需要引用列表参数,否则你会得到一个没有函数5的错误。

我不确定你试图通过使用 &key 来完成什么,但它们不能在 CL 中重复,即,如果你写

(defun foo (&key a) (print a))
(foo :a 1 :a 2 :a 3)

只会打印 3,忽略 1 和 2。

关于arguments - Common Lisp - 给出 &rest 列表作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30263516/

相关文章:

lisp - 创建自定义列表反转

c - 在可变参数函数中的断点处停止

arrays - 将数组传递给erlang中的函数

c++ - 成员变量作为默认参数?

string - 从 lisp 中的八位字节解码单个字符

object - 是否有克隆 CLOS 对象的通用方法?

C程序不计算文本文件中的字母频率

macros - 是否有向 "generic"程序员解释 Lisp 宏的简单示例?

macros - Lisp源代码重写系统

common-lisp - 调用加载时filespec中的奇怪符号