Sean Corfield <seancorfi...@gmail.com> writes:

> On Wed, Aug 18, 2010 at 10:28 AM, Shantanu Kumar
> <kumar.shant...@gmail.com> wrote:
>> Would suggest to consider this:
>>
>> (let [ x (true? (new java.lang.Boolean false)) ] (if x "trouble"
>> "ok"))
>
> Ah, but that wouldn't work for a new Boolean set to true:
>
> (let [ x (true? (new java.lang.Boolean true)) ] (if x "ok" "trouble"))
>
> Expect "ok"? Nope, you'll get "trouble".

How about something along these lines?

    (defmacro careful-if [test then else]
      `(let [result# ~test]
         (cond (nil? result#) ~else
               (identical? Boolean/FALSE result#) ~else
               (identical? Boolean/TRUE result#) ~then
               (instance? Boolean result#) (if (Boolean/valueOf result#)
                                             ~then
                                             ~else)
               :else ~then)))

In the case of a "proper" boolean value I think you just get one more
reference check than with normal "if"; you only hit reflection if both
those reference checks fail.  It satisfies the original author's
challenge, anyway:

    (map #(careful-if %1 :truthy :falsey)
         [true false (new Boolean true) (new Boolean false)])

    ;;; => (:truthy :falsey :truthy :falsey)

I'll leave it to someone more skilled in Clojure than me to tell us what
would be the impact of either using this as a replacement "if" or
somehow embedding similar logic into the Java interop functions...

-- 
Mark Shroyer
http://markshroyer.com/contact/

-- 
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
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to