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?
Because sliding() returns an Iterator, which is not a List.
numbers.sliding(2).map{case Seq(x,y) => action(x,y)}.toList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With