Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing NIL's from a list LISP

Tags:

list

null

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)

like image 742
CyberShot Avatar asked Feb 20 '12 03:02

CyberShot


4 Answers

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

(remove nil '(nil 1 nil 2 nil 3 nil 4))
like image 119
Spec Avatar answered Oct 20 '22 00:10

Spec


In common lisp and perhaps other dialects:

(remove-if #'null '(NIL 1 NIL 2 NIL 3 NIL 4))
like image 25
John Pick Avatar answered Oct 20 '22 00:10

John Pick


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)
like image 1
Óscar López Avatar answered Oct 19 '22 23:10

Óscar López


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)
like image 1
Adam Mihalcin Avatar answered Oct 20 '22 01:10

Adam Mihalcin