progs/lecture1.scala
changeset 447 f51e593903ac
parent 444 7a0735db4788
child 471 135bf034ac30
equal deleted inserted replaced
446:99dcfdf5aed8 447:f51e593903ac
     1 // Scala Lecture 1
     1 // Scala Lecture 1
     2 //=================
     2 //=================
     3 
     3 
     4 
     4 // - List, Sets, Strings, ... 
       
     5 // - Value assignments (val vs var)
       
     6 // - How to define functions? (What is returned?)
       
     7 // - If-Conditions
       
     8 
       
     9 val tmp = 0
       
    10 val result = !(tmp == 0)
       
    11 val result = if (tmp == 0) true else false
       
    12 
       
    13 //        expressions (if (tmp == 0) true else false)
       
    14 // - For-Comprehensions (guards, with/without yield)
       
    15 //
       
    16 //
       
    17 // - Options
       
    18 // - Higher-Order Functions (short-hand notation)
       
    19 // - maps (behind for-comprehensions)
       
    20 // - Pattern-Matching
       
    21 // - String-Interpolations
     5 
    22 
     6 // Value assignments
    23 // Value assignments
     7 // (their names should be lower case)
    24 // (their names should be lower case)
     8 //====================================
    25 //====================================
     9 
    26 
   178 
   195 
   179 
   196 
   180 // you can make the type of a value explicit
   197 // you can make the type of a value explicit
   181 val name = "bob"
   198 val name = "bob"
   182 
   199 
       
   200 val name : String = "bob"
   183 
   201 
   184 // type errors
   202 // type errors
   185 math.sqrt("64".toDouble)
   203 math.sqrt("64".toDouble)
   186 
   204 
   187 // produces
   205 // produces
   325   n * n  
   343   n * n  
   326 }
   344 }
   327 
   345 
   328 // with if-predicates / filters
   346 // with if-predicates / filters
   329 
   347 
   330 if (1 == 2) "a" else "b"
       
   331 
       
   332 for (n <- (1 to 3).toList; 
   348 for (n <- (1 to 3).toList; 
   333      m <- (1 to 3).toList;
   349      m <- (1 to 3).toList;
   334      if (n + m) % 2 == 0) yield (n, m)
   350      if (n + m) % 2 == 0) yield (n, m)
   335 
   351 
   336 
   352 
   451 //    two sets?
   467 //    two sets?
   452 // A; IMPROPER WAY (mutable counter)
   468 // A; IMPROPER WAY (mutable counter)
   453 
   469 
   454 def count_intersection(A: Set[Int], B: Set[Int]) : Int = {
   470 def count_intersection(A: Set[Int], B: Set[Int]) : Int = {
   455   var count = 0
   471   var count = 0
   456   for (x <- A; if (B contains x)) count += 1 
   472   for (x <- A.par; if (B contains x)) count += 1 
   457   count
   473   count
   458 }
   474 }
   459 
   475 
   460 val A = (0 to 999).toSet
   476 val A = (0 to 999).toSet
   461 val B = (0 to 999 by 4).toSet
   477 val B = (0 to 999 by 4).toSet