Defining remove-if and remove-if-not


#1

Two functions I find myself using frequently in Common Lisp are remove-if and remove-if-not, which filter items from a list depending on whether they satisfy, or don’t satisfy, a predicate you specify.

For example:

> (remove-if #'evenp '(1 2 3 4 5 6 7))
(1 3 5 7)

> (remove-if-not #'evenp '(1 2 3 4 5 6 7))
(2 4 6)

They’re not provided in uLisp, but fortunately they’re very easy to define using mapcan:

(defun remove-if (fn lis)
  (mapcan #'(lambda (item) (unless (funcall fn item) (list item))) lis))

(defun remove-if-not (fn lis)
  (mapcan #'(lambda (item) (when (funcall fn item) (list item))) lis))