7

F# has the pipeline operators:

arg |> func // or arg2 |> func arg1, as opposed to func arg1 arg2
func <| arg

Haskell has the $ operator:

func $ arg -- or func1 $ func2 arg, as opposed to func1 (func2 arg)

They're mostly used to increase readability by de-cluttering the function calls.

Is there a similar operator in Scala?

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
Electric Coffee
  • 11,733
  • 9
  • 70
  • 131

2 Answers2

13

There is not. You can easily define your own, however.

implicit class PipeEverything[A](val underlying: A) extends AnyVal {
  def |>[B](f: A => B) = f(underlying)
}
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • 1
    I should probably mention that `$` is right-associative and not only lets you pass in single arguments, but entire expressions as a parameter – Electric Coffee Mar 07 '14 at 09:44
  • 1
    @ElectricCoffee If you want right-associativity, call it `$:`. `|>` is already lowest precedence, except for letters (see http://stackoverflow.com/questions/2922347/operator-precedence-in-scala). – Alexey Romanov Mar 07 '14 at 13:32
  • 2
    @ElectricCoffee - You can always put an expression on the left; you just need parentheses or braces. If you append a `:` to a symbolic method name, it will be right-associative. So `|:` would be a right-associative `|>`. – Rex Kerr Mar 07 '14 at 18:59
  • @RexKerr The whole point of the `$` is to REMOVE parentheses, so having to add them would render it pointless – Electric Coffee Mar 07 '14 at 19:30
  • @ElectricCoffee - There can be other reasons to prefer the argument first (e.g. `(xs.head + 2) |> { y => (y,y) }`). "I want Scala to look like Haskell" is a motivation that will leave you disappointed sooner or later. (As will "I want Haskell to look like Scala", etc..) – Rex Kerr Mar 07 '14 at 23:08
  • oh but I don't want one to look like the other; I just want the convenience of not having to type more than I absolutely need to – Electric Coffee Mar 09 '14 at 00:09
  • @ElectricCoffee - "Not having to type more than I absolutely need to" is more of a Haskell design goal than a Scala one. Consistency with other languages' syntax and readability are higher up on Scala's list. – Rex Kerr Mar 09 '14 at 20:57
1

Scala does not have this operator in the standard library.

Scalaz brings the thrush operator:

arg |> method

If you prefer Cats to Scalaz, you need the Mouse companion library to get the same operator.