简体   繁体   English

在Clojure中建立匿名功能的地图

[英]Constructing a map on anonymous function in Clojure

I am just learning the language and I've got a simple question. 我只是在学习语言,并且有一个简单的问题。 Why does this work (constructs {:key "value"} ): 为什么这样做(构造{:key "value"} ):

(#(assoc {} :key %) "value")

But this doesn't: 但这不是:

(#({: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: 在Python上,后一种语法完全有效:

> (lambda v: {'key': v})('value')
{'key': 'value'}

edit: thanks for great answers, it is apparent I need to stop thinking # as equivalent to lambda in Python. 编辑:感谢出色的答案,很明显,我需要停止思考#等同于Python中的lambda

#(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. 读者将#(f %)扩展为(fn [%] (f %) 。同样, #({:key %})扩展为(fn [%] ({:key %}) 。等效的python其中一个是lambda v: {'key': v}() ,它与Clojure版本具有完全相同的问题。

What you are looking for is something equivalent to (fn [v] {:key v}) . 您正在寻找的东西等同于(fn [v] {:key v}) If you really want to use #(...) notation, you could use #(do {:key %}) . 如果您真的想使用#(...)表示法,则可以使用#(do {:key %})

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. 我认为更难理解(例如该证据的示例),并且仅比等效的fn格式紧凑得多。 Then there's also the limitation that #(...) forms can not be nested. 然后还有一个限制,即不能嵌套#(...)形式。

That is the limitation of #() reader. 那是#()阅读器的局限性。 fn will work fine. fn会正常工作。

user=> ((fn [x] {:key x}) "value")
{:key "value"}

Please take a look at the document Anonymous function literal (#()) 请看一下文档匿名函数文字(#())

{:key %} is a PersistentArrayMap. {:key %}是一个PersistentArrayMap。 You have it in the "verb position" in your function call. 您可以将其放在函数调用的“动词位置”中。 You need a Clojure method of some type in there to avoid that error, as you can see in your first (working) example. 如您在第一个(有效的)示例中所看到的,您需要在那里使用某种Clojure方法来避免该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM