Well, this is a pretty literal translation:
def flip[A, B, C](f: A => B => C)(x: B)(y: A) = f(y)(x)
Now you can write the following:
scala> def append: String => String => String = a => a + _ append: String => (String => String) scala> append("foo")("bar") res0: String = foobar scala> val flipped = flip(append) _ flipped: String => (String => String) = <function1> scala> flipped("foo")("bar") res1: String = barfoo
You can argue that the following is a bit closer to the spirit of the Haskell version:
def flip[A, B, C](f: A => B => C): B => A => C = x => y => f(y)(x)
Now you do not need to use the eta-expand partially applied method:
scala> val flipped = flip(append) flipped: String => (String => String) = <function1> scala> flipped("foo")("bar") res2: String = barfoo
So you have a few options. It's not entirely clear that it looks more like a Haskell implementation, but given the difference between Scala between methods and functions, they are both pretty close.
source share