filter nil?

Pondering the philosophy behind the language
Locked
Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

filter nil?

Post 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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

newdep
Posts: 2038
Joined: Mon Feb 23, 2004 7:40 pm
Location: Netherlands

Post 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.
-- (define? (Cornflakes))

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post 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.

Locked