Clojure: map card

I would like to use the map function on the map. But I canโ€™t make it work.

Toy example:

(map map [+ - *] [1 2 3] [4 5 6] [7 8 9])

I expect a result like (12 15 18), but all I get is a mistake.

Thank.

+4
source share
3 answers

If you want to match each operator separately in lists, use

((fn [ops & args] (map #(apply map %1 args) ops)) [+ - *] [1 2 3] [4 5 6] [7 8 9])

or if you want to change the order of the arguments

(map #(map %1 [1 2 3] [4 5 6] [7 8 9]) [+ - *])

Both give a result ((12 15 18) (-10 -11 -12) (28 80 162))

+4
source

As an alternative to existing answers, you can replace the external one mapwith a list comprehension that is more readable than the nested mapIMHO:

user=> (defn fun [ops & args]
  #_=>     (for [op ops]
  #_=>         (apply map op args)))
#'user/fun

user=> (fun [+ - *] [1 2 3] [4 5 6] [7 8 9])
((12 15 18) (-10 -11 -12) (28 80 162))
+5
source

juxt:

(apply map list (map (juxt + - *) [1 2 3] [4 5 6] [7 8 9]))

: ((12 15 18) (-10 -11 -12) (28 80 162))

+4

All Articles