| 238 |      1 | // Scala Lecture 5
 | 
| 222 |      2 | //=================
 | 
|  |      3 | 
 | 
| 333 |      4 | 
 | 
| 222 |      5 | 
 | 
| 238 |      6 | // Laziness with style
 | 
|  |      7 | //=====================
 | 
| 222 |      8 | 
 | 
| 240 |      9 | // The concept of lazy evaluation doesn’t really 
 | 
| 326 |     10 | // exist in non-functional languages. C-like languages
 | 
| 329 |     11 | // are (sort of) strict. To see the difference, consider
 | 
| 222 |     12 | 
 | 
| 238 |     13 | def square(x: Int) = x * x
 | 
| 222 |     14 | 
 | 
| 238 |     15 | square(42 + 8)
 | 
| 222 |     16 | 
 | 
| 326 |     17 | // This is called "strict evaluation".
 | 
| 222 |     18 | 
 | 
| 329 |     19 | // On the contrary, say we have a pretty expensive operation:
 | 
| 326 |     20 | 
 | 
| 238 |     21 | def peop(n: BigInt): Boolean = peop(n + 1) 
 | 
| 240 |     22 | 
 | 
| 238 |     23 | val a = "foo"
 | 
| 329 |     24 | val b = "foo"
 | 
| 222 |     25 | 
 | 
| 238 |     26 | if (a == b || peop(0)) println("true") else println("false")
 | 
| 222 |     27 | 
 | 
| 326 |     28 | // This is called "lazy evaluation":
 | 
| 238 |     29 | // you delay compuation until it is really 
 | 
| 326 |     30 | // needed. Once calculated though, the result
 | 
|  |     31 | // does not need to be re-calculated.
 | 
| 222 |     32 | 
 | 
| 326 |     33 | // A useful example is
 | 
| 328 |     34 | 
 | 
| 238 |     35 | def time_needed[T](i: Int, code: => T) = {
 | 
|  |     36 |   val start = System.nanoTime()
 | 
|  |     37 |   for (j <- 1 to i) code
 | 
|  |     38 |   val end = System.nanoTime()
 | 
|  |     39 |   f"${(end - start) / (i * 1.0e9)}%.6f secs"
 | 
| 222 |     40 | }
 | 
|  |     41 | 
 | 
| 326 |     42 | // A slightly less obvious example: Prime Numbers.
 | 
|  |     43 | // (I do not care how many) primes: 2, 3, 5, 7, 9, 11, 13 ....
 | 
| 222 |     44 | 
 | 
| 326 |     45 | def generatePrimes (s: LazyList[Int]): LazyList[Int] =
 | 
| 238 |     46 |   s.head #:: generatePrimes(s.tail.filter(_ % s.head != 0))
 | 
|  |     47 | 
 | 
| 326 |     48 | val primes = generatePrimes(LazyList.from(2))
 | 
| 222 |     49 | 
 | 
| 238 |     50 | // the first 10 primes
 | 
| 329 |     51 | primes.take(100).toList
 | 
| 222 |     52 | 
 | 
| 238 |     53 | time_needed(1, primes.filter(_ > 100).take(3000).toList)
 | 
| 326 |     54 | time_needed(1, primes.filter(_ > 100).take(3000).toList)
 | 
| 222 |     55 | 
 | 
| 326 |     56 | // A Stream (LazyList) of successive numbers:
 | 
| 222 |     57 | 
 | 
| 326 |     58 | LazyList.from(2).take(10)
 | 
|  |     59 | LazyList.from(2).take(10).force
 | 
| 222 |     60 | 
 | 
| 326 |     61 | // An Iterative version of the Fibonacci numbers
 | 
|  |     62 | def fibIter(a: BigInt, b: BigInt): LazyList[BigInt] =
 | 
| 238 |     63 |   a #:: fibIter(b, a + b)
 | 
| 222 |     64 | 
 | 
