函数调用 - >线程宏 [英] Function call in -> threading macro
问题描述
我们需要在这里使用括号来调用匿名函数。
We need parentheses here to make a call of anonymous function
user=> (-> [1 2 3 4] (conj 5) (#(map inc %)))
(2 3 4 5 6)
为什么不需要 map +
和 fmap +
在这些示例中?
Why there is no need for parentheses around map+
and fmap+
in these examples?
user=> (def map+ #(map inc %))
#'user/map+
user=> (-> [1 2 3 4] (conj 5) map+)
(2 3 4 5 6)
user=> (defn fmap+ [xs] (map inc xs))
#'user/fmap+
(-> [1 2 3 4] (conj 5) fmap+)
(2 3 4 5 6)
推荐答案
文档用于 - >
和 - >>
宏指出,如果第一个参数之外的表单不是列表,则将它们包装到列表中。所以问题是为什么这不适用于#()
和(fn ..)
形式?原因是这两种表单在宏展开时都以列表形式出现。
The documentation for the ->
and ->>
macros state that the forms after the first parameter are wrapped into lists if they are not lists already. So the question is why does this not work for #()
and (fn ..)
forms? The reason is that both forms are in list form at the time the macro expands.
例如
(-> 3 (fn [x] (println x)))
在扩展时获取(fn [x] ...)
形式,所以宏认为伟大,它是一个列表,我只是插入3在(fn ..)
列表的第二个位置。调用宏展开,这是我们得到的:
gets the (fn [x] ...)
form at expansion time, so the macro thinks "great, it's a list, I'll just insert the 3 in the second position of the (fn ..)
list." Invoking macroexpansion, this is what we get:
(fn 3 [x] (println x))
这当然不起作用。类似的#()
:
which of course doesn't work. Similarly for #()
:
(-> 3 #(println %))
已扩展为
(fn* 3 [p1__6274#] (println p1__6274#))
这就是为什么我们需要额外的括号。
That's why we need the extra parens.
这篇关于函数调用 - >线程宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!