Removing NIL's from a list LISP

大兔子大兔子 提交于 2019-12-05 09:13:47

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

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

In common lisp and perhaps other dialects:

(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)

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!