Clojure的功能#(:jerry @%)意味着什么

时间:2017-05-18 15:41:45

标签: clojure

我在Clojure中很新。我在Clojure Koans的帮助下学习。我找到了以下代码的答案:

(= ["Real Jerry" "Bizarro Jerry"]
       (do
         (dosync
          (ref-set the-world {})
          (alter the-world assoc :jerry "Real Jerry")
          (alter bizarro-world assoc :jerry "Bizarro Jerry")
          (vec (map #(:jerry @%) [the-world bizarro-world]))))))

来自:https://github.com/viebel/clojure-koans/blob/master/src/koans/16_refs.clj#L42

谷歌搜索像#Clojure @%"这是非常不友好的。所以我从互联网上得不到任何东西。

该功能如何运作"#(:jerry @%)"?

以下代码是我的答案,但它不起作用。

(= ["Real Jerry" "Bizarro Jerry"]
       (do
         (dosync
          (ref-set the-world {})
          (alter the-world assoc :jerry "Real Jerry")
          (alter bizarro-world assoc :jerry "Bizarro Jerry")
          (vec (map (fn [x] (:jerry x)) [the-world bizarro-world]))
         )))

3 个答案:

答案 0 :(得分:9)

#( ...)reader macro for anonymous function,其中%表示传递给函数的第一个参数。例如:

#(println %)

相当于:

(fn [x] (println x))

@再次为reader macro for deref

@some-variable

与:

相同

(deref some-variable)

用于取消引用ref types之一的当前值。

因此#(:jerry @%)是一个匿名函数,当应用于ref(例如一个原子)时,它将deref其当前值并将其用作调用:jerry {{3}的参数带有价值。

答案 1 :(得分:1)

the-worldbizarro-world是“可反驳的”,这意味着您可以在前面使用@来获取其价值。

您使用的是匿名函数,由#( )表示。在匿名函数中,百分号%表示函数的参数。

所以@%表示“取消引用此函数的参数。”

:jerry是一个用作函数的关键字,它获取与地图中的键:jerry相关联的值。

例如:

(def coll [(ref {:jerry 21})
           (ref {:jerry 42})])
=> #'user/coll

(map #(:jerry @%) coll)
=> (21 42)

答案 2 :(得分:1)

此外,你可以找到其他的"奇怪的"这里的符号在clojure中。 https://yobriefca.se/blog/2014/05/19/the-weird-and-wonderful-characters-of-clojure/