Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Higher-Order Functions with Tuples

Tags:

scala

I have the following problem. I was trying to make a high-order function that accepts two parameters: the String and the function type. Function type is defined this way:

(String, List[String]) => List[(String, List[String])]

I have also defined two functions f1 and f2 that has the same type. Afterwards I am trying to call myfun with f1 or f2. Here is the code:

object Main extends App {


def f1(t: (String,List[String])): List[(String,List[String])] = ...

def f2(t: (String,List[String])): List[(String,List[String])] =  ...

def myfun(tableName: String)(fn: (String,List[String]) => List[(String,List[String])]):  List[(String,List[String])] =
 ...

val res: List[(String,List[String])] = myfun("...")(f1)
res foreach println
val res2: List[(String,List[String])] = myfun("...")(f2)
res2 foreach println
}

and here is the error:

[error]  found   : (String, List[String]) => List[(String, List[String])]
[error]  required: (String, List[String]) => List[(String, List[String])]
[error]   val res: List[(String,List[String])] =  myfun("...")(f1)

I cannot understand why the compiler is complaining. Can someone explain it?

like image 253
qwertz1123 Avatar asked Nov 29 '12 16:11

qwertz1123


1 Answers

Try this. Note the extra set of parenthesis surrounding the argument list to fn.

def myfun(tableName: String)
         (fn: ((String,List[String])) => List[(String,List[String])]):  List[(String,List[String])] = ...

Unfortunately this extra set of parenthesis is needed to distinguish

Function1[(String, List[String]), List[(String,List[String])]] 

from

Function2[String, List[String], List[(String, List[String])]]
like image 112
drstevens Avatar answered Sep 28 '22 06:09

drstevens