progs/lecture1.scala
changeset 478 0e6ca70496c1
parent 468 c71ae4477e55
child 491 2a30c7dfe3ed
equal deleted inserted replaced
477:2403c931a32f 478:0e6ca70496c1
     1 // Scala Lecture 1
     1 // Scala Lecture 1
     2 //=================
     2 //=================
     3 
     3 
     4 // - List, Sets, Strings, ... 
     4 // - List, Sets, Ints, Strings, ... 
     5 // - Value assignments (val vs var)
     5 // - Value assignments (val vs var)
     6 // - How to define functions? (What is returned?)
     6 // - How to define functions? (What is returned?)
     7 // - If-Conditions
     7 // - If-Conditions
     8 // - For-Comprehensions (guards, with/without yield)
     8 // - For-Comprehensions (guards, with/without yield)
     9 // - String-Interpolations
     9 // - String-Interpolations
    17 
    17 
    18 
    18 
    19 val x = 42
    19 val x = 42
    20 val y = 3 + 4 
    20 val y = 3 + 4 
    21 val z = x / y
    21 val z = x / y
    22 val x = 70
    22 val x = 0
    23 println(z)
    23 println(z)
    24 
    24 
    25 
    25 
    26 // (you cannot reassign values: z = 9 will give an error)
    26 // (you cannot reassign values: z = 9 will give an error)
    27 //var z = 9
    27 var z = 9
    28 //z = 10
    28 z = 10
    29 
    29 
    30 
       
    31 // Hello World
       
    32 //=============
       
    33 
       
    34 // an example of a stand-alone Scala file
       
    35 // (in the assignments you must submit a plain Scala script)
       
    36 
       
    37 object Hello extends App { 
       
    38   println("hello world")
       
    39 }
       
    40 
       
    41 // can then be called with
       
    42 //
       
    43 // $> scalac hello-world.scala
       
    44 // $> scala Hello
       
    45 //
       
    46 // $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
       
    47 
    30 
    48 
    31 
    49 
    32 
    50 // Collections
    33 // Collections
    51 //=============
    34 //=============
    53 List(1,2,3,1)
    36 List(1,2,3,1)
    54 Set(1,2,3,1)
    37 Set(1,2,3,1)
    55 
    38 
    56 // picking an element in a list
    39 // picking an element in a list
    57 val lst = List(1, 2, 3, 1)
    40 val lst = List(1, 2, 3, 1)
       
    41 
    58 
    42 
    59 lst(0)
    43 lst(0)
    60 lst(2)
    44 lst(2)
    61 
    45 
    62 // head and tail
    46 // head and tail
    82 (1 until 10).toList
    66 (1 until 10).toList
    83 
    67 
    84 
    68 
    85 // Equality in Scala is structural
    69 // Equality in Scala is structural
    86 //=================================
    70 //=================================
    87 val a = "Dave"
    71 val a = "Dave2"
    88 val b = "Dave"
    72 val b = "Dave"
    89 
    73 
    90 if (a == b) println("Equal") else println("Unequal")
    74 if (a == b) println("Equal") else println("Unequal")
    91 
    75 
    92 Set(1,2,3) == Set(3,1,2)
    76 Set(1,2,3) == Set(3,1,2)
   157 
   141 
   158 "1,2,3,4,5".split(",").mkString("\n")
   142 "1,2,3,4,5".split(",").mkString("\n")
   159 "1,2,3,4,5".split(",").toList
   143 "1,2,3,4,5".split(",").toList
   160 "1,2,3,4,5".split(",3,").mkString("\n")
   144 "1,2,3,4,5".split(",3,").mkString("\n")
   161 
   145 
   162 "abcdefg".startsWith("abc")
       
   163 
   146 
   164 
   147 
   165 // Types (see slide)
   148 // Types (see slide)
   166 //===================
   149 //===================
   167 
   150 
   237 // type to each argument and a return type of the function
   220 // type to each argument and a return type of the function
   238 //
   221 //
   239 //  def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
   222 //  def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
   240 //     ....
   223 //     ....
   241 //  }
   224 //  }
       
   225 
       
   226 
       
   227 // > LENGTH OF LIST EXAMPLE
       
   228 def len(xs: List[Int], acc: Int) : Int = {
       
   229    if (xs == Nil) acc
       
   230    else foo(xs.tail, acc + 1)
       
   231 }
       
   232 
       
   233 def len(xs: List[Int]) : Int = foo(xs, 0)
       
   234 
       
   235 len(List(1,2,3,4,1))
       
   236 
       
   237 
       
   238 def len(xs: List[Int]) : Int = {
       
   239     if (xs == Nil) 0
       
   240     else (1 + len(xs.tail))
       
   241 }    
       
   242 
       
   243 
       
   244 
       
   245 len(List(1,2,3,4,1))
       
   246 
       
   247 
       
   248 
       
   249 def len(xs: List[Int]) : Int = xs match {
       
   250    case Nil => 0
       
   251    case x :: xs => 1 + len(xs)
       
   252 }
       
   253 
       
   254 len(List(1,2,3,4,1))
   242 
   255 
   243 
   256 
   244 
   257 
   245 // If-Conditionals
   258 // If-Conditionals
   246 //=================
   259 //=================
   316 for (n <- lst) yield { 
   329 for (n <- lst) yield { 
   317   square(n) + double(n)
   330   square(n) + double(n)
   318 }
   331 }
   319 
   332 
   320 for (n <- (1 to 10).toList; 
   333 for (n <- (1 to 10).toList; 
   321      m <- (1 to 5).toList) yield (n, m, n * m)
   334      m <- (1 to 5).toList) yield (n, m)
   322 
   335 
   323 
   336 
   324 // you can assign the result of a for-comprehension
   337 // you can assign the result of a for-comprehension
   325 // to a value
   338 // to a value
   326 val mult_table = 
   339 val mult_table = 
   327   for (n <- (1 to 10).toList; 
   340   for (n <- (1 to 10).toList; 
   328        m <- (1 to 10).toList) yield n * m
   341        m <- (1 to 10).toList) yield n * m
   329 
   342 
   330 println(mult_table.mkString)
   343 println(mult_table.mkString(","))
   331 mult_table.sliding(10,10).mkString("\n")
   344 mult_table.sliding(10,10).toList
       
   345 
       
   346 
       
   347 .mkString("\n")
   332 
   348 
   333 // for-comprehensions also work for other
   349 // for-comprehensions also work for other
   334 // collections
   350 // collections
   335 
   351 
   336 for (n <- Set(10,12,4,5,7,8,10)) yield n * n
   352 for (n <- Set(10,12,4,5,7,8,10)) yield n * n
   337 
   353 
   338 for (n <- (1 to 10)) yield {
   354 for (n <- (1 to 10)) yield {
       
   355 
   339   n * n  
   356   n * n  
   340 }
   357 }
   341 
   358 
   342 // with if-predicates / filters
   359 // with if-predicates / filters
       
   360 
       
   361 val xs = for (n <- (1 to 3).toList; 
       
   362      m <- (1 to 3).toList) yield (n,m)
       
   363 
       
   364 xs.filter{case (m, n) => (n + m) % 2 == 0}    
   343 
   365 
   344 for (n <- (1 to 3).toList; 
   366 for (n <- (1 to 3).toList; 
   345      m <- (1 to 3).toList;
   367      m <- (1 to 3).toList;
   346      if (n + m) % 2 == 0) yield (n, m)
   368      if (n + m) % 2 == 0) yield (n, m)
   347 
   369 
   348 
   370 
   349 // with patterns
   371 // with patterns
   350 
   372 
   351 val lst = List((1, 4), (2, 3), (3, 2), (4, 1))
   373 val lst = List((1, 4), (2, 3), (3, 2), (4, 1))
   352 
   374 
   353 for ((m, n) <- lst) yield m + n 
   375 ` yield m + n 
   354 
   376 
   355 for (p <- lst) yield p._1 + p._2 
   377 for (p <- lst) yield p._1 + p._2 
   356 
   378 
   357 
   379 
   358 // general pattern of for-yield 
   380 // general pattern of for-yield 
   367 //===================
   389 //===================
   368 
   390 
   369 // with only a side-effect (no list is produced),
   391 // with only a side-effect (no list is produced),
   370 // has no "yield"
   392 // has no "yield"
   371 
   393 
   372 for (n <- (1 to 10).toList) println(n * n)
   394 val xs = for (n <- (1 to 10).toList) yield println(n * n)
   373 
   395 
   374 for (n <- (1 to 10).toList) yield n * n
   396 xs.tail
       
   397 
       
   398 val foo = for (n <- (1 to 10).toList) yield n * n
   375 
   399 
   376 
   400 
   377 // BTW: a roundabout way of printing out a list, say
   401 // BTW: a roundabout way of printing out a list, say
   378 val lst = ('a' to 'm').toList
   402 val lst = ('a' to 'm').toList
   379 
   403 
   448 // Remember:
   472 // Remember:
   449 // - no vars, no ++i, no +=
   473 // - no vars, no ++i, no +=
   450 // - no mutable data-structures (no Arrays, no ListBuffers)
   474 // - no mutable data-structures (no Arrays, no ListBuffers)
   451 
   475 
   452 // But what the heck....lets try to count to 1 Mio in parallel
   476 // But what the heck....lets try to count to 1 Mio in parallel
       
   477 // 
       
   478 // requires
       
   479 // scala-cli --extra-jars scala- parallel-collections_3-1.0.4.jar
       
   480 
   453 import scala.collection.parallel.CollectionConverters._
   481 import scala.collection.parallel.CollectionConverters._
   454 
   482 
   455 var cnt = 0
   483 def test() = {
   456 
   484   var cnt = 0
   457 for(i <- (1 to 100_000).par) cnt += 1
   485 
   458 
   486   for(i <- (1 to 100_000)) cnt += 1
   459 println(s"Should be 100000: $cnt")
   487 
   460 
   488   println(s"Should be 100000: $cnt")
   461 
   489 }
       
   490 
       
   491 test()
   462 
   492 
   463 // Or
   493 // Or
   464 // Q: Count how many elements are in the intersections of 
   494 // Q: Count how many elements are in the intersections of 
   465 //    two sets?
   495 //    two sets?
   466 // A; IMPROPER WAY (mutable counter)
   496 // A; IMPROPER WAY (mutable counter)