简体   繁体   中英

Removing NIL's from a list LISP

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)

Common Lisp,而不是remove - 如果你可以使用remove:

(remove nil '(nil 1 nil 2 nil 3 nil 4))

在常见的lisp和其他方言中:

(remove-if #'null '(NIL 1 NIL 2 NIL 3 NIL 4))

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)

(remove-if-not #'identity list)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM