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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With