Reputation: 3050
The below code snippet took from GITHub Repo. In this code we are doing sum from next two numbers. My Question is in doAction function have toList at the end of curly braces. Why we need this. if i remove toList , then it causing the issue.
def doAction(numbers:List[Int],action: (Int,Int) => Int):List[Int] =
{
for(pair <- numbers.sliding(2)) yield {
action(pair(0),pair(1))
}
}.**toList**
var res = doAction(List(1,2,3,4,5,6,7,8),(a,b)=> a+b)
2. How can i rewrite the same code using map higher order function?
Upvotes: 4
Views: 763
Reputation: 51271
Because sliding()
returns an Iterator
, which is not a List
.
numbers.sliding(2).map{case Seq(x,y) => action(x,y)}.toList
Upvotes: 6