问题描述
我正在尝试在Common Lisp中编写一个函数,以递归方式将以10为底的数字转换为以列表表示的以8为底的数字.
I'm trying to write a function in Common Lisp to convert a base 10 number into a base 8 number, represented as a list, recursively.
这是我到目前为止所拥有的:
Here's what I have so far:
(defun base8(n)
(cond
((zerop (truncate n 8)) (cons n nil))
((t) (cons (mod n 8) (base8 (truncate n 8))))))
当我输入数字<时此功能可以正常工作8和> -8,但是递归的情况给我带来了很多麻烦.当我尝试将8作为参数(应返回(1 0)
)时,出现错误Undefined operator T in form (T)
.
This function works fine when I input numbers < 8 and > -8, but the recursive case is giving me a lot of trouble. When I try 8 as an argument (which should return (1 0)
), I get an error Undefined operator T in form (T)
.
提前谢谢.
推荐答案
似乎您已经忘记了(defun t ...)
了,或者这不是您打算在cond中使用的功能t
吗?也许是t
真值?
It seems you have forgotten to (defun t ...)
or perhaps it's not the function t
you meant to have in the cond? Perhaps it's t
the truth value?
Common Lisp的双重名称空间性质使t既可以是函数又可以是真值.区别在于您使用的是哪种上下文,并且您显然正在尝试将t
用作函数/宏.
The dual namespace nature of Common Lisp makes it possible for t to both be a function and the truth value. the difference is which context you use it and you clearly are trying to apply t
as a function/macro.
这里是为真值编辑的代码,而不是t
函数:
Here is the code edited for the truth value instead of the t
function:
(defun base8(n)
(cond
((zerop (truncate n 8)) (cons n nil))
(t (cons (mod n 8) (base8 (truncate n 8))))))
(base8 8) ; ==> (0 1)
这篇关于在Lisp中将十进制数转换为八进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!