定义一个递归函数来计算通用Lisp中一个数字的位数 [英] Define a recursive function to count the numbers of digits in a number in common lisp
问题描述
这是我直到现在为止所执行的操作,它告诉我它不是列表类型。
This is what I did until now it tells me that it is not of type list.
(defun number_list(n)
(setf x
(if (zerop (truncate n 10))
(list n)
(append (number_list (truncate n 10)) (list (mod n 10)))))
(length x))
当我删除(长度x )我可以看到结果是一个列表。
When I remove the (length x) I can see that the result is a list however.
不胜感激。
推荐答案
您的解决方案使用全局变量 x
,这通常不是一个好主意,尤其是在递归函数中。然后,您创建一个列表以计算位数。
Your solution uses a global variable x
, which is generally a bad idea, especially in recursive functions. Then, you create a list in order to count the number of digits. This is not really necessary.
使用列表
如果要使用列表,建议您将问题分为两部分:
If you want to work with a list, I suggest you split the problem in 2 parts:
1。将数字转换为列表
如果删除 setf x
,您的函数将对此非常有效:
Your function works well for this if you remove setf x
:
(defun number_list(n)
(if (zerop (truncate n 10))
(list n)
(append (number_list (truncate n 10)) (list (mod n 10)))))
2。计数位数
(defun numdigits (n)
(length (number_list n))).
替代
但是我建议一个简单的递归定义,例如:
But I would suggest a simple recursive definition such as:
(defun numdigits (n)
(if (< -10 n 10)
1
(1+ (numdigits (truncate n 10)))))
这篇关于定义一个递归函数来计算通用Lisp中一个数字的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!