什么时候应该使用Clojure的箭头宏? [英] When should I use the clojure arrow macro?
问题描述
在试图保持与实用的风格,我有困难的时候认识我应该更喜欢:
In trying to stay with the functional style, I am having difficulty understanding when I should prefer:
(-> [1 2 3] reverse last)
在:
(last (reverse [1 2 3]))
当我在项目中遇到两种样式时,我发现它中断了我的流程,因为我不得不在思考函数组成和思考中间值状态之间进行切换.
When I come across both styles in a project, I find that it breaks my flow since I have to switch between thinking about function compositions and thinking about intermediate value states.
我应该在什么时间使用?
Which should I use at what times?
推荐答案
我主要是避免使用
I mostly avoid using ->
for one-argument functions; it's a lot more useful when you have multiple-argument functions, because it lets you keep each function next to its "extra args", without the focus object obscuring it.
但同时,你不必选择一个或另一个极端:一个是我约喜欢的东西
But also, you don't have to choose one or the other extreme: one of my favorite things about ->
is that it allows you to write the functions in any order at all, and you can use this freedom to write the code in whatever way you think is most readable. For example, perhaps you want to emphasize that you're taking the last of a collection, and in context the fact that it's reversed first is uninteresting:
(last (-> [1 2 3] (reverse)))
也许反转很重要,最后却很无聊:
Or maybe reversing is important, and last is boring:
(-> (reverse [1 2 3]) (last))
顺便说一句,请注意,我写了->
的形式使用括号是个好主意.造成这种情况的原因有很多:
As an aside, note that I wrote (last)
and (reverse)
here rather than just last
and reverse
even though the ->
macro implicitly inserts parentheses for you if you leave them out. This was on purpose: although it's not a terribly popular style, I think it's a good idea to always use parentheses in the forms given to ->
. There are several reasons for this:
- 这意味着当
(-> (blah) (fn [x] (+ 1 (* x 5))))
怪异地扩展时,您不会感到惊讶,因为您习惯于认为->
采用形式而不是函数. - 它保持之间在这里是一个开括号"和函数被称为"链接.能够grep调用特定函数是一件很不错的事情,同时它也是很好的视觉提示.如果省略括号,则会在没有视觉信号的情况下调用函数.
-
它看起来在多线
一些一元函数和其他多参数的函数更经常.例如:
- It means you aren't surprised when
(-> (blah) (fn [x] (+ 1 (* x 5))))
expands weirdly, because you are used to thinking that->
takes a form rather than a function. - It keeps the link between "here is an open parenthesis" and "a function is being called". It's nice to be able to grep for calls to a particular function, and it's also a nice visual hint. If you omit the parentheses, functions are called without being visually signaled.
It looks more regular in a multi-line
->
with some unary functions and other multi-argument functions. For example:
(-> attrs
(update :sessions inc)
frobnicate
save-to-disk
(get :uuid))
是不是总有中间这两件事情偏移,目光从一切有什么不同?
Isn't it gross to have those two things in the middle offset, looking different from everything else?
我见过省去的唯一参数的
The only argument I have ever seen for omitting the ()
s is that it saves two characters of typing, which is not an argument at all.
这篇关于什么时候应该使用Clojure的箭头宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!