|  |     65 | 
 | 
| 238 |     66 | fibIter(1, 1).take(10).force
 | 
|  |     67 | fibIter(8, 13).take(10).force
 | 
|  |     68 | 
 | 
| 326 |     69 | fibIter(1, 1).drop(10000).take(1)
 | 
|  |     70 | fibIter(1, 1).drop(10000).take(1).force
 | 
| 222 |     71 | 
 | 
|  |     72 | 
 | 
| 326 |     73 | // LazyLists are good for testing
 | 
| 222 |     74 | 
 | 
|  |     75 | 
 | 
|  |     76 | // Regular expressions - the power of DSLs in Scala
 | 
| 238 |     77 | //                                     and Laziness
 | 
| 222 |     78 | //==================================================
 | 
|  |     79 | 
 | 
|  |     80 | abstract class Rexp
 | 
| 226 |     81 | case object ZERO extends Rexp                     // nothing
 | 
|  |     82 | case object ONE extends Rexp                      // the empty string
 | 
|  |     83 | case class CHAR(c: Char) extends Rexp             // a character c
 | 
|  |     84 | case class ALT(r1: Rexp, r2: Rexp) extends Rexp   // alternative  r1 + r2
 | 
|  |     85 | case class SEQ(r1: Rexp, r2: Rexp) extends Rexp   // sequence     r1 . r2  
 | 
|  |     86 | case class STAR(r: Rexp) extends Rexp             // star         r*
 | 
| 222 |     87 | 
 | 
|  |     88 | 
 | 
|  |     89 | // some convenience for typing in regular expressions
 | 
|  |     90 | import scala.language.implicitConversions    
 | 
|  |     91 | import scala.language.reflectiveCalls 
 | 
|  |     92 | 
 | 
|  |     93 | def charlist2rexp(s: List[Char]): Rexp = s match {
 | 
|  |     94 |   case Nil => ONE
 | 
|  |     95 |   case c::Nil => CHAR(c)
 | 
|  |     96 |   case c::s => SEQ(CHAR(c), charlist2rexp(s))
 | 
|  |     97 | }
 | 
| 224 |     98 | implicit def string2rexp(s: String): Rexp = 
 | 
|  |     99 |   charlist2rexp(s.toList)
 | 
| 222 |    100 | 
 | 
|  |    101 | implicit def RexpOps (r: Rexp) = new {
 | 
|  |    102 |   def | (s: Rexp) = ALT(r, s)
 | 
|  |    103 |   def % = STAR(r)
 | 
|  |    104 |   def ~ (s: Rexp) = SEQ(r, s)
 | 
|  |    105 | }
 | 
|  |    106 | 
 | 
|  |    107 | implicit def stringOps (s: String) = new {
 | 
|  |    108 |   def | (r: Rexp) = ALT(s, r)
 | 
|  |    109 |   def | (r: String) = ALT(s, r)
 | 
|  |    110 |   def % = STAR(s)
 | 
|  |    111 |   def ~ (r: Rexp) = SEQ(s, r)
 | 
|  |    112 |   def ~ (r: String) = SEQ(s, r)
 | 
|  |    113 | }
 | 
|  |    114 | 
 | 
| 238 |    115 | 
 | 
| 329 |    116 | 
 | 
| 238 |    117 | 
 | 
| 222 |    118 | //example regular expressions
 | 
|  |    119 | val digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
 | 
|  |    120 | val sign = "+" | "-" | ""
 | 
|  |    121 | val number = sign ~ digit ~ digit.% 
 | 
|  |    122 | 
 | 
| 326 |    123 | // Task: enumerate exhaustively regular expressions
 | 
| 238 |    124 | // starting from small ones towards bigger ones.
 | 
|  |    125 | 
 | 
| 240 |    126 | // 1st idea: enumerate them all in a Set
 | 
|  |    127 | // up to a level
 | 
