函数调用 ->线程宏 [英] Function call in -> threading macro

查看:24
本文介绍了函数调用 ->线程宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里需要括号来调用匿名函数

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)

推荐答案

documentation 声明第一个参数之后的表单如果不是列表,将被包装到列表中已经.所以问题是为什么这不适用于 #()(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屋!

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