我的 Lisp 代码有什么问题?
What's wrong with my Lisp code?
我有一些 lisp 代码,我必须用多种不同的方式编写。我尝试了两种不同的方法,但我不确定为什么它们不起作用。该函数必须接受一个列表,并且 return 只能是该列表中的整数。第一个必须采用映射函数,第二个必须使用循环。这是在 Clisp 中。
这是我的代码。
(defun posint1 (l)
(mapcan #'(lambda (x)
(and (integerp x)
(list l)))))
和
(defun posint1 (l)
(loop for x in (list l)
when (integerp x)
collect x)
(format t "~A " x))))
mapcan
需要至少一个列表参数,并且您在第一个函数中提供了 none(我不能使用名称,因为您调用的两者相同)
第二个函数试图格式化一个变量,x
,它不存在于该范围内。在 loop
中,x 是 (list l)
中的一个元素,它可能应该只是 l
,因为制作一个数字列表并不需要迭代。也许你想要这样的东西:
(defun print-integers (list)
(loop :for x :in list
:when (integerp x)
:collect x :into result
:finally (format t "~A " result)))
;; or using the result as argument
(defun print-integers (list)
(format t
"~A "
(loop :for x :in list
:when (integerp x)
:collect x)))
(print-integers '(-1 0.5 1/3 +inf.0 9)) ; ==> NIL (prints (-1 9)
另请注意,integerp
适用于整数,也适用于负数。该名称暗示您可能想改用 (and (integerp x) (>= x 0))
。
我有一些 lisp 代码,我必须用多种不同的方式编写。我尝试了两种不同的方法,但我不确定为什么它们不起作用。该函数必须接受一个列表,并且 return 只能是该列表中的整数。第一个必须采用映射函数,第二个必须使用循环。这是在 Clisp 中。
这是我的代码。
(defun posint1 (l)
(mapcan #'(lambda (x)
(and (integerp x)
(list l)))))
和
(defun posint1 (l)
(loop for x in (list l)
when (integerp x)
collect x)
(format t "~A " x))))
mapcan
需要至少一个列表参数,并且您在第一个函数中提供了 none(我不能使用名称,因为您调用的两者相同)
第二个函数试图格式化一个变量,x
,它不存在于该范围内。在 loop
中,x 是 (list l)
中的一个元素,它可能应该只是 l
,因为制作一个数字列表并不需要迭代。也许你想要这样的东西:
(defun print-integers (list)
(loop :for x :in list
:when (integerp x)
:collect x :into result
:finally (format t "~A " result)))
;; or using the result as argument
(defun print-integers (list)
(format t
"~A "
(loop :for x :in list
:when (integerp x)
:collect x)))
(print-integers '(-1 0.5 1/3 +inf.0 9)) ; ==> NIL (prints (-1 9)
另请注意,integerp
适用于整数,也适用于负数。该名称暗示您可能想改用 (and (integerp x) (>= x 0))
。