| 238 |    128 | 
 | 
|  |    129 | def enuml(l: Int, s: String) : Set[Rexp] = l match {
 | 
|  |    130 |   case 0 => Set(ZERO, ONE) ++ s.map(CHAR).toSet
 | 
|  |    131 |   case n =>  
 | 
|  |    132 |     val rs = enuml(n - 1, s)
 | 
|  |    133 |     rs ++
 | 
|  |    134 |     (for (r1 <- rs; r2 <- rs) yield ALT(r1, r2)) ++
 | 
|  |    135 |     (for (r1 <- rs; r2 <- rs) yield SEQ(r1, r2)) ++
 | 
|  |    136 |     (for (r1 <- rs) yield STAR(r1))
 | 
|  |    137 | }
 | 
|  |    138 | 
 | 
| 240 |    139 | enuml(1, "a")
 | 
| 238 |    140 | enuml(1, "a").size
 | 
|  |    141 | enuml(2, "a").size
 | 
| 326 |    142 | enuml(3, "a").size // out of heap space
 | 
| 238 |    143 | 
 | 
|  |    144 | 
 | 
| 326 |    145 | 
 | 
|  |    146 | def enum(rs: LazyList[Rexp]) : LazyList[Rexp] = 
 | 
| 238 |    147 |   rs #::: enum( (for (r1 <- rs; r2 <- rs) yield ALT(r1, r2)) #:::
 | 
|  |    148 |                 (for (r1 <- rs; r2 <- rs) yield SEQ(r1, r2)) #:::
 | 
|  |    149 |                 (for (r1 <- rs) yield STAR(r1)) )
 | 
|  |    150 | 
 | 
|  |    151 | 
 | 
| 326 |    152 | enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(200).force
 | 
| 329 |    153 | enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(5_000_000).force
 | 
|  |    154 | 
 | 
|  |    155 | 
 | 
|  |    156 | def depth(r: Rexp) : Int = r match {
 | 
|  |    157 |   case ZERO => 0
 | 
|  |    158 |   case ONE => 0
 | 
|  |    159 |   case CHAR(_) => 0
 | 
|  |    160 |   case ALT(r1, r2) => Math.max(depth(r1), depth(r2)) + 1
 | 
|  |    161 |   case SEQ(r1, r2) => Math.max(depth(r1), depth(r2)) + 1 
 | 
|  |    162 |   case STAR(r1) => depth(r1) + 1
 | 
|  |    163 | }
 | 
| 238 |    164 | 
 | 
|  |    165 | 
 | 
|  |    166 | val is = 
 | 
| 326 |    167 |   (enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b')))
 | 
| 238 |    168 |     .dropWhile(depth(_) < 3)
 | 
|  |    169 |     .take(10).foreach(println))
 | 
|  |    170 | 
 | 
|  |    171 | 
 | 
| 328 |    172 | 
 | 
| 326 |    173 | // (Immutable)
 | 
|  |    174 | // Object Oriented Programming in Scala
 | 
|  |    175 | // =====================================
 | 
| 238 |    176 | 
 | 
| 329 |    177 | 
 | 
|  |    178 | abstract class Animal 
 | 
| 326 |    179 | case class Bird(name: String) extends Animal {
 | 
|  |    180 |    override def toString = name
 | 
|  |    181 | }
 | 
|  |    182 | case class Mammal(name: String) extends Animal
 | 
|  |    183 | case class Reptile(name: String) extends Animal
 | 
|  |    184 | 
 | 
|  |    185 | Mammal("Zebra")
 | 
|  |    186 | println(Mammal("Zebra"))
 | 
|  |    187 | println(Mammal("Zebra").toString)
 | 
|  |    188 | 
 | 
| 238 |    189 | 
 | 
| 326 |    190 | Bird("Sparrow")
 | 
|  |    191 | println(Bird("Sparrow"))
 | 
|  |    192 | println(Bird("Sparrow").toString)
 | 
