Page 1 of 1

filter nil?

Posted: Wed Mar 30, 2005 10:57 pm
by Sammo
(filter if '(nil one nil two nil three)) --> (one two three)
(filter and '(nil one nil two nil three)) --> (one two three)
(filter or '(nil one nil two nil three)) --> (one two three)

Must be a better (that is, reads better) way to strip nils from a list, but I can't think of it now.

And, BTW, (filter not '(nil one nil two nil three)) --> (nil nil nil)

Thanks,
-- Sam

Posted: Thu Mar 31, 2005 1:05 am
by Lutz
Actually I find your methods pretty neat! But I agree on the readability issue. I guess we need a 'true?' predicate (which would be: not nil) ?

(filter true? '(nil one nil two nil three)) --> (one two three)

Lutz

Posted: Thu Mar 31, 2005 7:23 am
by newdep
Hello Sammo,

Have you thought abaout ? ->

> (difference '(nil no nil false nil no nil not nil etc ) '(nil) )
(no false not etc)


Aaaa oke... yes .. I understand your problem now.. I had that also using 'filter and 'map.. because these two can work strongly together but you need a third handle to streer it ;-)

Norman.

Posted: Thu Mar 31, 2005 2:21 pm
by Sammo
My previous attempt is weak because if, and, & or equate nil and ().

> ;a list to play with
> (set 'a '(one nil two nil three nil nil ()))

> ;returns true when 'a' is non-nil
> (define (true? a) (!= a nil))

> ;true? is more accurate than if / and / or
> (filter true? a)
(one two three ())
> (filter if a)
(one two three)
> (filter and a)
(one two three)
> (filter or a)
(one two three)

> ;returns true only when 'a' is nil
> (define (nil? a) (= a nil))

> ;nil? is more accurate than not
> (filter nil? a)
(nil nil nil nil)
> (filter not a)
(nil nil nil nil ())

> ;of course, both can be written anonymously
> (filter (fn (a) (!= a nil)) a)
(one two three)
> (filter (fn (a) (= a nil)) a)
(nil nil nil nil)

As Norman pointed out, difference operates on sets and will, therefore, eliminate duplicates — a good thing when working with sets; not so good when working with lists.

Since true? and nil? are so easy to write and may be deployed anonymously with little loss of readability, I don't see a strong reason to add them the newLisp's repertoire.