Is it possible to implement flip in Scala, as implemented in Haskell?

Is it possible to implement flip in Scala, as implemented in Haskell?

http://hackage.haskell.org/package/base-4.7.0.1/docs/src/GHC-Base.html#flip

flip :: (a -> b -> c) -> b -> a -> c flip fxy = fyx 
+5
source share
2 answers

Another way, closer to the Haskell version:

 scala> def flip[a, b, c]: (a => b => c) => b => a => c = f => x => y => f(y)(x) flip: [a, b, c]=> (a => (b => c)) => (b => (a => c)) scala> val f: Int => Char => String = i => c => f"Int($i) and Char($c)" f: Int => (Char => String) = <function1> scala> val g = flip(f) g: Char => (Int => String) = <function1> 

Or that:

 scala> def flip[a, b, c]: (a => b => c) => b => a => c = { | case f => x => y => f(y)(x) | } flip: [a, b, c]=> (a => (b => c)) => (b => (a => c)) scala> g('a')(100) res0: String = Int(100) and Char(a) scala> f(100)('a') res1: String = Int(100) and Char(a) 
+3
source

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.

+7
source

Source: https://habr.com/ru/post/1200531/


All Articles