Wednesday, April 29, 2015

Learning Scala 1: swap array elements

Here posted my solution for the exercise 2 and 3 of Chapter 3 of page 39, in the book "Scala for the impatient".

Exercise 2.  Write a loop that swaps adjacent elements of an array of integers. For example,
Array(1, 2, 3, 4, 5)  becomes Array(2, 1, 4, 3, 5) .

Exercise 3.  Repeat the preceding assignment, but produce a new array with the swapped
values. Use for /yield.

Note: I realize you can not write java style for yield statement, like if ( i%2 ==0 ) yield s(i+1)

No comments:

Post a Comment