Just tossing up some non-juxt alternatives for comparison's sake, so we
can see where it is an improvement.

Sean Devlin <francoisdev...@gmail.com> writes:

> Notice that juxt creates a closure.  The most straightforward case is
> to *predictably* access multiple values from a map.
>
> user=>(def test-map {:a "1" :b "2" :c "3" :d "4"})
>
> user=>((juxt :a :c) test-map)
> ("1" "3")

(map test-map [:a :c])

> However, as one works with maps more and more, situations arise where
> it is desired to perform many operations on a map at once.  For
> example
>
> ;assume parse-int turns a string to an int appropriately
> user=>((juxt :a (comp parse-int :c)) test-map)
> ("1" 3)

[(:a test-map) (parse-int (:c test-map))]

> Since juxt returns a closure, it is very useful in any place one would
> use a map operation as well.  For example, this can make turning a
> list of maps into a list of lists very easy. Also, this made it very
> easy to determine if a sub-selection of a hash-map is equal to another
> hash- map
>
> user=>(def test-juxt (juxt :a :c))
> user=>(= (test-juxt {:a 1 :b 2 :c 3}) (test-juxt {:a 1 :b 34 :c 3}))
> true

(let [ks [:a :b]]
  (= (map {:a 1 :b  2 :c 3} ks)
     (map {:a 1 :b 34 :c 3} ks)))

> One thing that is very interesting is that this function allows one to
> simulate the behavior of let in a point-free style.
>
> ;This is deliberate overkill for a small example
> ;Generate a list of squares
> ;Notice that the juxt fn uses the range twice
> user=>((partial map (juxt identity #(* % %))) (range 1 6))
> ((1 1) (2 4) (3 9) (4 16) (5 25))

(for [i (range 1 6)] [i (* i i)])

> ;Assume our sales data is a list of maps, in the sales-coll variable
> ;returns a map with two element vectors as keys, a list of maps as the
> vals.
> user=>(group-by (juxt :sold-by :category) sales-coll)
> <Lots-Of-Data>

(group-by #(fmap % [:sold-by :category]) sales-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