Wednesday 4 May 2016

Scala Useful Code Snippets for Beginners(Part-1): Arrays

Question

How do we retrieve Array elements in (ArrayElement, ElementIndex) or (ElementIndexArrayElement) ?


We can do it in two ways: Lazily and Eagerly

scala> val myIntArry = Array(10, 2, 30, 33, 12, 1, 17)
myIntArry: Array[Int] = Array(10, 2, 30, 33, 12, 1, 17)

scala> for(arrayElement <- myIntArry) println(arrayElement)
10
2
30
33
12
1
17

Lazy Evaluation:


scala> for((index,value) <- myIntArry.view.zipWithIndex) yield (index,value)
res1: Seq[(Int, Int)] = SeqViewZFM(...)

As its created lazily, we are not seeing any elements. We can see elements only when we access them.

scala> for((value,index) <- myIntArry.view.zipWithIndex) println(index,value)
(0,10)
(1,2)
(2,30)
(3,33)
(4,12)
(5,1)
(6,17)

Eager Evaluation:

In approach, whether we access it or not, elements are created.
                                                   
scala>  for(i <- Range(0,myIntArry.length)) yield(i,myIntArry(i))

res7: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,10), (1,2), (2,30), (3,33), (4,12), (5,1), (6,17))

scala>  for(i <- Range(0,myIntArry.length)) println(i,myIntArry(i))
(0,10)
(1,2)
(2,30)
(3,33)
(4,12)
(5,1)
(6,17)


That's it. I will write some more useful posts like this.

Please drop me a comment if you like my posts.

Thank you for reading my tutorial.

No comments:

Post a Comment