【发布时间】:2014-08-11 00:05:48
【问题描述】:
set-difference 用作过滤器功能,但仅适用于列表。数组和字符串是怎么回事?这些类型的数据是否有类似的功能?如果没有这样的功能,实现它们的正确方法是什么?
现在我使用这个宏来处理任何序列作为一个列表(有时它很有用):
(defmacro treat-as-lists (vars &body body)
(let ((type (gensym)))
`(let ((,type (etypecase ,(car vars)
(string 'string)
(vector 'vector)
(list 'list)))
,@(mapcar (lambda (x) `(,x (coerce ,x 'list)))
vars))
(coerce (progn ,@body) ,type))))
我的filter:
(defun filter (what where &key key (test #'eql))
(treat-as-lists (what where)
(set-difference where what :key key :test test)))
例子:
CL-USER> (filter "cat" "can you take this cat away?")
"n you ke his wy?"
CL-USER> (filter #(0 1) #(1 5 0 1 9 8 3 0))
#(5 9 8 3)
【问题讨论】:
-
数组和字符串的标准中没有类似的函数,但正如您所发现的,您可以定义自己的函数。请注意,这些强制使数组和字符串的使用毫无意义。
-
我不喜欢对列表的强制,因为它涉及大量的 consing 只是为了能够表达集合差异的想法。
标签: arrays string lisp filtering common-lisp