Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating circular way

I need iterate through a List but circular way. I need too add new elements to the list and iterate over all elements (olds and news elements), How I do it? Is there any data structure for them?

like image 210
barroco Avatar asked Jul 15 '10 13:07

barroco


1 Answers

One option is to use the Stream class to create a lazy, circular, infinite sequence:

scala> val values = List(1, 2, 3)
values: List[Int] = List(1, 2, 3)

scala> Stream.continually(values.toStream).flatten.take(9).toList
res2: List[Int] = List(1, 2, 3, 1, 2, 3, 1, 2, 3)

or this way:

val values = List(1, 2, 3)

def circularStream(values: List[Int],
                   remaining: List[Int] = List()): Stream[Int] = {

  if (remaining.isEmpty)
    circularStream(values,values)
  else
    Stream.cons(remaining.head, circularStream(values, remaining.drop(1)))
}

circularStream(values).take(9).toList //Same result as example #1
like image 75
dbyrne Avatar answered Sep 18 '22 17:09

dbyrne