Removing NIL's from a list LISP
Asked Answered
B

5

8

Simple question.

Say I have a bunch of NIL's in my list q . Is there a simple way to remove the NILs and just keep the numbers?. eval doesn't seem to work here.

(NIL 1 NIL 2 NIL 3 NIL 4)

I need (1 2 3 4)

Badman answered 20/2, 2012 at 3:41 Comment(4)
Sounds like you're looking for a filter function. Which Lisp dialect (Scheme, Common Lisp, etc.) are you using?Elli
Common Lisp. It makes sense for there to be a built in function that ignores NILs..Badman
@JohnPick nailed it, check out his answer!Bresnahan
if this is homework, tag it as suchLaurentium
T
25

Common Lisp, instead of remove-if you can use remove:

(remove nil '(nil 1 nil 2 nil 3 nil 4))
Tacnaarica answered 20/2, 2012 at 18:18 Comment(0)
C
11

In common lisp and perhaps other dialects:

(remove-if #'null '(NIL 1 NIL 2 NIL 3 NIL 4))
Coarse answered 20/2, 2012 at 3:48 Comment(1)
User "Spec" has a more straightforward answer.Coarse
P
1

If you're using Scheme, this will work nicely:

(define lst '(NIL 1 NIL 2 NIL 3 NIL 4))

(filter (lambda (x) (not (equal? x 'NIL)))
        lst)
Parterre answered 20/2, 2012 at 3:48 Comment(0)
E
1

As I noted in my comment above, I'm not sure which Lisp dialect you are using, but your problem fits exactly into the mold of a filter function (Python has good documentation for its filter here). A Scheme implementation taken from SICP is

(define (filter predicate sequence)
  (cond ((null? sequence) nil)
        ((predicate (car sequence))
         (cons (car sequence)
               (filter predicate (cdr sequence))))
        (else (filter predicate (cdr sequence)))))

assuming of course that your Lisp interpreter doesn't have a built-in filter function, as I suspect it does. You can then keep only the numbers from your list l by calling

(filter number? l)
Elli answered 20/2, 2012 at 3:50 Comment(0)
E
0

(remove-if-not #'identity list)

Electroplate answered 15/9, 2022 at 2:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.