katalin
katalin

Reputation: 1

How to replace sublists with NIL in Lisp?

I have a project in Common Lisp and I need help.

I have for example the list:

(( C ) ( A C ) (  ) (  ) ( P B ) (  ) ( C C A ) ( A ))

and I want to replace all the sublists except the sublist which contains the element P. There's only one P in the whole list and it's always the first element in a sublist. So the result should be:

(NIL NIL NIL NIL ( P B ) NIL NIL NIL)

Upvotes: 0

Views: 78

Answers (1)

ptb
ptb

Reputation: 2148

Your problem combines mapping and membership testing. Both of these functionalities are available in common lisp:

(mapcar (lambda (list) (member 'p list))
         '((c) (a c) () () (p b) (c c a) (a)))

;; (NIL NIL NIL NIL (P B) NIL NIL)

More documentation on mapping can be found in the hyperspec

We could also use iteration:

(loop for item in '((c) (a c) () () (p b) (c c a) (a))
          collect (member 'p item))
;; (NIL NIL NIL NIL (P B) NIL NIL)

Upvotes: 1

Related Questions