On Thu, Aug 19, 2010 at 7:56 PM, Glen Rubin <rubing...@gmail.com> wrote:
>
> I want to multiply a list of n items by h lists of n items, so that
> for example if i have list 'a' and 'b'
>
> (def a (list 1 2 3))
> (def b (list '(4 5 6) '(7 8 9)))
>
> when multiplied I will get:
>
> ((4 10 18) (7 16 27))
>

Others have already given this solution, but I'd like to generalize
it. Tomorrow you might need to add those two lists in that way, or do
some other similar thing:

(defn mapmap [f a b]
   (map #(map f a %) b))

(def m* (partial mapmap *))
(def m+ (partial mapmap +))
(def m- (partial mapmap -))
(def mdiv (partial mapmap /))

user> (m+ '(1 2 3) '((4 5 6) (7 8 9)))
((5 7 9) (8 10 12))
user> (m- '(1 2 3) '((4 5 6) (7 8 9)))
((-3 -3 -3) (-6 -6 -6))
user> (m* '(1 2 3) '((4 5 6) (7 8 9)))
((4 10 18) (7 16 27))
user> (mdiv '(1 2 3) '((4 5 6) (7 8 9)))
((1/4 2/5 1/2) (1/7 1/4 1/3))

The key to this is that clojure allows us to pass around functions, so
called higher order functions, and allows us to very easily generalize
operations.

-- 
http://www.apgwoz.com

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