|  |    193 | 
 | 
| 383 |    194 | Bird("Sparrow").copy(name = "House Sparrow")
 | 
|  |    195 | 
 | 
|  |    196 | def group(a : Animal) = a match {
 | 
|  |    197 |   case Bird(_) => "It's a bird"
 | 
|  |    198 |   case Mammal(_) => "It's a mammal"
 | 
|  |    199 | }
 | 
|  |    200 | 
 | 
| 326 |    201 | 
 | 
|  |    202 | // There is a very convenient short-hand notation
 | 
|  |    203 | // for constructors:
 | 
|  |    204 | 
 | 
|  |    205 | class Fraction(x: Int, y: Int) {
 | 
|  |    206 |   def numer = x
 | 
|  |    207 |   def denom = y
 | 
| 238 |    208 | }
 | 
|  |    209 | 
 | 
| 326 |    210 | val half = new Fraction(1, 2)
 | 
| 383 |    211 | half.numer
 | 
| 326 |    212 | 
 | 
|  |    213 | case class Fraction(numer: Int, denom: Int)
 | 
|  |    214 | 
 | 
|  |    215 | val half = Fraction(1, 2)
 | 
|  |    216 | 
 | 
| 383 |    217 | half.numer
 | 
| 326 |    218 | half.denom
 | 
|  |    219 | 
 | 
|  |    220 | 
 | 
|  |    221 | // In mandelbrot.scala I used complex (imaginary) numbers 
 | 
|  |    222 | // and implemented the usual arithmetic operations for complex 
 | 
|  |    223 | // numbers.
 | 
|  |    224 | 
 | 
|  |    225 | case class Complex(re: Double, im: Double) { 
 | 
|  |    226 |   // represents the complex number re + im * i
 | 
|  |    227 |   def +(that: Complex) = Complex(this.re + that.re, this.im + that.im)
 | 
|  |    228 |   def -(that: Complex) = Complex(this.re - that.re, this.im - that.im)
 | 
|  |    229 |   def *(that: Complex) = Complex(this.re * that.re - this.im * that.im,
 | 
|  |    230 |                                  this.re * that.im + that.re * this.im)
 | 
|  |    231 |   def *(that: Double) = Complex(this.re * that, this.im * that)
 | 
|  |    232 |   def abs = Math.sqrt(this.re * this.re + this.im * this.im)
 | 
|  |    233 | }
 | 
|  |    234 | 
 | 
|  |    235 | val test = Complex(1, 2) + Complex (3, 4)
 | 
|  |    236 | 
 | 
| 383 |    237 | import scala.language.postfixOps
 | 
|  |    238 | List(5,4,3,2,1).sorted.reverse
 | 
|  |    239 | 
 | 
| 326 |    240 | // this could have equally been written as
 | 
|  |    241 | val test = Complex(1, 2).+(Complex (3, 4))
 | 
|  |    242 | 
 | 
|  |    243 | // this applies to all methods, but requires
 | 
|  |    244 | import scala.language.postfixOps
 | 
|  |    245 | 
 | 
|  |    246 | List(5, 2, 3, 4).sorted
 | 
|  |    247 | List(5, 2, 3, 4) sorted
 | 
|  |    248 | 
 | 
|  |    249 | 
 | 
|  |    250 | // ...to allow the notation n + m * i
 | 
|  |    251 | import scala.language.implicitConversions   
 | 
|  |    252 | 
 | 
|  |    253 | val i = Complex(0, 1)
 | 
|  |    254 | implicit def double2complex(re: Double) = Complex(re, 0)
 | 
|  |    255 | 
 | 
| 238 |    256 | 
 | 
| 326 |    257 | val inum1 = -2.0 + -1.5 * i
 | 
|  |    258 | val inum2 =  1.0 +  1.5 * i
 | 
|  |    259 | 
 | 
|  |    260 | 
 | 
