在Clojure中,我如何将所有内容映射到一个恒定值?

del*_*ber 8 clojure

例如

(map #(+ 10 %1) [ 1 3 5 7 ])
Run Code Online (Sandbox Code Playgroud)

将为所有内容添加10

假设我想将所有内容映射到常量1.我试过了

(map #(1) [ 1 3 5 7 ])
Run Code Online (Sandbox Code Playgroud)

但我不明白编译错误.

mik*_*era 14

(map #(1) [ 1 3 5 7 ])
Run Code Online (Sandbox Code Playgroud)

不会有两个原因:

  • #(1) 是一个零参数的匿名函数,因此它不适用于map(当与一个输入序列一起使用时需要一个参数函数).
  • 即使它有正确的arity,它也行不通,因为它试图将常量1称为函数(1)- (#(1))例如,如果你想看到这个错误.

以下是一些可行的替代方案:

; 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])
Run Code Online (Sandbox Code Playgroud)

上述情况,我想使用的版本不断应首选-这是更清晰,更地道.


Ale*_*art 11

匿名函数#(+ 10 %1)相当于:

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

#(1)相当于:

(fn []
  (1))

尝试1作为一个没有args的函数调用是行不通的.


eps*_*lbe 10

我在clojure.org上 通过谷歌搜索"clojure constant function"来得到这个,因为我刚开始看clojure

(map (constantly 9) [1 2 3])
Run Code Online (Sandbox Code Playgroud)

干杯