Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lisp apply append

Tags:

append

apply

lisp

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?

like image 679
CSawy Avatar asked Mar 11 '26 08:03

CSawy


1 Answers

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))
like image 106
Chris Jester-Young Avatar answered Mar 13 '26 01:03

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!