|  |    261 | 
 | 
|  |    262 | // All is public by default....so no public is needed.
 | 
|  |    263 | // You can have the usual restrictions about private 
 | 
|  |    264 | // values and methods, if you are MUTABLE !!!
 | 
|  |    265 | 
 | 
|  |    266 | case class BankAccount(init: Int) {
 | 
|  |    267 | 
 | 
|  |    268 |   private var balance = init
 | 
|  |    269 | 
 | 
|  |    270 |   def deposit(amount: Int): Unit = {
 | 
|  |    271 |     if (amount > 0) balance = balance + amount
 | 
|  |    272 |   }
 | 
| 238 |    273 | 
 | 
| 326 |    274 |   def withdraw(amount: Int): Int =
 | 
|  |    275 |     if (0 < amount && amount <= balance) {
 | 
|  |    276 |       balance = balance - amount
 | 
|  |    277 |       balance
 | 
|  |    278 |     } else throw new Error("insufficient funds")
 | 
| 238 |    279 | }
 | 
|  |    280 | 
 | 
| 326 |    281 | // BUT since we are completely IMMUTABLE, this is 
 | 
| 383 |    282 | // virtually of no concern to us.
 | 
| 326 |    283 | 
 | 
|  |    284 | 
 | 
|  |    285 | 
 | 
|  |    286 | // another example about Fractions
 | 
|  |    287 | import scala.language.implicitConversions
 | 
|  |    288 | import scala.language.reflectiveCalls
 | 
|  |    289 | 
 | 
|  |    290 | case class Fraction(numer: Int, denom: Int) {
 | 
|  |    291 |   override def toString = numer.toString + "/" + denom.toString
 | 
|  |    292 | 
 | 
| 383 |    293 |   def +(other: Fraction) = 
 | 
|  |    294 |     Fraction(numer * other.denom + other.numer * denom, 
 | 
|  |    295 |              denom * other.denom)
 | 
|  |    296 |   def *(other: Fraction) = Fraction(numer * other.numer, denom * other.denom)
 | 
| 326 |    297 |  }
 | 
|  |    298 | 
 | 
|  |    299 | implicit def Int2Fraction(x: Int) = Fraction(x, 1)
 | 
|  |    300 | 
 | 
|  |    301 | val half = Fraction(1, 2)
 | 
|  |    302 | val third = Fraction (1, 3)
 | 
|  |    303 | 
 | 
|  |    304 | half + third
 | 
| 383 |    305 | half * third
 | 
| 326 |    306 | 
 | 
| 383 |    307 | 1 + half
 | 
|  |    308 | 
 | 
|  |    309 | 
 | 
| 326 |    310 | 
 | 
|  |    311 | 
 | 
|  |    312 | // DFAs in Scala  
 | 
|  |    313 | //===============
 | 
|  |    314 | import scala.util.Try
 | 
| 238 |    315 | 
 | 
| 326 |    316 | 
 | 
|  |    317 | // A is the state type
 | 
|  |    318 | // C is the input (usually characters)
 | 
|  |    319 | 
 | 
|  |    320 | case class DFA[A, C](start: A,              // starting state
 | 
|  |    321 |                      delta: (A, C) => A,    // transition function
 | 
|  |    322 |                      fins:  A => Boolean) { // final states (Set)
 | 
|  |    323 | 
 | 
|  |    324 |   def deltas(q: A, s: List[C]) : A = s match {
 | 
|  |    325 |     case Nil => q
 | 
|  |    326 |     case c::cs => deltas(delta(q, c), cs)
 | 
|  |    327 |   }
 | 
|  |    328 | 
 | 
|  |    329 |   def accepts(s: List[C]) : Boolean = 
 | 
| 383 |    330 |     Try(fins(deltas(start, s))).getOrElse(false)
 | 
| 238 |    331 | }
 | 
|  |    332 | 
 | 
