filter out null values

2,498 views
Skip to first unread message

Razvan Rotaru

unread,
Feb 2, 2012, 1:53:10 PM2/2/12
to Clojure
Hi,

What's the clojure way to filter out null values from a sequence?

I have following code:

(filter identity (map myfun myseq))

Is there a better/faster way?

Thanks,
Razvan

Phil Hagelberg

unread,
Feb 2, 2012, 1:59:23 PM2/2/12
to clo...@googlegroups.com
Razvan Rotaru <razvan...@gmail.com> writes:

> (filter identity (map myfun myseq))
>
> Is there a better/faster way?

Not yet, but there's an open ticket for that:

http://dev.clojure.org/jira/browse/CLJ-450

-Phil

Jonas

unread,
Feb 2, 2012, 2:04:18 PM2/2/12
to clo...@googlegroups.com
Note that `(filter identity ,,,)` will also remove `false` values:

    => (filter identity [1 2 nil 3 false 4])
    (1 2 3 4)

You could use `remove` instead

    => (remove nil? [1 2 nil 3 false 4])
    (1 2 3 false 4)

Hope that helps!

Jonas

Mark Engelberg

unread,
Feb 2, 2012, 2:46:07 PM2/2/12
to clo...@googlegroups.com
(keep my-fun my-seq) does exactly what you want, I believe.

David Powell

unread,
Feb 2, 2012, 4:00:54 PM2/2/12
to clo...@googlegroups.com
Hmm, the original suggestion for single-arity filter might pre-date the introduction of remove?

(remove nil? xs)

seems more self-explanatory than:

(filter xs)

-- 
Dave

Reply all
Reply to author
Forward
0 new messages