CSawy
CSawy

Reputation: 924

lisp apply append

i worte this function to remove numbers from a list x

(defun rm-nums (x)
  (cond
    ((null x) nil)
    (t (mapcar 'numberp x))))

however when i enter (rm-nums '(32 A T 4 3 E)) returns (T NIL NIL T T NIL)

i want it instead of returning T or Nil, i want it to return the values that caused NIL only [which are not numbers] so this example should return (A T E) i am supposed to use mapcar WITHOUT recursion or iteration or the bultin function "remove-if"

i think it is related to something called apply-append but i know nothing about it. any help?

Upvotes: 3

Views: 1832

Answers (1)

C. K. Young
C. K. Young

Reputation: 223023

I think your course had this in mind:

(defun my-remove-if (pred lst)
  (apply #'append (mapcar (lambda (x)
                            (and (not (funcall pred x))
                                 (list x)))
                          lst)))

It does use apply and append and mapcar, like you said. Example usage:

(my-remove-if #'numberp '(32 a t 4 3 e))
=> (a t e)

More idiomatic solution suggested by Rörd:

(defun my-remove-if (pred lst)
  (mapcan (lambda (x)
            (and (not (funcall pred x))
                 (list x)))
          lst))

Upvotes: 5

Related Questions