Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pairwise traversal of list elements

Tags:

scala

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?

like image 713
Learn Hadoop Avatar asked Nov 04 '25 02:11

Learn Hadoop


1 Answers

  1. Because sliding() returns an Iterator, which is not a List.

  2. numbers.sliding(2).map{case Seq(x,y) => action(x,y)}.toList

like image 89
jwvh Avatar answered Nov 07 '25 14:11

jwvh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!