| 326 |    333 | // the example shown in the handout 
 | 
|  |    334 | abstract class State
 | 
|  |    335 | case object Q0 extends State
 | 
|  |    336 | case object Q1 extends State
 | 
|  |    337 | case object Q2 extends State
 | 
|  |    338 | case object Q3 extends State
 | 
|  |    339 | case object Q4 extends State
 | 
| 238 |    340 | 
 | 
| 326 |    341 | val delta : (State, Char) => State = 
 | 
|  |    342 |   { case (Q0, 'a') => Q1
 | 
|  |    343 |     case (Q0, 'b') => Q2
 | 
|  |    344 |     case (Q1, 'a') => Q4
 | 
|  |    345 |     case (Q1, 'b') => Q2
 | 
|  |    346 |     case (Q2, 'a') => Q3
 | 
|  |    347 |     case (Q2, 'b') => Q2
 | 
|  |    348 |     case (Q3, 'a') => Q4
 | 
|  |    349 |     case (Q3, 'b') => Q0
 | 
|  |    350 |     case (Q4, 'a') => Q4
 | 
|  |    351 |     case (Q4, 'b') => Q4 
 | 
|  |    352 |     case _ => throw new Exception("Undefined") }
 | 
|  |    353 | 
 | 
|  |    354 | val dfa = DFA(Q0, delta, Set[State](Q4))
 | 
|  |    355 | 
 | 
|  |    356 | dfa.accepts("abaaa".toList)     // true
 | 
|  |    357 | dfa.accepts("bbabaab".toList)   // true
 | 
|  |    358 | dfa.accepts("baba".toList)      // false
 | 
|  |    359 | dfa.accepts("abc".toList)       // false
 | 
|  |    360 | 
 | 
| 238 |    361 | 
 | 
| 326 |    362 | // NFAs (Nondeterministic Finite Automata)
 | 
|  |    363 | 
 | 
|  |    364 | 
 | 
|  |    365 | case class NFA[A, C](starts: Set[A],          // starting states
 | 
|  |    366 |                      delta: (A, C) => Set[A], // transition function
 | 
|  |    367 |                      fins:  A => Boolean) {   // final states 
 | 
|  |    368 | 
 | 
|  |    369 |   // given a state and a character, what is the set of 
 | 
|  |    370 |   // next states? if there is none => empty set
 | 
|  |    371 |   def next(q: A, c: C) : Set[A] = 
 | 
| 383 |    372 |     Try(delta(q, c)).getOrElse(Set[A]()) 
 | 
| 326 |    373 | 
 | 
|  |    374 |   def nexts(qs: Set[A], c: C) : Set[A] =
 | 
|  |    375 |     qs.flatMap(next(_, c))
 | 
|  |    376 | 
 | 
|  |    377 |   // depth-first version of accepts
 | 
|  |    378 |   def search(q: A, s: List[C]) : Boolean = s match {
 | 
|  |    379 |     case Nil => fins(q)
 | 
|  |    380 |     case c::cs => next(q, c).exists(search(_, cs))
 | 
|  |    381 |   }
 | 
|  |    382 | 
 | 
|  |    383 |   def accepts(s: List[C]) : Boolean =
 | 
|  |    384 |     starts.exists(search(_, s))
 | 
| 238 |    385 | }
 | 
|  |    386 | 
 | 
|  |    387 | 
 | 
| 326 |    388 | 
 | 
|  |    389 | // NFA examples
 | 
|  |    390 | 
 | 
|  |    391 | val nfa_trans1 : (State, Char) => Set[State] = 
 | 
|  |    392 |   { case (Q0, 'a') => Set(Q0, Q1) 
 | 
|  |    393 |     case (Q0, 'b') => Set(Q2) 
 | 
|  |    394 |     case (Q1, 'a') => Set(Q1) 
 | 
|  |    395 |     case (Q2, 'b') => Set(Q2) }
 | 
