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