Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Function Composition

Tags:

function

scala

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.

like image 597
Alex Peake Avatar asked Dec 14 '22 23:12

Alex Peake


1 Answers

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)).

like image 88
lpiepiora Avatar answered Jan 03 '23 04:01

lpiepiora