在Clojure中构造一个匿名函数的映射 [英] Constructing a map on anonymous function in Clojure
问题描述
我只是学习语言,我有一个简单的问题。为什么这样工作(构造 {:keyvalue}
):
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)
后面的语法是完全有效的:
On Python the latter syntax is perfectly valid:
> (lambda v: {'key': v})('value')
{'key': 'value'}
编辑:感谢伟大的答案,显然我需要停止思考#
等同于 lambda
在Python中。
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 %})
.
code>#(...)。我认为grok更困难(例如这个证据),并且只是比一个等效的 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屋!