Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipeline of functions scala

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

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

I know this can be easily done with a list comprehension, but the idea is to do more complex things like

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

which helps to better readable code in my opinion.

like image 667
Brandon Avatar asked Aug 01 '17 10:08

Brandon


2 Answers

While using Scalaz as suggested in other answer for this is perfectly reasonable, you can add simple value class for the same purpose if you want to avoid adding 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
like image 120
P. Frolov Avatar answered Sep 20 '22 19:09

P. Frolov


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))
like image 20
Alexander Ershov Avatar answered Sep 16 '22 19:09

Alexander Ershov