(top-posting corrected)

> On Sunday, March 25, 2012 5:49:27 PM UTC-5, Dustin Getz wrote:
>>
>> first a quesiton about idiomatic code:
>>
>> ;; provided by book Fogus & Houser, Joy of Clojure
>> (defn index [coll]
>>   (cond
>>     (map? coll) (seq coll)
>>     (set? coll) (map vector coll coll)
>>     :else (map vector (iterate inc 0) coll)))
>>
>> ;; book gives this as idiomatic code
>> (defn pos [needle coll]
>>   (for [[i val] (index coll)
>>         :when (= needle val)] i))
>>
>> ;; usage
>> (let [coll [:0 :1 :2 :3 :4 :5 :4]]
>>   (pos :4 coll)) ;-> (4 6)
>>
>> ;; how can i make this alternate version better, and why provide :when,
>> given filter?
>> ;; is it possible to get the destructuring elegance above without `for` ?
>> ;; is this sequencing property of for (operate on individual values that
>> will end up in a seq)
>> ;; the reason `for` exists? is not not possible to do have nice syntax
>> wtihout for (or seq-monad)?
>> (defn pos2 [needle coll]
>>   (let [pairs (filter (fn [[i val]] (= val needle))
>>                       (index coll))]
>>     (for [[i val] pairs] i))) ; can't destructure nicely without for, or
>> seq-monad, i think

If your inner operation (the part within the "for") is expensive, it's
nice to not be able to do it at all rather than calculate it uselessly
then throw it away using filter.

"(map expensive-fn (filter pred coll))" is pretty much equivalent to
"(for [item coll :when pred] expensive-fn)".


On Mon, Mar 26, 2012 at 11:30 PM, Caleb <caleb.phill...@gmail.com> wrote:
> In this case the for gives you the destructuring, plus the ability to do
> filtering (:when) and mapping (yeilding the value of i) in one expression.
>  So you have one destructured binding that you can use for both purposes.
>
> If you want to use filter, I think it is probably more idiomatic to follow
> it up with a map.
>
> (defn pos2 [needle coll]
>   (map first
>        (filter (fn [[_ val]] (= val needle))
>                (index coll))))
>
>

This yak can be shaved in many ways.

(defn pos3 [needle coll]
   (keep-indexed (fn [index val] (when (= val needle) index)) coll)

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