Reputation: 413
I am trying to map a function that takes two arguments to a vector.
For example, given a vector [2, 3, 4]
, I'd like to add 2 to every digits by "+" function.
Here is what I tried :
(map (defn add2[i] (+ 2 i)) [2, 3, 4])
(map (+ 2) [2, 3, 4])
Upvotes: 0
Views: 756
Reputation: 183
(map (fn [i] (+ 2 i)) [1 2 3])
Or instead use the following anonymous function :#(+ 2 %)
You can also do:(partial + 2)
to define a partial function
Your second code example won't work because you need to tell clojure where to put the argument that map is applying the function to. The way to do this is to either define a function (as you've done in your first example) or to create an anonymous function as I've done above.
Upvotes: 0
Reputation: 530
You want to use the anonymous function fn
$ (map (fn [x] (+ 2 x)) [2 3 4])
=> [4 5 6]
#(do %1 %2)
is reader sugar for fn
$ (map #(+ %) [2 3 4]);the first argument can be either % or %1
=> [4 5 6]
or alternatively you can use partial to return a function that partially applies the function you give it to one of the arguments. You should prefer this one for partial application of constant values.
$ (map (partial + 2) [2 3 4]);the first argument can be either % or %1
=> [4 5 6]
Upvotes: 1
Reputation: 18005
Anonymous functions are declared with fn
or #()
:
(map (fn [i] (+ 2 i)) [2 3 4])
(map #(+ 2 %) [2 3 4])
You could also use partial
:
(map (partial + 2) [2 3 4])
Commas are optional and usually not used in source code.
Upvotes: 1