> The technique, using throw an Exception when succeeded in searching, strikes
> me!

You can make it less ugly with a bit of library:

user> (deftype EarlyExit [result])
user.EarlyExit
user> (defn early-exit [x] (EarlyExit. x))
user> (defn reduce-with-early-exit [f acc coll]
            (if (instance? user.EarlyExit acc)  
                (. ^EarlyExit acc result)
                (if-let [hd (first coll)]
                        (recur f (f acc hd) (rest coll))
                        acc)))

Then you can write:

(defn has22 [coll] (= (reduce-with-early-exit #(and (= %2 2) (or (not
%1) (early-exit :found!))) false coll) :found!))

You can write early-exit and reduce-with-early-exit by using a Throwable.
Whichever is best depends on how often you exit early and how long is
your sequence.

-- 
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
  • [no subject] John Holland
    • Re: Mark Rathwell
      • Re: Moritz Ulrich
    • Re: Yoshinori Kohyama
      • Re: DeWitt Clinton
        • Re: nicolas.o...@gmail.com
          • Re: Yoshinori Kohyama
            • Re: nicolas.o...@gmail.com
              • Re: Yoshinori Kohyama
    • Re: Ben Smith-Mannschott

Reply via email to