| 
222
 | 
     1  | 
// Scala Lecture 4
  | 
| 
 | 
     2  | 
//=================
  | 
| 
 | 
     3  | 
  | 
| 
 | 
     4  | 
  | 
| 
325
 | 
     5  | 
// expressions (essentially trees)
  | 
| 
 | 
     6  | 
  | 
| 
 | 
     7  | 
abstract class Exp
  | 
| 
 | 
     8  | 
case class N(n: Int) extends Exp                  // for numbers
  | 
| 
 | 
     9  | 
case class Plus(e1: Exp, e2: Exp) extends Exp
  | 
| 
 | 
    10  | 
case class Times(e1: Exp, e2: Exp) extends Exp
  | 
| 
 | 
    11  | 
  | 
| 
 | 
    12  | 
def string(e: Exp) : String = e match {
 | 
| 
 | 
    13  | 
  case N(n) => s"$n"
  | 
| 
 | 
    14  | 
  case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})" 
 | 
| 
 | 
    15  | 
  case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})"
 | 
| 
 | 
    16  | 
}
  | 
| 
 | 
    17  | 
  | 
| 
 | 
    18  | 
val e = Plus(N(9), Times(N(3), N(4)))
  | 
| 
 | 
    19  | 
println(string(e))
  | 
| 
 | 
    20  | 
  | 
| 
 | 
    21  | 
def eval(e: Exp) : Int = e match {
 | 
| 
 | 
    22  | 
  case N(n) => n
  | 
| 
 | 
    23  | 
  case Plus(e1, e2) => eval(e1) + eval(e2) 
  | 
| 
 | 
    24  | 
  case Times(e1, e2) => eval(e1) * eval(e2) 
  | 
| 
 | 
    25  | 
}
  | 
| 
 | 
    26  | 
  | 
| 
 | 
    27  | 
println(eval(e))
  | 
| 
 | 
    28  | 
  | 
| 
 | 
    29  | 
// simplification rules:
  | 
| 
 | 
    30  | 
// e + 0, 0 + e => e 
  | 
| 
 | 
    31  | 
// e * 0, 0 * e => 0
  | 
| 
 | 
    32  | 
// e * 1, 1 * e => e
  | 
| 
326
 | 
    33  | 
//
  | 
| 
 | 
    34  | 
// (....0  ....)
  | 
| 
325
 | 
    35  | 
  | 
| 
 | 
    36  | 
def simp(e: Exp) : Exp = e match {
 | 
| 
 | 
    37  | 
  case N(n) => N(n)
  | 
| 
 | 
    38  | 
  case Plus(e1, e2) => (simp(e1), simp(e2)) match {
 | 
| 
 | 
    39  | 
    case (N(0), e2s) => e2s
  | 
| 
 | 
    40  | 
    case (e1s, N(0)) => e1s
  | 
| 
 | 
    41  | 
    case (e1s, e2s) => Plus(e1s, e2s)
  | 
| 
 | 
    42  | 
  }  
  | 
| 
 | 
    43  | 
  case Times(e1, e2) => (simp(e1), simp(e2)) match {
 | 
| 
 | 
    44  | 
    case (N(0), _) => N(0)
  | 
| 
 | 
    45  | 
    case (_, N(0)) => N(0)
  | 
| 
 | 
    46  | 
    case (N(1), e2s) => e2s
  | 
| 
 | 
    47  | 
    case (e1s, N(1)) => e1s
  | 
| 
 | 
    48  | 
    case (e1s, e2s) => Times(e1s, e2s)
  | 
| 
 | 
    49  | 
  }  
  | 
| 
 | 
    50  | 
}
  | 
| 
 | 
    51  | 
  | 
| 
 | 
    52  | 
  | 
| 
 | 
    53  | 
val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9)))
  | 
| 
 | 
    54  | 
println(string(e2))
  | 
| 
 | 
    55  | 
println(string(simp(e2)))
  | 
| 
 | 
    56  | 
  | 
| 
 | 
    57  | 
  | 
| 
 | 
    58  | 
// Tokens and Reverse Polish Notation
  | 
| 
 | 
    59  | 
abstract class Token
  | 
| 
 | 
    60  | 
case class T(n: Int) extends Token
  | 
| 
 | 
    61  | 
case object PL extends Token
  | 
| 
 | 
    62  | 
case object TI extends Token
  | 
| 
 | 
    63  | 
  | 
| 
 | 
    64  | 
// transfroming an Exp into a list of tokens
  | 
| 
 | 
    65  | 
def rp(e: Exp) : List[Token] = e match {
 | 
| 
 | 
    66  | 
  case N(n) => List(T(n))
  | 
| 
 | 
    67  | 
  case Plus(e1, e2) => rp(e1) ::: rp(e2) ::: List(PL) 
  | 
| 
 | 
    68  | 
  case Times(e1, e2) => rp(e1) ::: rp(e2) ::: List(TI) 
  | 
| 
 | 
    69  | 
}
  | 
| 
 | 
    70  | 
println(string(e2))
  | 
| 
 | 
    71  | 
println(rp(e2))
  | 
| 
 | 
    72  | 
  | 
| 
326
 | 
    73  | 
