defun with a list as argument

我怕爱的太早我们不能终老 提交于 2019-12-04 06:39:54

/ takes as arguments one or more numbers, but in your code you're passing it a list - clearly this will not work. The function apply is your friend here - (apply #'foo a b (list c d e)) is equivalent to (foo a b c d e). Note the the arguments to apply between the function to use and the final list are optional, so (apply #'/ '(20 2 5)) is equivalent to (/ 20 2 5).

Also, your attempt at removing zeros will not work. dolist is evaluating its body for each item in the argument list elements, but you're not actually doing anything to change the content of elements (the result of evaluating dolist s body is not reassigned to the source element as you seem to expect).

The functions remove-if (and its destructive counterpart, delete-if) are what you are looking for. The following shows how to use it (it takes lots of optional arguments, which you don't need to worry about for this purpose).

(defun divtest (elements)
  (apply #'/ (remove-if #'zerop elements)))

Also note that this won't behave correctly if the elements list has zero as its first element (assuming I understand what the function's meant to do). So you might instead want something like

(defun divtest (elements)
  (apply #'/ (first elements) (remove-if #'zerop (rest elements))))

See the Hyperspec for more details.

Or you can write it like this

(defun divtest (elements)
  (if (member 0 elements)
      0
      (apply #'/ elements)))
(block exit
  (reduce #'/ '(1 2 3 0 5)
          :key (lambda (x)
                 (if (zerop x)
                     (return-from exit 0)
                   x))))

Try (apply / elements) in place of (/ elements). I think(?) that should work in most dialects of Lisp.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!