Laurent, I think this is a close variant of the early exiting reduce
function you proposed:
(defn reduce-bail [f pred? val col]
(let [s (seq col)]
(if s
(if (pred? val)
(recur f pred? (f val (first s)) (next s))
val)
val)))
;Then we can write:
(defn interesting? [pixels in-range? count]
(let [p-count (reduce-bail (fn [c p] (if (in-range? p) (inc c) c))
(partial > count) 0 pixels)]
[( = count yummy-pix-count) p-count]))
; This returns a vec showing how close to the interesting count the
pixels came in addition to showing whether the sequence was
interesting, so that we see that it works.
; Now, in completely terrible form precipitated by the fact that it's
4:20 in the morning we try:
(interesting? (let [r (take 1000 (repeatedly #(rand-int 10)))]
(println (count (filter #(= % 5) r ))) r) #(= % 5) 93)
; This bails according to the number of 5s counted, but also side
effects the printing of a complete count to show that it works.
(interesting? (repeatedly rand) #(> % 0.99) 1000)
; Here, we see that our cautious reduce does not choke on infinite
sequences if it can escape. It will not halt for uninteresting
sequences however, so this isn't useful here.
Way too tired right now to think about whether this is useful in
general (Maybe in cases where you're looking to bail at some value
more complicated than a count), but the code runs pretty neat, and I
agree with Laurent that we should explore this abstraction. Dunno if
there are hidden bugs in my code tho. Anyways.
Sleepytime
- max
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
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
-~----------~----~----~----~------~----~------~--~---