是美元运算符($)被认为是坏形式吗?为什么? [英] Is dollar operator ($) considered bad form? Why?

查看:147
本文介绍了是美元运算符($)被认为是坏形式吗?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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> baz
quux 子表达式很长。以下是不好的形式:

  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, and quux 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 the x argument are valid refactorings, whereas with (.) and ($) operators even subexpressions like bar . baz or baz . 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, ($) is infixr, meaning it associates to the right, like so:

foo x = bar $ (baz $ (quux $ x))

However, ($) would be useful in more expressions if it were infixl; for example, something like

foo 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 be

foo x = ((bar $ baz) $ quux) $ x

which means something significantly different. So, future-proof your code by avoiding this form.

这篇关于是美元运算符($)被认为是坏形式吗?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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