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 to share