Question

def t[A] = (l:List[A]) => l tail
def r[A] = (r:List[A]) => r reverse
def tr[A] :List[A] => List[A] = t compose r

tr(List(1,2,3,4))

List(3, 2, 1)

As expected.

But somehow, every variant (with several variations of type annotations) I have tried on

def tr = tail compose reverse

fails (not found - value tail). I am missing something obvious, but I am stuck.

Was it helpful?

Solution 3

in scala, A => B will be treated as Function1 which define the method compose, so if u want to use tail compose reverse, you need to give scala compiler hint that what "class" it is, and then change a "method" to a "function".

the example :

def tr[A] = ((x: List[A]) => x.tail) compose ((x: List[A]) => x.reverse)

OTHER TIPS

Well let's start from the back, what compose function does.

It is defined in the Function1 as def compose[A](g: (A) => T1): (A) => R, and description

Composes two instances of Function1 in a new Function1, with this function applied last.

What it does it takes another function g, taking parameter of some type - A, and returning same type T1. It creates new function which , when called is equivalent to call f(g(x)).

The two functions you have defined:

def t[A] = (l:List[A]) => l.tail
def r[A] = (r:List[A]) => r.reverse

They take no parameters, but return functions which take a list and call tail and reverse respectively on the argument.

The same you could write like:

def t[A](l: List[A]): List[A] = l.tail
def r[A](l: List[A]): List[A] = l.reverse

so the composition of two functions is t(r(List(1,2,3,4))).

The tail or reverse however are not functions, they are method defined in a List class. They must be called on an object, and there is no way you could do tail(reverse(arg)).

compose is a function (i.e. Function1) composition.

List[T].tail and List[T].reverse are List[T] methods

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top