Reputation: 23220
I wrote map1
function similar to List.map
as:
def map1[A, B](xs: List[A], f: A => B): List[B] = {
xs match {
case List() => scala.collection.immutable.Nil
case head :: tail => f(head) :: map1(tail, f)
}
}
Now when I call the above as:
map1(List(1, 2, 3), x => x + 1)
I get error as: error: missing parameter type
. But following works:
List(1, 2, 3).map(x => x + 1)
Why map1
doesn't work with lamdas?
Upvotes: 1
Views: 80
Reputation: 149626
In Scala, argument type inference works between argument lists and not inside them. To help the compiler infer the type, move f
to it's own argument list:
def map1[A, B](xs: List[A])(f: A => B): List[B] = {
xs match {
case Nil => scala.collection.immutable.Nil
case head :: tail => f(head) :: map1(tail)(f)
}
}
Upvotes: 4