Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 558
Henry Henrinson Avatar asked Jul 27 '11 10:07

Henry Henrinson


People also ask

Is Dollar sign an operator?

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.

What is Haskell operator?

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).

What does the dollar sign do in Haskell?

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).

What does <$> mean in Haskell?

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.


2 Answers

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
like image 168
Anonymous Avatar answered Oct 02 '22 16:10

Anonymous


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.

like image 31
Kevin Wright Avatar answered Oct 02 '22 14:10

Kevin Wright