Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 535
Lord of the Goo Avatar asked Aug 03 '13 23:08

Lord of the Goo


1 Answers

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.

like image 150
Chris Martin Avatar answered Sep 24 '22 02:09

Chris Martin