Constructing a map on anonymous function in Clojure

后端 未结 3 1010
既然无缘
既然无缘 2020-12-01 21:47

I am just learning the language and I\'ve got a simple question. Why does this work (constructs {:key \"value\"}):

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


        
相关标签:
3条回答
  • 2020-12-01 22:20

    {:key %} is a 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.

    0 讨论(0)
  • 2020-12-01 22:36

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

    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 %}).

    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.

    0 讨论(0)
  • That is the limitation of #() reader. fn will work fine.

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

    Please take a look at the document Anonymous function literal (#())

    0 讨论(0)
提交回复
热议问题