AndroidDev
AndroidDev

Reputation: 21237

How to map a function that adds 5 to its argument?

Please help me get off the ground with Clojure. I've searched and read, but all I see is how to add the number 1 using the function inc.

I'm trying to understand the very basics of map. All I want to do is to add the value 5 to each element in a collection. I've tried a number of different approaches, but nothing comes close. Here is one pathetic incomplete attempt:

(map (+ 5 ???) [0 1 2])

This must be childishly simple, but not for a non-functional programmer like me.

Thanks.

Upvotes: 2

Views: 101

Answers (3)

Mark Karpov
Mark Karpov

Reputation: 7599

Use partial application (see partial) to create a function that adds 5 to its argument:

(partial + 5)

You can try it yourself:

user> ((partial + 5) 10)
;; => 15

Now map it over your list:

user> (map (partial + 5) [0 1 2])
;; => [5 6 7]

Upvotes: 1

galdre
galdre

Reputation: 2339

(+ 5 ???) is an expression, not a function.

(defn foo [x] (+ 5 x)) is a named function.

(fn [x] (+ 5 x)) is an anonymous function.

#(+ 5 %) is a faster way of writing an anonymous function.

These lines do what you want:

(map foo [0 1 2])
(map (fn [x] (+ 5 x)) [0 1 2])
(map #(+ 5 %) [0 1 2])

I find this site helpful sometimes, when looking at a language I've never seen before. If you search for "function," you'll find a whole section on how to define them. There are also six examples in the official Clojure docs for map. This is for Scala, but here's another answer on SO that explains map and reduce (left fold) pretty well.

Upvotes: 2

Lee
Lee

Reputation: 144136

The first argument to map is the function you want to apply to each element in the input sequence. You could create a function and supply it:

(defn plus5 [x] (+ 5 x))
(map plus5 [0 1 2])

if you don't want to declare a named function you could create an anonymous one inline e.g.

(map (fn [x] (+ 5 x)) [0 1 2])

and you can shorten the function definition to:

(map #(+ 5 %) [0 1 2])

Upvotes: 3

Related Questions