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?
The dollar sign, $ , is a controversial little Haskell operator. Semantically, it doesn't mean much, and its type signature doesn't give you a hint of why it should be used as often as it is. It is best understood not via its type but via its precedence.
Haskell provides special syntax to support infix notation. An operator is a function that can be applied using infix syntax (Section 3.4), or partially applied using a section (Section 3.5).
Dollar sign. Since complex statements like a + b are pretty common and Haskellers don't really like parentheses, the dollar sign is used to avoid parentheses: f $ a + b is equivalent to the Haskell code f (a + b) and translates into f(a + b).
It's merely an infix synonym for fmap , so you can write e.g. Prelude> (*2) <$> [1.. 3] [2,4,6] Prelude> show <$> Just 11 Just "11" Like most infix functions, it is not built-in syntax, just a function definition. But functors are such a fundamental tool that <$> is found pretty much everywhere.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With