def comp(ls: List[Token], st: List[Int] = Nil) : Int = (ls, st) match {
 | 
| 
325
 | 
    74  | 
  case (Nil, st) => st.head 
  | 
| 
 | 
    75  | 
  case (T(n)::rest, st) => comp(rest, n::st)
  | 
| 
 | 
    76  | 
  case (PL::rest, n1::n2::st) => comp(rest, n1 + n2::st)
  | 
| 
 | 
    77  | 
  case (TI::rest, n1::n2::st) => comp(rest, n1 * n2::st)
  | 
| 
 | 
    78  | 
}
  | 
| 
 | 
    79  | 
  | 
| 
326
 | 
    80  | 
comp(rp(e))
  | 
| 
325
 | 
    81  | 
  | 
| 
 | 
    82  | 
def proc(s: String) : Token = s match {
 | 
| 
 | 
    83  | 
  case  "+" => PL
  | 
| 
 | 
    84  | 
  case  "*" => TI
  | 
| 
 | 
    85  | 
  case  _ => T(s.toInt) 
  | 
| 
 | 
    86  | 
}
  | 
| 
 | 
    87  | 
  | 
| 
 | 
    88  | 
comp("1 2 + 4 * 5 + 3 +".split(" ").toList.map(proc), Nil)
 | 
| 
 | 
    89  | 
  | 
| 
 | 
    90  | 
  | 
| 
380
 | 
    91  | 
// Polymorphic Types
  | 
| 
 | 
    92  | 
//===================
  | 
| 
 | 
    93  | 
  | 
| 
 | 
    94  | 
// You do not want to write functions like contains, first, 
  | 
| 
 | 
    95  | 
// length and so on for every type of lists.
  | 
| 
 | 
    96  | 
  | 
| 
 | 
    97  | 
def length_int_list(lst: List[Int]): Int = lst match {
 | 
| 
 | 
    98  | 
  case Nil => 0
  | 
| 
 | 
    99  | 
  case x::xs => 1 + length_int_list(xs)
  | 
| 
 | 
   100  | 
}
  | 
| 
 | 
   101  | 
  | 
| 
 | 
   102  | 
length_int_list(List(1, 2, 3, 4))
  | 
| 
 | 
   103  | 
  | 
| 
 | 
   104  | 
def length_string_list(lst: List[String]): Int = lst match {
 | 
| 
 | 
   105  | 
  case Nil => 0
  | 
| 
 | 
   106  | 
  case _::xs => 1 + length_string_list(xs)
  | 
| 
 | 
   107  | 
}
  | 
| 
 | 
   108  | 
  | 
| 
 | 
   109  | 
length_string_list(List("1", "2", "3", "4"))
 | 
| 
 | 
   110  | 
  | 
| 
 | 
   111  | 
  | 
| 
 | 
   112  | 
// you can make the function parametric in type(s)
  | 
| 
 | 
   113  | 
  | 
| 
 | 
   114  | 
def length[A](lst: List[A]): Int = lst match {
 | 
| 
 | 
   115  | 
  case Nil => 0
  | 
| 
 | 
   116  | 
  case x::xs => 1 + length(xs)
  | 
| 
 | 
   117  | 
}
  | 
| 
 | 
   118  | 
length(List("1", "2", "3", "4"))
 | 
| 
 | 
   119  | 
length(List(1, 2, 3, 4))
  | 
| 
 | 
   120  | 
  | 
| 
 | 
   121  | 
length[Int](List(1, 2, 3, 4))
  | 
| 
 | 
   122  | 
  | 
| 
 | 
   123  | 
  | 
| 
 | 
   124  | 
def map[A, B](lst: List[A], f: A => B): List[B] = lst match {
 | 
| 
 | 
   125  | 
  case Nil => Nil
  | 
| 
 | 
   126  | 
  case x::xs => f(x)::map(xs, f) 
  | 
| 
 | 
   127  | 
}
  | 
| 
 | 
   128  | 
  | 
| 
 | 
   129  | 
map(List(1, 2, 3, 4), (x: Int) => x.toString)
  | 
| 
 | 
   130  | 
  | 
| 
 | 
   131  | 
  | 
| 
 | 
   132  | 
// from knight1.scala
  | 
| 
 | 
   133  | 
def first(xs: List[Pos], f: Pos => Option[Path]) : Option[Path] = ???
  | 
| 
 | 
   134  | 
  | 
| 
 | 
   135  | 
// should be
  | 
| 
 | 
   136  | 
def first[A, B](xs: List[A], f: A => Option[B]) : Option[B] = ???
  | 
| 
 | 
   137  | 
  | 
| 
 | 
   138  | 
// Type inference is local in Scala
  | 
| 
 | 
   139  | 
  | 
| 
 | 
   140  | 
def id[T](x: T) : T = x
  | 
| 
 | 
   141  | 
  | 
| 
 | 
   142  | 
val x = id(322)          // Int
  | 
| 
 | 
   143  | 
val y = id("hey")        // String
 | 
| 
 | 
   144  | 
val z = id(Set(1,2,3,4)) // Set[Int]
  | 
| 
 | 
   145  | 
  | 
| 
 | 
   146  | 
  | 
| 
 | 
   147  | 
// The type variable concept in Scala can get really complicated.
  | 
| 
 | 
   148  | 
//
  | 
| 
 | 
   149  | 
