On Aug 18, 12:57 am, Parth Malwankar <[EMAIL PROTECTED]>
wrote:
> On Aug 18, 1:57 am, Randall R Schulz <[EMAIL PROTECTED]> wrote:
>
> > On Sunday 17 August 2008 07:08, Parth Malwankar wrote:
>
> > > I am trying to create a "in" macro.
> > > (in 'a 'b 'a 'c) => true.
>
> > > ...
>
> > Apart from the pedantic value in making it work, why would one want this
> > functionality in a macro rather than a plain old function?
>
> I can't think of a good way to do this with a function.
> If we do:
>
> (defn in2 [obj & choices]
>   (let [o obj]
>     (map (fn [x] (= o x)) choices)))
>
> We get:
>
> user=> (in2 'a 'a 'b 'c)
> (true false false)
>
> Which is somewhat correct but the problem is its not a
> short circuited evaluation like 'or', so the second
> and third tests are also done.
>
> Also, we now are left with the problem of finding
> if true is present in the result of in2.
> 'apply'ing 'or' to the result doesn't work because
> 'or' is a macro and we can't apply macros.
>
> Another nice way to achieve this is:
> user=> (contains? (set ['a 'b 'c]) 'a)
> true
>
> I didn't know about 'contains?' ... if I know about this
> I wouldn't have bothered with in, but 'in' was a good
> exercise.

These are all fine:

(some #(= % obj) items)
(some #{obj} items)
(#{'a 'b 'c} obj) ;for non-nil/false
((set items) obj) ;ditto
(contains? #{'a 'b 'c} obj) ;works for nils/false too

Note in particular the 'set trick' works for sets with more than one
element, and most directly represents what you mean by 'in' - is this
value in this set?

Rich
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to