How to invert IndexedSeq in Scala?

Having IndexedSeq, how do I iterate from end to beginning?

+3


source to share


2 answers


You can call reverseIterator

if you just want to iterate from end to beginning. If you want to use the card reverseMap

. foldLeft

and foldRight

run in opposite directions, so each can be seen as the other in the reverse list; similarly reduceRight

and scanRight

. There are several methods last

for finding things near the end rather than the beginning. Anything else and reverse

(to recreate the entire collection) or .view.reverse.whatever

if you don't want to duplicate the collection in memory. For simple things foreach

, reverseIterator

usually does the trick.



+9


source


You can simply change it:

scala> val x = IndexedSeq(1,2,3,4)
x: IndexedSeq[Int] = Vector(1, 2, 3, 4)

scala> x.reverse.foreach(println)
4
3
2
1

      



Or, depending on what you do during the replay, it foldRight

might be what you want. foldRight

is a fold that moves from right to left through the collection.

scala> x.foldRight(0){ (item, total) => println("adding "+item); total + item }
adding 4
adding 3
adding 2
adding 1
res121: Int = 10

      

+4


source







All Articles