// - variance (OO)
  | 
| 
 | 
   150  | 
// - bounds (subtyping)
  | 
| 
 | 
   151  | 
// - quantification
  | 
| 
 | 
   152  | 
  | 
| 
 | 
   153  | 
// Java has issues with this too: Java allows
  | 
| 
 | 
   154  | 
// to write the following incorrect code, and
  | 
| 
 | 
   155  | 
// only recovers by raising an exception
  | 
| 
 | 
   156  | 
// at runtime.
  | 
| 
 | 
   157  | 
  | 
| 
 | 
   158  | 
// Object[] arr = new Integer[10];
  | 
| 
 | 
   159  | 
// arr[0] = "Hello World";
  | 
| 
 | 
   160  | 
  | 
| 
 | 
   161  | 
  | 
| 
 | 
   162  | 
// Scala gives you a compile-time error, which
  | 
| 
 | 
   163  | 
// is much better.
  | 
| 
 | 
   164  | 
  | 
| 
 | 
   165  | 
var arr = Array[Int]()
  | 
| 
 | 
   166  | 
arr(0) = "Hello World"
  | 
| 
 | 
   167  | 
  | 
| 
 | 
   168  | 
  | 
| 
 | 
   169  | 
  | 
| 
 | 
   170  | 
  | 
| 
 | 
   171  | 
// Function definitions again
  | 
| 
 | 
   172  | 
//============================
  | 
| 
 | 
   173  | 
  | 
| 
 | 
   174  | 
// variable arguments
  | 
| 
 | 
   175  | 
  | 
| 
 | 
   176  | 
def printAll(strings: String*) = {
 | 
| 
 | 
   177  | 
  strings.foreach(println)
  | 
| 
 | 
   178  | 
}
  | 
| 
 | 
   179  | 
  | 
| 
 | 
   180  | 
printAll()
  | 
| 
 | 
   181  | 
printAll("foo")
 | 
| 
 | 
   182  | 
printAll("foo", "bar")
 | 
| 
 | 
   183  | 
printAll("foo", "bar", "baz")
 | 
| 
 | 
   184  | 
  | 
| 
 | 
   185  | 
// pass a list to the varargs field
  | 
| 
 | 
   186  | 
val fruits = List("apple", "banana", "cherry")
 | 
| 
 | 
   187  | 
  | 
| 
 | 
   188  | 
printAll(fruits: _*)
  | 
| 
 | 
   189  | 
  | 
| 
 | 
   190  | 
  | 
| 
 | 
   191  | 
// you can also implement your own string interpolations
  | 
| 
 | 
   192  | 
import scala.language.implicitConversions
  | 
| 
 | 
   193  | 
import scala.language.reflectiveCalls
  | 
| 
 | 
   194  | 
  | 
| 
 | 
   195  | 
implicit def sring_inters(sc: StringContext) = new {
 | 
| 
 | 
   196  | 
    def i(args: Any*): String = s"${sc.s(args:_*)}\n"
 | 
| 
 | 
   197  | 
}
  | 
| 
 | 
   198  | 
  | 
| 
 | 
   199  | 
i"add ${3+2} ${3 * 3}" 
 | 
| 
 | 
   200  | 
  | 
| 
 | 
   201  | 
  | 
| 
 | 
   202  | 
// default arguments
  | 
| 
 | 
   203  | 
  | 
| 
 | 
   204  | 
def length[A](xs: List[A]) : Int = xs match {
 | 
| 
 | 
   205  | 
  case Nil => 0
  | 
| 
 | 
   206  | 
  case _ :: tail => 1 + length(tail)
  | 
| 
 | 
   207  | 
}
  | 
| 
 | 
   208  | 
  | 
| 
 | 
   209  | 
def lengthT[A](xs: List[A], acc : Int = 0) : Int = xs match {
 | 
| 
 | 
   210  | 
  case Nil => acc
  | 
| 
 | 
   211  | 
  case _ :: tail => lengthT(tail, 1 + acc)
  | 
| 
 | 
   212  | 
}
  | 
| 
 | 
   213  | 
  | 
| 
 | 
   214  | 
lengthT(List.fill(100000)(1))
  | 
| 
 | 
   215  | 
  | 
| 
 | 
   216  | 
  | 
| 
 | 
   217  | 
def fact(n: BigInt, acc: BigInt = 1): BigInt =
  | 
| 
 | 
   218  | 
  if (n == 0) acc else fact(n - 1, n * acc)
  | 
| 
 | 
   219  | 
  | 
| 
 | 
   220  | 
fact(10)
  | 
| 
 | 
   221  | 
  | 
| 
 | 
   222  | 
  | 
| 
 | 
   223  | 
  | 
| 
 | 
   224  | 
// currying    (Haskell Curry)
  | 
| 
 | 
   225  | 
  | 
| 
 | 
   226  | 
def add(x: Int, y: Int) = x + y
  | 
| 
 | 
   227  | 
  | 
| 
 | 
   228  | 
List(1,2,3,4,5).map(x => add(3, x))
  | 
| 
 | 
   229  | 
  | 
| 
 | 
   230  | 
def add2(x: Int)(y: Int) = x + y
  | 
| 
 | 
   231  | 
  | 
| 
 | 
   232  | 
List(1,2,3,4,5).map(add2(3))
  | 