| 238 |    396 | 
 | 
| 326 |    397 | val nfa = NFA(Set[State](Q0), nfa_trans1, Set[State](Q2))
 | 
| 238 |    398 | 
 | 
| 326 |    399 | nfa.accepts("aa".toList)             // false
 | 
|  |    400 | nfa.accepts("aaaaa".toList)          // false
 | 
|  |    401 | nfa.accepts("aaaaab".toList)         // true
 | 
|  |    402 | nfa.accepts("aaaaabbb".toList)       // true
 | 
|  |    403 | nfa.accepts("aaaaabbbaaa".toList)    // false
 | 
|  |    404 | nfa.accepts("ac".toList)             // false
 | 
| 222 |    405 | 
 | 
| 238 |    406 | 
 | 
| 326 |    407 | // Q: Why the kerfuffle about the polymorphic types in DFAs/NFAs?
 | 
|  |    408 | // A: Subset construction. Here the state type for the DFA is
 | 
|  |    409 | //    sets of states.
 | 
| 238 |    410 | 
 | 
| 383 |    411 | 
 | 
| 326 |    412 | def subset[A, C](nfa: NFA[A, C]) : DFA[Set[A], C] = {
 | 
|  |    413 |   DFA(nfa.starts, 
 | 
|  |    414 |       { case (qs, c) => nfa.nexts(qs, c) }, 
 | 
|  |    415 |       _.exists(nfa.fins))
 | 
| 238 |    416 | }
 | 
|  |    417 | 
 | 
| 326 |    418 | subset(nfa).accepts("aa".toList)             // false
 | 
|  |    419 | subset(nfa).accepts("aaaaa".toList)          // false
 | 
|  |    420 | subset(nfa).accepts("aaaaab".toList)         // true
 | 
|  |    421 | subset(nfa).accepts("aaaaabbb".toList)       // true
 | 
|  |    422 | subset(nfa).accepts("aaaaabbbaaa".toList)    // false
 | 
|  |    423 | subset(nfa).accepts("ac".toList)             // false
 | 
| 238 |    424 | 
 | 
|  |    425 | 
 | 
| 222 |    426 | 
 | 
| 240 |    427 | // The End ... Almost Christmas
 | 
| 238 |    428 | //===============================
 | 
|  |    429 | 
 | 
|  |    430 | // I hope you had fun!
 | 
|  |    431 | 
 | 
|  |    432 | // A function should do one thing, and only one thing.
 | 
|  |    433 | 
 | 
|  |    434 | // Make your variables immutable, unless there's a good 
 | 
| 326 |    435 | // reason not to. Usually there is not.
 | 
| 238 |    436 | 
 | 
| 326 |    437 | // I did it once, but this is actually not a good reason:
 | 
| 240 |    438 | // generating new labels:
 | 
|  |    439 | 
 | 
| 238 |    440 | var counter = -1
 | 
| 222 |    441 | 
 | 
| 238 |    442 | def Fresh(x: String) = {
 | 
|  |    443 |   counter += 1
 | 
|  |    444 |   x ++ "_" ++ counter.toString()
 | 
|  |    445 | }
 | 
|  |    446 | 
 | 
|  |    447 | Fresh("x")
 | 
|  |    448 | Fresh("x")
 | 
|  |    449 | 
 | 
|  |    450 | 
 | 
|  |    451 | 
 | 
| 326 |    452 | // I think you can be productive on Day 1, but the 
 | 
|  |    453 | // language is deep.
 | 
| 238 |    454 | //
 | 
|  |    455 | // http://scalapuzzlers.com
 | 
|  |    456 | //
 | 
|  |    457 | // http://www.latkin.org/blog/2017/05/02/when-the-scala-compiler-doesnt-help/
 | 
|  |    458 | 
 | 
| 328 |    459 | val two   = 0.2
 | 
|  |    460 | val one   = 0.1
 | 
