How can I fold the nth and (n+1)th elements into a new list in Scala? -


let's have list(1,2,3,4,5) , want list(3,5,7,9), is, sums of element , previous (1+2, 2+3,3+4,4+5)

i tried making 2 lists:

val list1 = list(1,2,3,4) val list2 = (list1.tail ::: list(0))                   // 2,3,4,5,0 (n0_ <- list1; n1th_ <- list2) yield (n0_ + n1_) 

but combines elements each other cross product, , want combine elements pairwise. i'm new functional programming , thought i'd use map() can't seem so.

list(1, 2, 3, 4, 5).sliding(2).map(_.sum).to[list] job.

docs:

def sliding(size: int): iterator[seq[a]]  

groups elements in fixed size blocks passing "sliding window" on them (as opposed partitioning them, done in grouped.)


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -