是美元运算符($)被认为是坏形式吗?为什么? [英] Is dollar operator ($) considered bad form? Why?
问题描述
在Haskell中,我经常用$'来写表达式。我发现它很自然和可读,但我有时读它是不好的形式,不明白为什么它应该是。
以下都是良好的形式:
foo = bar。巴兹。 quux
foo x = bar。巴兹。 quux $ x
foo x =(bar。baz。quux)x
foo x = bar(baz(quux x))
我把它们按我的喜好粗略的顺序,虽然一如既往的味道不同,上下文可能需要不同的选择。我也偶尔看到
foo = bar
和
。 baz
。当每个bar
, code> bazquux
子表达式很长。以下是不好的形式:foo x = bar $ baz $ quux $ x
有两个原因,这不太可取。首先,在重构期间可以将较少的子表达式复制和粘贴到辅助定义中;与所有
($)
运算符,只有包含x
参数的子表达式是有效的重构,而(。)
和($)
运算符甚至子表达式baz
或baz。
第二个更喜欢
(。)的原因
是预期可能更改($)
的固定性;目前,($)
是infixr
,意味着它与右边相关联,如下:foo x = bar $(baz $(quux $ x))
但是,
($)
在更多的表达式中是有用的,如果infixl
;例如像foo h = f(gx)(hy)
foo h = f $ gx $ hy
foo h =(f $ gx)$ hy
...目前无法无括号表示。使用
infixl
应用程序解析时,坏形式示例为foo x =((bar $ baz)$ quux)$ x
不同。所以,通过避免这种形式,未来的代码。
In Haskell, I often write expressions with $'s. I find it quite natural and readable, but I sometimes read it is bad form and do not understand why it should be.
解决方案The following are all good form:
foo = bar . baz . quux foo x = bar . baz . quux $ x foo x = (bar . baz . quux) x foo x = bar (baz (quux x))
I've put them in rough order of my preference, though as always taste varies, and context may demand a different choice. I've also occasionally seen
foo = bar . baz . quux
when each of the
bar
,baz
, andquux
subexpressions are long. The following is bad form:foo x = bar $ baz $ quux $ x
There are two reasons this is less preferable. First, fewer subexpressions can be copied and pasted into an auxiliary definition during refactoring; with all
($)
operators, only subexpressions that include thex
argument are valid refactorings, whereas with(.)
and($)
operators even subexpressions likebar . baz
orbaz . quux
can be pulled out into a separate definition.The second reason to prefer
(.)
is in anticipation of a possible change to the fixity of($)
; currently,($)
isinfixr
, meaning it associates to the right, like so:foo x = bar $ (baz $ (quux $ x))
However,
($)
would be useful in more expressions if it wereinfixl
; for example, something likefoo h = f (g x) (h y) foo h = f $ g x $ h y foo h = (f $ g x) $ h y
...which currently cannot be expressed without parentheses. The "bad form" example, when parsed with an
infixl
application, would befoo x = ((bar $ baz) $ quux) $ x
which means something significantly different. So, future-proof your code by avoiding this form.
这篇关于是美元运算符($)被认为是坏形式吗?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!