user1639926
user1639926

Reputation: 862

Clojure using map to store results and parameters

I'm trying to take some inputs, run a calculation on it, and then find the min, and get the parameters that created that min.

alist = [1 2 3 4 5 -4]

; I want [[1 -1] [2 -2] [3 -3]]
; the following doesn't work.  how can i make it work?
(map #( [% (* -1 %)])  [ 1  2 3])

It can be a hashmap too, to store the results.
This should be absurdly trivial but I can't get it to work. Also my list is a lazy-seq so I couldn't just zip the results with the original list.

; this doesn't work cause alist is a lazy-seq in my program
(let [results (map #(* -1 %) alist)]
    (map vector alist results)
)

Upvotes: 0

Views: 115

Answers (1)

noisesmith
noisesmith

Reputation: 20194

There are a number of ways to do this:

(map (juxt identity #(* -1 %)) [1 2 3])

(for [i [1 2 3]] [i (* i -1)])

(let [s [1 2 3] result (map #(* -1 %) s)] (map vector s result))

(map (fn [i] [i (* i -1)]) [1 2 3])

Despite your claim to the contrary, the version using a let binding and two calls to map works just fine on a lazy-seq. It's the least clear way to do it out of these examples though.

To show why your anonymous function is erroneous:

user> '#( [% (* -1 %)])
(fn* [p1__17065#] ([p1__17065# (* -1 p1__17065#)]))

the reader expands #([% (* -1 %)]) to a function call on a two element vector, with no arguments provided to that function call. This is of course an error (a vector when used as a function should take 1 or 2 arguments, and this is not what you want to do with your vector anyway).

Upvotes: 2

Related Questions