KaC
KaC

Reputation: 613

How to compose curried functions in Scala

Is it possible compose functions in Scala that are curried? For example:

def a(s1: String)(s2: String): Int = s1.length + s2.length
def b(n: Int): Boolean = n % 2 == 0

def x : String => String => Boolean = a andThen b

x("blabla")("foo") 

Edit :

I've found a way of doing it in Haskell :

a :: String -> String -> Int
a s1 s2 = length s1 + length s2

b :: Int -> Bool
b n = mod n 2 == 0

c :: String -> String -> Bool 
c = curry (b . (uncurry a))

Upvotes: 3

Views: 606

Answers (1)

Tim
Tim

Reputation: 27356

This should work:

def x = a _ andThen (_ andThen b)

The first _ avoids invoking a and makes it into a function value. This value is of type String=>String=>Int, i.e. a function that takes String and returns String=>Int.

The argument to the andThen method is a function that takes the result of the original function and modifies it. So in this case it requires a function that takes String=>Int and returns a new value, a function String=>Boolean. We can fabricate this new function by using andThen on the original function. This takes the result of a and composes it with the new function b.

Upvotes: 3

Related Questions