| 
 | 
   233  | 
  | 
| 
 | 
   234  | 
val a3 : Int => Int = add2(3)
  | 
| 
 | 
   235  | 
  | 
| 
 | 
   236  | 
// currying helps sometimes with type inference
  | 
| 
 | 
   237  | 
  | 
| 
 | 
   238  | 
def find[A](xs: List[A])(pred: A => Boolean): Option[A] = {
 | 
| 
 | 
   239  | 
  xs match {
 | 
| 
 | 
   240  | 
    case Nil => None
  | 
| 
 | 
   241  | 
    case hd :: tl =>
  | 
| 
 | 
   242  | 
      if (pred(hd)) Some(hd) else find(tl)(pred)
  | 
| 
 | 
   243  | 
  }
  | 
| 
 | 
   244  | 
}
  | 
| 
 | 
   245  | 
  | 
| 
 | 
   246  | 
find(List(1, 2, 3))(x => x % 2 == 0)
  | 
| 
 | 
   247  | 
  | 
| 
 | 
   248  | 
// Source.fromURL(url)(encoding)
  | 
| 
 | 
   249  | 
// Source.fromFile(name)(encoding)
  | 
| 
325
 | 
   250  | 
  | 
| 
 | 
   251  | 
  | 
| 
 | 
   252  | 
// Sudoku 
  | 
| 
 | 
   253  | 
//========
  | 
| 
 | 
   254  | 
  | 
| 
 | 
   255  | 
// THE POINT OF THIS CODE IS NOT TO BE SUPER
  | 
| 
 | 
   256  | 
// EFFICIENT AND FAST, just explaining exhaustive
  | 
| 
 | 
   257  | 
// depth-first search
  | 
| 
 | 
   258  | 
  | 
| 
 | 
   259  | 
  | 
| 
 | 
   260  | 
val game0 = """.14.6.3..
  | 
| 
 | 
   261  | 
              |62...4..9
  | 
| 
 | 
   262  | 
              |.8..5.6..
  | 
| 
 | 
   263  | 
              |.6.2....3
  | 
| 
 | 
   264  | 
              |.7..1..5.
  | 
| 
 | 
   265  | 
              |5....9.6.
  | 
| 
 | 
   266  | 
              |..6.2..3.
  | 
| 
 | 
   267  | 
              |1..5...92
  | 
| 
 | 
   268  | 
              |..7.9.41.""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   269  | 
  | 
| 
326
 | 
   270  | 
candidates(game0, (0, 0))
  | 
| 
 | 
   271  | 
  | 
| 
325
 | 
   272  | 
type Pos = (Int, Int)
  | 
| 
 | 
   273  | 
val EmptyValue = '.'
  | 
| 
 | 
   274  | 
val MaxValue = 9
  | 
| 
 | 
   275  | 
  | 
| 
 | 
   276  | 
val allValues = "123456789".toList
  | 
| 
 | 
   277  | 
val indexes = (0 to 8).toList
  | 
| 
 | 
   278  | 
  | 
| 
 | 
   279  | 
  | 
| 
 | 
   280  | 
def empty(game: String) = game.indexOf(EmptyValue)
  | 
| 
 | 
   281  | 
def isDone(game: String) = empty(game) == -1 
  | 
| 
 | 
   282  | 
def emptyPosition(game: String) = 
  | 
| 
 | 
   283  | 
  (empty(game) % MaxValue, empty(game) / MaxValue)
  | 
| 
 | 
   284  | 
  | 
| 
 | 
   285  | 
  | 
| 
 | 
   286  | 
def get_row(game: String, y: Int) = 
  | 
| 
 | 
   287  | 
  indexes.map(col => game(y * MaxValue + col))
  | 
| 
 | 
   288  | 
def get_col(game: String, x: Int) = 
  | 
| 
 | 
   289  | 
  indexes.map(row => game(x + row * MaxValue))
  | 
| 
 | 
   290  | 
  | 
| 
326
 | 
   291  | 
get_row(game0, 0)
  | 
| 
 | 
   292  | 
  | 
| 
325
 | 
   293  | 
def get_box(game: String, pos: Pos): List[Char] = {
 | 
| 
 | 
   294  | 
    def base(p: Int): Int = (p / 3) * 3
  | 
| 
 | 
   295  | 
    val x0 = base(pos._1)
  | 
| 
 | 
   296  | 
    val y0 = base(pos._2)
  | 
| 
 | 
   297  | 
    val ys = (y0 until y0 + 3).toList
  | 
| 
 | 
   298  | 
    (x0 until x0 + 3).toList.flatMap(x => ys.map(y => game(x + y * MaxValue)))
  | 
| 
 | 
   299  | 
}
  | 
| 
 | 
   300  | 
  | 
| 
 | 
   301  | 
//get_row(game0, 0)
  | 
| 
 | 
   302  | 
//get_row(game0, 1)
  | 
| 
 | 
   303  | 
//get_col(game0, 0)
  | 
| 
 | 
   304  | 
//get_box(game0, (3, 1))
  | 
| 
 | 
   305  | 
  | 
| 
 | 
   306  | 
  | 
| 
 | 
   307  | 
// this is not mutable!!
  | 
| 
 | 
   308  | 
def update(game: String, pos: Int, value: Char): String = 
  | 
| 
 | 
   309  | 
  game.updated(pos, value)
  | 
| 
 | 
   310  | 
  | 
| 
 | 
   311  | 
def toAvoid(game: String, pos: Pos): List[Char] = 
  | 
| 
 | 
   312  | 
  (get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos))
  | 
| 
 | 
   313  | 
  | 
| 
 | 
   314  | 
def candidates(game: String, pos: Pos): List[Char] = 
  | 
| 
 | 
   315  | 
  allValues.diff(toAvoid(game, pos))
  | 
| 
 | 
   316  | 
  | 
| 
 | 
   317  | 
//candidates(game0, (0,0))
  | 
| 
 | 
   318  | 
  | 
| 
 | 
   319  | 
def pretty(game: String): String = 
  | 
| 
 | 
   320  | 
  "\n" + (game.sliding(MaxValue, MaxValue).mkString("\n"))
 | 
| 
 | 
   321  | 
  | 
| 
 | 
   322  | 
def search(game: String): List[String] = {
 | 
| 
 | 
   323  | 
  if (isDone(game)) List(game)
  | 
| 
 | 
   324  | 
  else {
 | 
| 
 | 
   325  | 
    val cs = candidates(game, emptyPosition(game))
  | 
| 
 | 
   326  | 
    cs.map(c => search(update(game, empty(game), c))).toList.flatten
  | 
| 
 | 
   327  | 
  }
  | 
| 
 | 
   328  | 
}
  | 
| 
 | 
   329  | 
  | 
| 
326
 | 
   330  | 
List(List("sol1"), List("sol2", "sol3")).flatten
 | 
| 
 | 
   331  | 
  | 
| 
325
 | 
   332  | 
search(game0).map(pretty)
  | 
| 
 | 
   333  | 
  | 
| 
 | 
   334  | 
val game1 = """23.915...
  | 