|  |    461 | val eight = 0.8
 | 
|  |    462 | val six   = 0.6
 | 
|  |    463 | 
 | 
|  |    464 | two - one == one
 | 
|  |    465 | eight - six == two
 | 
| 329 |    466 | eight - six
 | 
| 328 |    467 | 
 | 
|  |    468 | 
 | 
| 329 |    469 | // problems about equality and type-errors
 | 
| 328 |    470 | 
 | 
| 329 |    471 | List(1, 2, 3).contains("your cup")   // should not compile, but retruns false
 | 
|  |    472 | 
 | 
|  |    473 | List(1, 2, 3) == Vector(1, 2, 3)     // again should not compile, but returns true
 | 
| 326 |    474 | 
 | 
| 238 |    475 | 
 | 
|  |    476 | // I like best about Scala that it lets me often write
 | 
|  |    477 | // concise, readable code. And it hooks up with the 
 | 
| 326 |    478 | // Isabelle theorem prover. 
 | 
|  |    479 | 
 | 
|  |    480 | 
 | 
|  |    481 | // Puzzlers
 | 
|  |    482 | 
 | 
| 329 |    483 | val month = 12
 | 
|  |    484 | val day = 24
 | 
|  |    485 | val (hour, min, sec) = (12, 0, 0)
 | 
| 326 |    486 | 
 | 
|  |    487 | // use lowercase names for variable 
 | 
|  |    488 | 
 | 
|  |    489 | 
 | 
|  |    490 | //==================
 | 
|  |    491 | val oneTwo = Seq(1, 2, 3).permutations
 | 
|  |    492 | 
 | 
|  |    493 | if (oneTwo.length > 0) {
 | 
| 329 |    494 |   println("Permutations of 1,2 and 3:")
 | 
| 326 |    495 |   oneTwo.foreach(println)
 | 
|  |    496 | }
 | 
|  |    497 | 
 | 
|  |    498 | val threeFour = Seq(3, 4, 5).permutations
 | 
|  |    499 | 
 | 
|  |    500 | if (!threeFour.isEmpty) {
 | 
| 329 |    501 |   println("Permutations of 3, 4 and 5:")
 | 
| 326 |    502 |   threeFour.foreach(println)
 | 
|  |    503 | }
 | 
| 238 |    504 | 
 | 
| 326 |    505 | //==================
 | 
|  |    506 | val (a, b, c) =
 | 
|  |    507 |     if (4 < 5) {
 | 
|  |    508 |         "bar"
 | 
|  |    509 |     } else { 
 | 
|  |    510 |         Some(10)
 | 
|  |    511 |     }
 | 
|  |    512 | 
 | 
|  |    513 | //Because when an expression has multiple return branches, Scala tries to
 | 
|  |    514 | //be helpful, by picking the first common ancestor type of all the
 | 
|  |    515 | //branches as the type of the whole expression.
 | 
|  |    516 | //
 | 
|  |    517 | //In this case, one branch has type String and the other has type
 | 
|  |    518 | //Option[Int], so the compiler decides that what the developer really
 | 
|  |    519 | //wants is for the whole if/else expression to have type Serializable,
 | 
|  |    520 | //since that’s the most specific type to claim both String and Option as
 | 
|  |    521 | //descendants.
 | 
|  |    522 | //
 | 
|  |    523 | //And guess what, Tuple3[A, B, C] is also Serializable, so as far as the
 | 
|  |    524 | //compiler is concerned, the assignment of the whole mess to (a, b, c)
 | 
|  |    525 | //can’t be proven invalid. So it gets through with a warning,
 | 
|  |    526 | //destined to fail at runtime.
 | 
|  |    527 | 
 | 
|  |    528 | 
 | 
|  |    529 | //================
 | 
|  |    530 | // does not work anymore in 2.13.0
 | 
| 329 |    531 | val numbers = List("1", "2").toSet + "3"
 |