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) .

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

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

2 comments:

  1. please post the functional programming style version as well please

    ReplyDelete
    Replies
    1. l.sliding(2,2).map(x => x.reverse).toList.flatten

      Delete