| 
 | 
   335  | 
              |...2..54.
  | 
| 
 | 
   336  | 
              |6.7......
  | 
| 
 | 
   337  | 
              |..1.....9
  | 
| 
 | 
   338  | 
              |89.5.3.17
  | 
| 
 | 
   339  | 
              |5.....6..
  | 
| 
 | 
   340  | 
              |......9.5
  | 
| 
 | 
   341  | 
              |.16..7...
  | 
| 
 | 
   342  | 
              |...329..1""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   343  | 
  | 
| 
 | 
   344  | 
search(game1).map(pretty)
  | 
| 
 | 
   345  | 
  | 
| 
 | 
   346  | 
// a game that is in the hard category
  | 
| 
 | 
   347  | 
val game2 = """8........
  | 
| 
 | 
   348  | 
              |..36.....
  | 
| 
 | 
   349  | 
              |.7..9.2..
  | 
| 
 | 
   350  | 
              |.5...7...
  | 
| 
 | 
   351  | 
              |....457..
  | 
| 
 | 
   352  | 
              |...1...3.
  | 
| 
 | 
   353  | 
              |..1....68
  | 
| 
 | 
   354  | 
              |..85...1.
  | 
| 
 | 
   355  | 
              |.9....4..""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   356  | 
  | 
| 
 | 
   357  | 
search(game2).map(pretty)
  | 
| 
 | 
   358  | 
  | 
| 
 | 
   359  | 
// game with multiple solutions
  | 
| 
 | 
   360  | 
val game3 = """.8...9743
  | 
| 
 | 
   361  | 
              |.5...8.1.
  | 
| 
 | 
   362  | 
              |.1.......
  | 
| 
 | 
   363  | 
              |8....5...
  | 
| 
 | 
   364  | 
              |...8.4...
  | 
| 
 | 
   365  | 
              |...3....6
  | 
| 
 | 
   366  | 
              |.......7.
  | 
| 
 | 
   367  | 
              |.3.5...8.
  | 
| 
 | 
   368  | 
              |9724...5.""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   369  | 
  | 
| 
 | 
   370  | 
search(game3).map(pretty).foreach(println)
  | 
| 
 | 
   371  | 
  | 
| 
 | 
   372  | 
// for measuring time
  | 
| 
 | 
   373  | 
def time_needed[T](i: Int, code: => T) = {
 | 
| 
 | 
   374  | 
  val start = System.nanoTime()
  | 
| 
 | 
   375  | 
  for (j <- 1 to i) code
  | 
| 
 | 
   376  | 
  val end = System.nanoTime()
  | 
| 
 | 
   377  | 
  s"${(end - start) / 1.0e9} secs"
 | 
| 
 | 
   378  | 
}
  | 
| 
 | 
   379  | 
  | 
| 
 | 
   380  | 
time_needed(1, search(game2))
  | 
| 
 | 
   381  | 
  | 
| 
 | 
   382  | 
  | 
| 
 | 
   383  | 
  | 
| 
 | 
   384  | 
// Tail recursion
  | 
| 
 | 
   385  | 
//================
  | 
| 
 | 
   386  | 
  | 
| 
326
 | 
   387  | 
@tailrec
  | 
| 
 | 
   388  | 
def fact(n: BigInt): BigInt = 
  | 
| 
325
 | 
   389  | 
  if (n == 0) 1 else n * fact(n - 1)
  | 
