Clojure 匿名函数

Clojure Anonymous Functions

我正在构建一个将字符串放入向量中的函数。

不过我想不通,为什么这样行得通:

(mapv (fn [i] [i]) '("hi" "there"))

但这不起作用:

(mapv #([%]) '("hi" "there"))

参见:https://clojuredocs.org/clojure.core/fn#example-560054c2e4b08e404b6c1c80

简而言之:#(f) == (fn [] (f)),因此#([1 2 3]) == (fn [] ([1 2 3]))

希望对您有所帮助。

#() 需要一个函数作为它的第一个参数。你可以做 #(vector %)

例如:

(map #(vector %) (range 5))
> ([0] [1] [2] [3] [4])

当然你也可以这样做:

(map vector (range 5))
> ([0] [1] [2] [3] [4])

, the anonymous function reader macro 将其主体包裹在一个列表中,如下所示:

(read-string "#([%])")
;=> (fn* [p1__20620#] ([p1__20620#]))

通常对于需要编写主体为向量的匿名函数的情况,我建议您只使用 fn 宏,就像您在问题中所做的那样:

(mapv (fn [i] [i]) '("hi" "there"))
;=> [["hi"] ["there"]]

不过,在这种情况下,您的 (fn [i] [i]) 相当于内置的 vector 函数,所以我建议您改用它:

(mapv vector '("hi" "there"))
;=> [["hi"] ["there"]]