I have a list of strings in scala template of play framework.
I want to iterate over half of list at one time and then the other half of list on the second time.
I am not sure how to write efficient iterator for this.
I have tried
@for(i <- 0 until list.length/2 ) {list(i) }
and then for second loop
@for(i <- list.length/2+1 until list.length )
{ list(i) }
This works but complexity becomes high.
Then later I did
@defining(list.size) { size =>
@for(i <- 0 until size/2)
{list(i) }
}
Now it seems to work fine.
Here's one way.
scala> List("a","b","c","d","e")
res0: List[String] = List(a, b, c, d, e)
scala> res0.splitAt(res0.size/2)
res1: (List[String], List[String]) = (List(a, b),List(c, d, e))
scala> res1._1.foreach(println(_))
a
b
scala> res1._2.foreach(println(_))
c
d
e
Use sliding to create iterators,
scala> val input = List(1, 2, 3)
input: List[Int] = List(1, 2, 3)
scala> val step = (input.length + 1 ) / 2
step: Int = 2
scala> val sliding = input.sliding(step, step)
sliding: Iterator[List[Int]] = non-empty iterator
scala> val left = sliding.next()
left: List[Int] = List(1, 2)
scala> val right = sliding.next()
right: List[Int] = List(3)
scala> left.foreach(println)
1
2
scala> right.foreach(println)
3
or use take & drop,
scala> val input = List(1, 2, 3)
input: List[Int] = List(1, 2, 3)
scala> val step = (input.length + 1 ) / 2
step: Int = 2
scala> input.take(step).foreach(println)
1
2
scala> input.drop(step).foreach(println)
3
Iterator
might be a good choice.
scala> val list = List(1,2,3,4,5,6)
list: List[Int] = List(1, 2, 3, 4, 5, 6)
scala> val iterator = list.toIterator
iterator: Iterator[Int] = non-empty iterator
scala> val half = (0 until list.size / 2)
half: scala.collection.immutable.Range = Range(0, 1, 2)
scala> val left = (list.size / 2 until list.size)
left: scala.collection.immutable.Range = Range(3, 4, 5)
scala> half foreach { x => println(x + ":" + iterator.next) }
0:1
1:2
2:3
scala> left foreach { x => println(x + ":" + iterator.next) }
3:4
4:5
5:6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.