在 Clojure 中构建匿名函数映射 [英] Constructing a map on anonymous function in Clojure
问题描述
我只是在学习语言,我有一个简单的问题.为什么这样做(构造 {:key "value"}
):
I am just learning the language and I've got a simple question. Why does this work (constructs {:key "value"}
):
(#(assoc {} :key %) "value")
但这不会:
(#({:key %}) "value")
ArityException Wrong number of args (0) passed to: PersistentArrayMap clojure.lang.AFn.throwArity (AFn.java:429)
在 Python 上,后一种语法是完全有效的:
On Python the latter syntax is perfectly valid:
> (lambda v: {'key': v})('value')
{'key': 'value'}
感谢您提供出色的答案,很明显我需要停止将 #
视为 Python 中的 lambda
等价物.
edit: thanks for great answers, it is apparent I need to stop thinking #
as equivalent to lambda
in Python.
推荐答案
#(f %)
被读者展开为 (fn [%] (f %)
>. 同样地,#({:key %})
被扩展为 (fn [%] ({:key %})
.python 等效的将是 lambda v: {'key': v}()
,与Clojure版本有完全相同的问题.
#(f %)
is expanded by the reader into (fn [%] (f %)
. Likewise, #({:key %})
is expanded into (fn [%] ({:key %})
. The python equivalent of this would be lambda v: {'key': v}()
, which has the exact same problem as the Clojure version.
您要查找的内容与 (fn [v] {:key v})
等价.如果你真的想使用 #(...)
表示法,你可以使用 #(do {:key %})
.
What you are looking for is something equivalent to (fn [v] {:key v})
. If you really want to use #(...)
notation, you could use #(do {:key %})
.
顺便说一句,我个人从不使用 #(...)
.我认为它更难理解(例如这个证据),并且只比等效的 fn
形式稍微紧凑一些.然后还有 #(...)
表单不能嵌套的限制.
Incidentally, I personally never use #(...)
. I think it's more difficult to grok (as examples such as this evidence), and is only very slightly more compact than an equivalent fn
form. Then there's also the limitation that #(...)
forms can not be nested.
这篇关于在 Clojure 中构建匿名函数映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!