Scala function piping

Is it possible to create a pipeline of functions in scala ?. I wanted to do something like the following syntax in F #, achieved with the | >

indexPairs |> Seq.iter (fun (i,j) -> parents.[j] <- Some nodes.[i])

      

I know it can be done easily with a list, but the idea is to do more complicated things like

indexPairs |> Seq.groupBy fst |> Seq.iter (fun (i, pairs) -> sons.[i] <- pairs |> Seq.map (fun (_,j) -> nodes.[j]) |> Seq.toList)

      

which helps me read the code better in my opinion.

+3


source to share


3 answers


When used Scalaz

as suggested in another answer, it makes perfect sense to do this, you can add a simple value class for the same purpose if you want to avoid adding an external library dependency:



implicit class ChainOps[A](val value: A) extends AnyVal {
  def |>[B](f: A => B): B = f(value)
}

def add(other: Int)(x: Int): Int = x + other
def mul(other: Int)(x: Int): Int = x * other
val value = 12
value |> add(9) |> mul(2) // 42

      

+3


source


You can use either compose

or andThen

.



val fComposeG = f _ compose g _ // fComposeG(x) equals f(g(x))
val fAndThenG = f _ andThen g _ // fAndThenG(x) equals g(f(x))

      

+2


source


You can use the pipe operator from Scalaz in syntax like this:

import scalaz.Scalaz._

def f1(a:String):String =a + "1"
def f2(a:String):String =a + "2"
def f3(a:String):String =a + "3"
val text:String = "abc to xyz"
f1(text) |> f3 |> f2

scala> res2: String = abc to xyz132

      

+2


source







All Articles