Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Clojure, how would I map everything to a constant value?

Tags:

clojure

For example

(map #(+ 10 %1) [ 1 3 5 7 ])

Will add 10 to everything

Suppose I want to map everything to the constant 1. I have tried

(map #(1) [ 1 3 5 7 ])

But I don't understand the compiler error.

like image 639
deltanovember Avatar asked Feb 05 '12 23:02

deltanovember


2 Answers

(map #(1) [ 1 3 5 7 ])

Won't work for two reasons:

  • #(1) is a zero-argument anonymous function, so it won't work with map (which requires a one-argument function when used with one input sequence).
  • Even if it had the right arity, it wouldn't work because it is trying to call the constant 1 as a function like (1) - try (#(1)) for example if you want to see this error.

Here are some alternatives that will work:

; use an anonymous function with one (ignored) argument
(map (fn [_] 1) [1 3 5 7])

; a hack with do that ignores the % argument 
(map #(do % 1) [1 3 5 7])

; use a for list comprehension instead
(for [x [1 3 5 7]] 1)

; use constantly from clojure.core
(map (constantly 1) [1 3 5 7])

Of the above, I think the versions using constantly or for should be preferred - these are clearer and more idiomatic.

like image 74
mikera Avatar answered Feb 15 '23 17:02

mikera


The anonymous function #(+ 10 %1) is equivalent to:

(fn [%1]
  (+ 10 %1))

Whereas #(1) is equivalent to:

(fn []
  (1))

And trying to call 1 as a function with no args just won't work.

like image 27
Alex Taggart Avatar answered Feb 15 '23 17:02

Alex Taggart