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