在Clojure中构造一个匿名函数的映射 [英] Constructing a map on anonymous function in Clojure

查看:107
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