0

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)
)
2
  • your question is unclear to me, but you might want to look into min-key though Commented Oct 19, 2014 at 23:41
  • How do you get [[1 -1] [2 -2] [3 -3]] ? Commented Oct 20, 2014 at 1:40

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

i must have another error when using the (map vector alist results) on a lazy-seq. It just said something error lazy-seq so I assumed it was cause of this line (when I added it in, the program broke). thanks though! hoping from python to clojure is ew.
Another small trick that I noticed, probably not big enough for editing this answer, but #(* % -1) is equivalent to - when called on one arg (- 4) => -4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.