比方说,我们希望使用一个需要谓词的函数,但是出于某种原因,我们对函数的其他特性(比如:start和:end参数)感兴趣,所以我们需要提供一个谓词,它总是返回true。
很明显,这根本不是问题:
CL-USER> (defparameter *list* '(0 1 2 3 4 5))
*LIST*
CL-USER> (remove-if (lambda (x) t) *list* :start 1 :end 3)
(0 3 4 5)很管用,但一点也不漂亮。我们可能会收到不使用变量x的丑陋信息。因为我喜欢美,所以我很好奇是否有“总是t”的谓词?
我们可以给它下定义:
(defun tp (&rest rest)
(declare (ignore rest))
t)..but可能是存在的吗?
发布于 2014-06-04 13:36:57
您正在寻找函数constantly,它接受参数并返回始终返回该值的函数。然后,您需要的谓词是(constantly t)。因此:
CL-USER> (remove-if (constantly t) '(0 1 2 3 4 5) :start 1 :end 3)
(0 3 4 5)constantly上的注释表明,您在建议的实现方面绝对是正确的。(不过,通过添加(declare (ignore …)),您做得更好。)
备注: 经常可以通过以下方式来界定: (经常(object) #'(lambda (&rest参数)对象))
写完这篇文章后,我突然意识到这可能是一个重复。我没有找到合适的副本,而是找到了一个类似的、更具体的问题,希望在Is there a common lisp macro for popping the nth element from a list?位置删除单个元素,其中Rainer Joswig's answer包括:
删除列表的第n个元素: (删除-n(列表n) (删除-如果(经常t)列表:开始n:结束(1+ n)
这实际上只是该方法的一个推广,因为您处理的是任意的序列边界。因此,我们可以(使边界参数类似于subseq):
(defun remove-subseq (sequence &optional (start 0) end)
(remove-if (constantly t) sequence :start start :end end))
(defun remove-nth (sequence n)
(remove-subseq sequence n (1+ n)))CL-USER> (remove-subseq '(0 1 2 3 4 5) 1 3)
(0 3 4 5)
CL-USER> (remove-nth '(0 1 2 3 4 5) 3)
(0 1 2 4 5)https://stackoverflow.com/questions/24037628
复制相似问题