在 Clojure 中,我如何将所有内容映射到常量值?

发布于 2025-01-03 07:27:01 字数 185 浏览 2 评论 0原文

例如

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

将向所有内容添加 10

假设我想将所有内容映射到常量 1。我已经尝试过

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

但我不明白编译器错误。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

为你鎻心 2025-01-10 07:27:01
(map #(1) [ 1 3 5 7 ])

不起作用有两个原因:

  • #(1) 是一个零参数匿名函数,因此它不能与 map 一起使用(与一个输入序列一起使用时需要一个单参数函数) 。
  • 即使它有正确的数量,它也不会工作,因为它试图将常量 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])

在上述版本中,我认为使用 constantlyfor 应该是首选 - 这些更清晰、更惯用。

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

东京女 2025-01-10 07:27:01

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

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

#(1) 相当于:

(fn []
  (1))

并尝试将 1 调用为没有参数的函数将无法工作。

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.

白昼 2025-01-10 07:27:01

我从 clojure.org 得到这个
通过谷歌搜索“clojure常量函数”这个词,因为我刚刚开始关注clojure

(map (constantly 9) [1 2 3])

欢呼

I got this from clojure.org
by googling the words "clojure constant function" as I am just beginning to look at clojure

(map (constantly 9) [1 2 3])

cheers

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文