lisp-如何检查所有列表是否都是数字 [英] lisp -how to check if all the list is numbers

查看:307
本文介绍了lisp-如何检查所有列表是否都是数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了此功能,以检查列表上的所有"var"是否均为数字. 这是我试图做的

I build this function to check if all the "var" on the list are numbers. This what i tried to do

(defun check6 (list) 
(if  (null list) 'TRUE)
(if (not (numberp(first list))) nil)
(check6 (rest list)))

但是总是会出现堆栈溢出.

But always i get stack overflow.

为什么请?

推荐答案

堆栈溢出是由于以下事实造成的:您有几个不相关的if,因此它们产生的值不会被消耗,并且 continue 执行该函数的其余部分.这意味着check6永远不会终止,并导致溢出.

The stack overflow is due to the fact that you have several unrelated if, so that they produce a value which is not consumed and continue to execute the rest of the body of the function. This means that check6 is never terminated and causes the overflow.

如果将代码粘贴到适当的编辑器中,该编辑器将自动对齐代码行,则可能会发现编辑器产生了这种对齐方式:

If you paste your code in a proper editor, which automatically align the lines of code, you could discover that the editor produces this alignment:

(defun check6 (list) 
  (if (null list) 
      'TRUE)             ; only one branch, no else branch, continue to the next form
  (if (not (numberp(first list))) 
      nil)               ; again only one branch, continue to the next form
  (check6 (rest list)))  ; infinite loop

如果要使用if特殊运算符,则应记住它有两种情况,即条件为true时和条件为false时,并应以这种方式嵌套表单(再次正确对齐) ):

If you want to use the if special operator, you should remember that it has two cases, for when the condition is true and when it is false, and should nest the forms in this way (again with the proper alignment):

(defun check6 (list) 
  (if (null list)
      t
      (if (not (numberp (first list)))
          nil
          (check6 (rest list)))))

但是Common Lisp具有连接条件的更方便的语法,cond:

But Common Lisp has the much more convenient syntax for concatenating conditions, cond:

(defun check6 (list) 
  (cond ((null list) t)
        ((not (numberp (first list))) nil)
        (t (check6 (rest list)))))

最后,请注意,还有其他方法可以通过使用迭代来解决问题:

Finally, note that there are other ways to solve your problem, either by using iteration:

(defun check6 (list)
  (loop for element in list always (numberp element)))

或具有更简洁的方式的高级功能:

or with high-level functions, in a still more concise way:

(defun check6 (list)
  (every #'numberp list))

这篇关于lisp-如何检查所有列表是否都是数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