21

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?

3 Answers 3

17

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
16

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.

2
  • Pursued again by the phantom downvoter who leaves no explanation... most bizarre Mar 2, 2014 at 20:20
  • 1
    lovely code snippet that first one - i'll keep that handy to remind myself of these rules. thanks Nov 30, 2016 at 23:01
8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.