| 
 | 
   390  | 
  | 
| 
 | 
   391  | 
  | 
| 
326
 | 
   392  | 
fact(10)          
  | 
| 
 | 
   393  | 
fact(1000)        
  | 
| 
 | 
   394  | 
fact(100000)       
  | 
| 
325
 | 
   395  | 
  | 
| 
 | 
   396  | 
def factB(n: BigInt): BigInt = 
  | 
| 
 | 
   397  | 
  if (n == 0) 1 else n * factB(n - 1)
  | 
| 
 | 
   398  | 
  | 
| 
326
 | 
   399  | 
def factT(n: BigInt, acc: BigInt): BigInt =
  | 
| 
 | 
   400  | 
  if (n == 0) acc else factT(n - 1, n * acc)
  | 
| 
 | 
   401  | 
  | 
| 
 | 
   402  | 
  | 
| 
325
 | 
   403  | 
factB(1000)
  | 
| 
 | 
   404  | 
  | 
| 
 | 
   405  | 
  | 
| 
326
 | 
   406  | 
  | 
| 
325
 | 
   407  | 
  | 
| 
 | 
   408  | 
factT(10, 1)
  | 
| 
326
 | 
   409  | 
println(factT(500000, 1))
  | 
| 
 | 
   410  | 
  | 
| 
 | 
   411  | 
  | 
| 
 | 
   412  | 
  | 
| 
 | 
   413  | 
  | 
| 
325
 | 
   414  | 
  | 
| 
 | 
   415  | 
// there is a flag for ensuring a function is tail recursive
  | 
| 
 | 
   416  | 
import scala.annotation.tailrec
  | 
| 
 | 
   417  | 
  | 
| 
 | 
   418  | 
@tailrec
  | 
| 
 | 
   419  | 
def factT(n: BigInt, acc: BigInt): BigInt =
  | 
| 
 | 
   420  | 
  if (n == 0) acc else factT(n - 1, n * acc)
  | 
| 
 | 
   421  | 
  | 
| 
 | 
   422  | 
factT(100000, 1)
  | 
| 
 | 
   423  | 
  | 
| 
 | 
   424  | 
// for tail-recursive functions the Scala compiler
  | 
| 
 | 
   425  | 
// generates loop-like code, which does not need
  | 
| 
 | 
   426  | 
// to allocate stack-space in each recursive
  | 
| 
 | 
   427  | 
// call; Scala can do this only for tail-recursive
  | 
| 
 | 
   428  | 
// functions
  | 
| 
 | 
   429  | 
  | 
| 
 | 
   430  | 
// tail recursive version that searches 
  | 
| 
 | 
   431  | 
// for all Sudoku solutions
  | 
| 
 | 
   432  | 
  | 
| 
326
 | 
   433  | 
@tailrec
  | 
| 
325
 | 
   434  | 
def searchT(games: List[String], sols: List[String]): List[String] = games match {
 | 
| 
 | 
   435  | 
  case Nil => sols
  | 
| 
 | 
   436  | 
  case game::rest => {
 | 
| 
 | 
   437  | 
    if (isDone(game)) searchT(rest, game::sols)
  | 
| 
 | 
   438  | 
    else {
 | 
| 
 | 
   439  | 
      val cs = candidates(game, emptyPosition(game))
  | 
| 
 | 
   440  | 
      searchT(cs.map(c => update(game, empty(game), c)) ::: rest, sols)
  | 
| 
 | 
   441  | 
    }
  | 
| 
 | 
   442  | 
  }
  | 
| 
 | 
   443  | 
}
  | 
| 
 | 
   444  | 
  | 
| 
 | 
   445  | 
searchT(List(game3), List()).map(pretty)
  | 
| 
 | 
   446  | 
  | 
| 
 | 
   447  | 
  | 
| 
 | 
   448  | 
// tail recursive version that searches 
  | 
| 
 | 
   449  | 
// for a single solution
  | 
| 
 | 
   450  | 
  | 
| 
 | 
   451  | 
def search1T(games: List[String]): Option[String] = games match {
 | 
| 
 | 
   452  | 
  case Nil => None
  | 
| 
 | 
   453  | 
  case game::rest => {
 | 
| 
 | 
   454  | 
    if (isDone(game)) Some(game)
  | 
| 
 | 
   455  | 
    else {
 | 
| 
 | 
   456  | 
      val cs = candidates(game, emptyPosition(game))
  | 
| 
 | 
   457  | 
      search1T(cs.map(c => update(game, empty(game), c)) ::: rest)
  | 
| 
 | 
   458  | 
    }
  | 
| 
 | 
   459  | 
  }
  | 
| 
 | 
   460  | 
}
  | 
| 
 | 
   461  | 
  | 
| 
 | 
   462  | 
search1T(List(game3)).map(pretty)
  | 
| 
 | 
   463  | 
time_needed(1, search1T(List(game3)))
  | 
| 
 | 
   464  | 
time_needed(1, search1T(List(game2)))
  | 
| 
 | 
   465  | 
  | 
| 
 | 
   466  | 
// game with multiple solutions
  | 
| 
 | 
   467  | 
