filter nil?

Started by Sammo, March 30, 2005, 02:57:55 PM

Previous topic - Next topic

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

#1
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

#2
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

#3
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.