开发者

Is there a Scala operator similar to Haskell's $ (dollar sign)?

Is there any way开发者_运维百科 to force operator precedence in Scala like you do in Haskell with $?

For example, in Haskell, you have:

a b c = ((a b) c)

and

a $ b c = a (b c)

Is there a similar way to do this in Scala? I know Scala doesn't have operators per se, but is there a way to achieve a similar effect?


It is possible to use implicits to achieve a similar effect. For example: (untested, but should be something like this)

object Operator {

  class WithOperator[T](that: T) {
    def &:[U](f: T => U) = f(that)
  }
  implicit def withOperator[T](that: T) = new WithOperator(that)

}

Using this system, you can't use the name $, because the name needs to end with a : (to fix the associativity) and the dollar is a normal identifier (not operator identifier), so you can't have it in the same name as a :, unless you separate them with underscores.

So, how do you use them? Like this:

val plusOne = (x: Int) => {x + 1}
plusOne &: plusOne &: plusOne &: 1


infix vs . notation is often used in a similar fashion to control precedence:

a b c d == a.b(c).d
a.b c d == a.b.c(d)
a b c.d == a.b(c.d)

Scala also has a fixed precedence ordering for operators used in infix notation:

(all letters)
|
^
&
< >
= !
:
+ -
* / %
(all other special characters)

Names can usually chosen explicitly to take advantage of this. For example, ~ and ^^ in the standard parsers library.


Scalaz has defined a "pipe" operator, which works similar, but with flipped arguments. See switch function and object with scalaz' |>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