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