Tuesday 14 July 2015

Compose and AndThen functions in Scala

Function Composition

Let’s make two aptly-named functions:
scala> def f(s: String) = "f(" + s + ")"
f: (String)java.lang.String

scala> def g(s: String) = "g(" + s + ")"
g: (String)java.lang.String

compose

compose makes a new function that composes other functions f(g(x))
scala> val fComposeG = f _ compose g _
fComposeG: (String) => java.lang.String = <function>

scala> fComposeG("yay")
res0: java.lang.String = f(g(yay))

andThen

andThen is like compose, but calls the first function and then the second, g(f(x))
scala> val fAndThenG = f _ andThen g _
fAndThenG: (String) => java.lang.String = <function>

scala> fAndThenG("yay")
res1: java.lang.String = g(f(yay))
In Scala, one way to compose functions is "f andThen g", which is the same as
def newFunc[T](x: T) = g(f(x))
You can think of it as "evaluate f(x) and then evaluate g with that result". It's an easy way to chain functions and it's good for noncommutative operations, where "order matters".

How to use andThen for function with multiple parameters instead of one?

andThen is the combinator combines functions by taking one parameter(Function1)
For Function2 chains, we convert each to a Function1 form by calling the tupled method.
The tupled method converts the two-parameter versioin into a one-parameter version by stashing the parameters into a tuple and accepting that instead.



No comments:

Post a Comment