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