val game3 = """.8...9743
  | 
| 
 | 
   468  | 
              |.5...8.1.
  | 
| 
 | 
   469  | 
              |.1.......
  | 
| 
 | 
   470  | 
              |8....5...
  | 
| 
 | 
   471  | 
              |...8.4...
  | 
| 
 | 
   472  | 
              |...3....6
  | 
| 
 | 
   473  | 
              |.......7.
  | 
| 
 | 
   474  | 
              |.3.5...8.
  | 
| 
 | 
   475  | 
              |9724...5.""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   476  | 
  | 
| 
 | 
   477  | 
searchT(List(game3), Nil).map(pretty)
  | 
| 
 | 
   478  | 
search1T(List(game3)).map(pretty)
  | 
| 
 | 
   479  | 
  | 
| 
 | 
   480  | 
// Moral: Whenever a recursive function is resource-critical
  | 
| 
326
 | 
   481  | 
// (i.e. works with a large recursion depth), then you need to
  | 
| 
325
 | 
   482  | 
// write it in tail-recursive fashion.
  | 
| 
 | 
   483  | 
// 
  | 
| 
 | 
   484  | 
// Unfortuantely, Scala because of current limitations in 
  | 
| 
 | 
   485  | 
// the JVM is not as clever as other functional languages. It can 
  | 
| 
 | 
   486  | 
// only optimise "self-tail calls". This excludes the cases of 
  | 
| 
 | 
   487  | 
// multiple functions making tail calls to each other. Well,
  | 
| 
 | 
   488  | 
// nothing is perfect. 
  | 
| 
 | 
   489  | 
  | 
| 
 | 
   490  | 
  | 
| 
 | 
   491  | 
  | 
| 
 | 
   492  | 
  | 
| 
222
 | 
   493  | 
  | 
| 
 | 
   494  | 
  | 
| 
 | 
   495  | 
  | 
| 
325
 | 
   496  | 
// Cool Stuff in Scala
  | 
| 
 | 
   497  | 
//=====================
  | 
| 
 | 
   498  | 
  | 
| 
 | 
   499  | 
  | 
| 
 | 
   500  | 
// Implicits or How to Pimp your Library
  | 
| 
 | 
   501  | 
//======================================
  | 
| 
 | 
   502  | 
//
  | 
| 
 | 
   503  | 
// For example adding your own methods to Strings:
  | 
| 
 | 
   504  | 
// Imagine you want to increment strings, like
  | 
| 
 | 
   505  | 
//
  | 
| 
 | 
   506  | 
//     "HAL".increment
  | 
| 
 | 
   507  | 
//
  | 
| 
 | 
   508  | 
// you can avoid ugly fudges, like a MyString, by
  | 
| 
 | 
   509  | 
// using implicit conversions.
  | 
| 
 | 
   510  | 
  | 
| 
 | 
   511  | 
  | 
| 
 | 
   512  | 
implicit class MyString(s: String) {
 | 
| 
 | 
   513  | 
  def increment = s.map(c => (c + 1).toChar) 
  | 
| 
 | 
   514  | 
}
  | 
| 
 | 
   515  | 
  | 
| 
 | 
   516  | 
"HAL".increment
  | 
| 
 | 
   517  | 
  | 
| 
 | 
   518  | 
  | 
| 
 | 
   519  | 
// Abstract idea:
  | 
| 
 | 
   520  | 
// In that version implicit conversions were used to solve the 
  | 
| 
 | 
   521  | 
// late extension problem; namely, given a class C and a class T, 
  | 
| 
 | 
   522  | 
// how to have C extend T without touching or recompiling C. 
  | 
| 
 | 
   523  | 
// Conversions add a wrapper when a member of T is requested 
  | 
| 
 | 
   524  | 
// from an instance of C.
  | 
| 
 | 
   525  | 
  | 
| 
 | 
   526  | 
//Another example (TimeUnit in 2.13?)
  | 
| 
 | 
   527  | 
  | 
| 
 | 
   528  | 
import scala.concurrent.duration.{TimeUnit,SECONDS,MINUTES}
 | 
| 
 | 
   529  | 
  | 
| 
 | 
   530  | 
case class Duration(time: Long, unit: TimeUnit) {
 | 
| 
 | 
   531  | 
  def +(o: Duration) = 
  | 
| 
 | 
   532  | 
    Duration(time + unit.convert(o.time, o.unit), unit)
  | 
| 
 | 
   533  | 
}
  | 
| 
 | 
   534  | 
  | 
| 
 | 
   535  | 
implicit class Int2Duration(that: Int) {
 | 
| 
 | 
   536  | 
  def seconds = new Duration(that, SECONDS)
  | 
| 
 | 
   537  | 
  def minutes = new Duration(that, MINUTES)
  | 
| 
 | 
   538  | 
}
  | 
| 
 | 
   539  | 
  | 
| 
 | 
   540  | 
5.seconds + 2.minutes   //Duration(125L, SECONDS )
  | 
| 
 | 
   541  | 
2.minutes + 60.seconds
  | 
| 
 | 
   542  | 
  | 
| 
 | 
   543  | 
  | 
| 
 | 
   544  | 
  | 
| 
 | 
   545  | 
  | 
| 
 | 
   546  | 
// Regular expressions - the power of DSLs in Scala
  | 
| 
 | 
   547  | 
//==================================================
  | 
| 
 | 
   548  | 
  | 
| 
 | 
   549  | 
abstract class Rexp
  | 
| 
 | 
   550  | 
case object ZERO extends Rexp                     // nothing
  | 
| 
 | 
   551  | 
case object ONE extends Rexp                      // the empty string
  | 
| 
 | 
   552  | 
case class CHAR(c: Char) extends Rexp             // a character c
  | 
| 
 | 
   553  | 
case class ALT(r1: Rexp, r2: Rexp) extends Rexp   // alternative  r1 + r2
  | 
| 
 | 
   554  | 
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp   // sequence     r1 . r2  
  | 
| 
 | 
   555  | 
case class STAR(r: Rexp) extends Rexp             // star         r*
  | 
| 
 | 
   556  | 
  | 
| 
 | 
   557  | 
  | 
| 
 | 
   558  | 
  | 
| 
 | 
   559  | 
// writing (ab)* in the format above is 
  | 
| 
 | 
   560  | 
// tedious
  | 
| 
 | 
   561  | 
val r0 = STAR(SEQ(CHAR('a'), CHAR('b')))
 | 
| 
 | 
   562  | 
  | 
| 
 | 
   563  | 
  | 
| 
 | 
   564  | 
// some convenience for typing in regular expressions
  | 
| 
 | 
   565  | 
import scala.language.implicitConversions    
  | 
| 
 | 
   566  | 
import scala.language.reflectiveCalls 
  | 
| 
 | 
   567  | 
  | 
| 
 | 
   568  | 
def charlist2rexp(s: List[Char]): Rexp = s match {
 | 
| 
 | 
   569  | 
  case Nil => ONE
  | 
| 
 | 
   570  | 
  case c::Nil => CHAR(c)
  | 
| 
 | 
   571  | 
  case c::s => SEQ(CHAR(c), charlist2rexp(s))
  | 
| 
 | 
   572  | 
}
  | 
| 
326
 | 
   573  | 
  | 
| 
325
 | 
   574  | 
implicit def string2rexp(s: String): Rexp = 
  | 
| 
 | 
   575  | 
  charlist2rexp(s.toList)
  | 
| 
 | 
   576  | 
  | 
| 
326
 | 
   577  | 
"(a|b)"
  | 
| 
325
 | 
   578  | 
  | 
| 
 | 
   579  | 
val r1 = STAR("ab")
 | 
| 
326
 | 
   580  | 
val r2 = (STAR("ab")) | (STAR("ba"))
 | 
| 
325
 | 
   581  | 
val r3 = STAR(SEQ("ab", ALT("a", "b")))
 | 
| 
 | 
   582  | 
  | 
| 
 | 
   583  | 
implicit def RexpOps (r: Rexp) = new {
 | 
| 
 | 
   584  | 
  def | (s: Rexp) = ALT(r, s)
  | 
| 
 | 
   585  | 
  def % = STAR(r)
  | 
| 
 | 
   586  | 
  def ~ (s: Rexp) = SEQ(r, s)
  | 
| 
 | 
   587  | 
}
  | 
| 
 | 
   588  | 
  | 
| 
 | 
   589  | 
implicit def stringOps (s: String) = new {
 | 
| 
 | 
   590  | 
  def | (r: Rexp) = ALT(s, r)
  | 
| 
 | 
   591  | 
  def | (r: String) = ALT(s, r)
  | 
| 
 | 
   592  | 
  def % = STAR(s)
  | 
| 
 | 
   593  | 
  def ~ (r: Rexp) = SEQ(s, r)
  | 
| 
 | 
   594  | 
  def ~ (r: String) = SEQ(s, r)
  | 
| 
 | 
   595  | 
}
  | 
| 
 | 
   596  | 
  | 
| 
 | 
   597  | 
//example regular expressions
  | 
| 
326
 | 
   598  | 
val digit = ("0" | "1" | "2" | "3" | "4" | 
 | 
| 
 | 
   599  | 
              "5" | "6" | "7" | "8" | "9")
  | 
| 
325
 | 
   600  | 
val sign = "+" | "-" | ""
  | 
| 
 | 
   601  | 
val number = sign ~ digit ~ digit.% 
  | 
| 
 | 
   602  | 
  | 
| 
 | 
   603  | 
  | 
| 
 | 
   604  | 
  | 
| 
 | 
   605  | 
// Mind-Blowing Regular Expressions
  | 
| 
 | 
   606  | 
  | 
| 
222
 | 
   607  | 
// same examples using the internal regexes
  | 
| 
 | 
   608  | 
val evil = "(a*)*b"
  | 
| 
 | 
   609  | 
  | 
| 
325
 | 
   610  | 
  | 
| 
 | 
   611  | 
println("a" * 100)
 | 
| 
 | 
   612  | 
  | 
| 
326
 | 
   613  | 
("a" * 10000).matches(evil)
 | 
| 
222
 | 
   614  | 
("a" * 10).matches(evil)
 | 
| 
 | 
   615  | 
("a" * 10000).matches(evil)
 | 
| 
 | 
   616  | 
("a" * 20000).matches(evil)
 | 
| 
226
 | 
   617  | 
("a" * 50000).matches(evil)
 | 
| 
222
 | 
   618  | 
  | 
| 
326
 | 
   619  | 
time_needed(1, ("a" * 50000).matches(evil))
 |