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?

Henry Henrinson
  • 5,203
  • 7
  • 44
  • 76

3 Answers3

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
Anonymous
  • 821
  • 1
  • 5
  • 14
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.

Kevin Wright
  • 49,540
  • 9
  • 105
  • 155
8

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

Community
  • 1
  • 1
Landei
  • 54,104
  • 13
  • 100
  • 195