Scala API 2.10.*: Function2.andThen what happened to?

二次信任 提交于 2019-12-22 04:40:52

问题


I'm reading «Scala in Depth» by Joshua Suereth, book that I've bought for the clearly established competency of the author. I'm on page 3 and after a bunch of typos and incoherent formatting (ok, I've become tolerant of these errors) I stumbled upon the following example about a functional approach to solve a very simple scenario.

trait Cat
trait Bird
trait Catch
trait FullTummy

def catch(hunter: Cat, prey: Bird): Cat with Catch
def eat(consumer: Cat with Catch): Cat with FullTummy

val story = (catch _) andThen (eat _)
story(new Cat, new Bird)

I took the example with caution provided it's clearly a blue-print (no concrete methods are defined…)… «catch» is clearly another typo provided it's a reserved word… Cat and Bird are not instantiable…

… but, despite the poor quality of the example, I can't consider that the «story» val defined in terms of function composition (andThen is the «reverse-associative» of compose) is another accidental mistake provided it's the core of the example.

Effectively the example won't compile on my local version of Scala (2.10.1) and it's not documented either on the latest version available (2.10.2).

There is no doubt of its usefulness and that its implementation is easy to accomplish (follow):

trait Function2ex[-T1, -T2, +R] extends Function2[T1, T2, R] {
  def andThen[A](g: R => A): (T1, T2) => A = { (x, y) => g(apply(x, y)) }
} 

After a short scrutiny of the API I found that the andThen is supported only by Function1 and supposedly disappeared from Function2 to Function22 so, the question is:

What is the current idiom to support andThen and compose with Function* of arity greater than 1?


回答1:


I don't understand where that example is going at all, but here's some code that compiles in scala 2.10.2.

trait Cat
trait Bird
trait Catch
trait FullTummy

def `catch`(hunter: Cat, prey: Bird): Cat with Catch = ???
def eat(consumer: Cat with Catch): Cat with FullTummy = ???

val story = (`catch` _).tupled andThen (eat _)
story(new Cat with Catch, new Bird {})

I had to quote catch because it's a reserved word, and tuple the Function2.



来源:https://stackoverflow.com/questions/18038321/scala-api-2-10-function2-andthen-what-happened-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!