(3 из 3)      << | < | 1 | 2 | 3 | > | >>

6. Tuples

Tuple an association of various objects in one structure, such as (1, 3.14, "John"):

val t = (1, 3.14, "John")  // t: (Int, Double, String) = (1,3.14,John)
t._1  // Int = 1
t._2  // Double = 3.14
t._3  // String = John
val (first, second, third) = t  // first = 1 second = 3.14 third = John
val (first1, second1, _) = t  // first1 = 1 second1 = 3.14 (used not all)

Zipping:

val symbols = Array("<", "-", ">")
val counts = Array(2, 10, 2)
val pairs = symbols zip counts  // Array[(String, Int)] = Array((<,2), (-,10), (>,2))
for ((s, n) <- pairs) print(s*n)  // <<---------->>

Two Lists to Map transformation:

val keys = List(1,2,3)
val values = List("a","b","c")
(keys zip values).toMap // Map(1 -> a, 2 -> b, 3 -> c)

7. Lists

From abstract collections to Lists:

val t  = Traversable(1,2,3) // List(1, 2, 3)
val i  = Iterable(1,2,3) // List(1, 2, 3)
val sq = Seq(1,2,3) // List(1, 2, 3)

Operations with Lists:

val odds = List(1,3,5,7,9)
val evens = List(2,4,6,8)
val nums = odds ++ evens // List(1,3,5,7,9,2,4,6,8)
val digs = 0 :: nums // List(0,1,3,5,7,9,2,4,6,8)
val lstr = "a" :: "b" :: "c" :: Nil // List(a, b, c)

Other useful examples:

val list = List(1,-2,3,2,-1,0,-3)
list.head // 1
list.tail // List(-2, 3, 2, -1, 0, -3)
list.last // -3
list.take(4) // List(1, -2, 3, 2)
list.takeRight(4) // List(2, -1, 0, -3)
list.slice(3,6) // List(2, -1, 0)
list.sum // 0
list.min // -3
list.max // 3
list.contains(3) // true
list.indexOf(3) // 2
list.contains(5) // false
list.mkString // 1-232-10-3
list.mkString(",") // 1,-2,3,2,-1,0,-3
list.count(x => x*x>1) // 4
list.filter(x => x >0) // List(1, 3, 2)
list.map(x => if (x<0) -x*x else x*x) // List(1, -4, 9, 4, -1, 0, -9)
list.splitAt(4) // (List(1, -2, 3, 2),List(-1, 0, -3))
list.partition(x => x>0) // (List(1, 3, 2),List(-2, -1, 0, -3))
list.groupBy(x => x*x) //  Map(4 -> List(-2, 2), 1 -> List(1, -1), 9 -> List(3, -3), 0 -> List(0))
List(1,2,3) intersect List(2,3,4) // List(2, 3) 
List(1,2,3) diff List(2,3,4) // List(1)              
List(1,2,3).permutations.toList // List(List(1, 2, 3), List(1, 3, 2), List(2, 1, 3), List(2, 3, 1), List(3, 1, 2), List(3, 2, 1))
List(1,2,3).combinations(2).toList // List(List(1, 2), List(1, 3), List(2, 3))
List(List(1,2),List(3,4)).flatten // List(1, 2, 3, 4)
val lz = List(1,2) zip List("a","b") // List((1,a), (2,b))
lz.unzip // (List(1, 2),List(a, b))

Fold and reduce:

List(1,2,3,4).foldLeft(5)((x,y) => x+2*y) // 25 
List(1,2,3,4).reduceLeft((x,y) => x+2*y) // 19

8. Conditionals

Syntax of Scala if ... else construction like in Java, except that it anyway return value:

val x = 0
val y = if (x > 0) 1 else -1 // y: Int = -1 - return value
if (x>0) "plus" else -1 // Any = -1 - return common type Any for Int and String
if (x>0) 1 else () // AnyVal = () 
if (x>0) 1 // AnyVal = () // the same as previous
val r = scala.util.Random
val u = println(if (r.nextInt(10)%3 > 0) "Not multiple of 3" else "Multiple of 3") // u: Unit = () - return value Unit object
def max(x: Int, y: Int) = if (x > y) x else y // maximum function
max(5, 3) // 5

9. Loops

While and do ... while loops the same as in Java:

var sum = 0
while (sum < 10) sum += 1 // sum = 10 after loop
sum = 0
var k = 0
while (k < 10) {
  sum += k*k
  k +=1
} // k = 10, sum = 285

Scala basic for loop: for (e <- l) { ... } , where e runs over all elements l and l is some kind of Seq:

var sum1 = 0
val l =  List(1,2,3,4,5)
for(e <- l) sum1 += e // sum1 = 15
sum1 = 0
for(i <- 1 to 10) sum1 += i // sum1 = 55 
sum1 = 0
for (ch <- "Hello") sum1 += ch // 500 - sum of ASCII codes

More complex for loop examples:

for (i <- 1 to 3; j <- 1 to 3) print((10 * i + j) + " ") // 11 12 13 21 22 23 31 32 33
for (i <- 1 to 3; j <- 1 to 3 if (i != j)) print((10 * i + j) + " ") // 12 13 21 23 31 32
for (i <- 1 to 3; from = 4 - i; j <- from to 3) print((10 * i + j) + " ") // 13 22 23 31 32 33

For comprehensions:

for (i <- 1 to 10) yield i % 3 // Vector(1, 2, 0, 1, 2, 0, 1, 2, 0, 1)
for {
  x <- 1 to 3
  y <- 'a' to 'b'
} yield (x, y) // Vector((1,a), (1,b), (2,a), (2,b), (3,a), (3,b))
for {
  i <- 1 to 10
  j <- i to 10
  k = i + j
  if (i%2==1)&&(j%2==1)
  if k > 10
} yield (i,j) // Vector((3,9), (5,7), (5,9), (7,7), (7,9), (9,9))

10. Small Challenge

Variation of theme that uses some of the previous topics to create a small challenge.

Write implementation of the next functions or tasks:

1. def signum(x: Int): Int = ??? // -1 if x<0, 1 if x>0, 0 if x=0
2. def update(a: Array[Int]): Array[Int] = ??? 
// Array a should be divided into three parts (part1: x>0, part2: x=0 and part3: x<0)
// return an array where the first part precedes the second and the second precedes third 
3. Remove all digits from String.
4. Count number of occurrences for each character of String and get list of tuples, sorted in descending order by number of occurrences. 
5. Get a String from the first letters of a list of Strings
6. Remove first occurrence of given element from the list.
(3 из 3)      << | < | 1 | 2 | 3 | > | >>

Комментарии (0)

Автор (*):Город:
Эл.почта:Сайт:
Текст (*):