3

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))
KaC
  • 613
  • 6
  • 14
  • Possible duplicate of [Scala, currying and overloading](https://stackoverflow.com/questions/7179229/scala-currying-and-overloading) – Sinan Ünür Aug 22 '18 at 16:15
  • 2
    Probably this is the answer you look for https://stackoverflow.com/questions/28566214/andthen-for-function-of-two-arguments-in-scala – FerranJr Aug 22 '18 at 16:18
  • 1
    Thanks for the suggestions, but it's not the same question. There's no overloading, and it's not Function2 since it is curried (so Function1 twice, which has andThen). – KaC Aug 23 '18 at 07:04

1 Answers1

3

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.

Tim
  • 26,753
  • 2
  • 16
  • 29