| 
51
 | 
     1  | 
// Scala Lecture 2
  | 
| 
 | 
     2  | 
//=================
  | 
| 
 | 
     3  | 
  | 
| 
 | 
     4  | 
  | 
| 
 | 
     5  | 
// Option type
  | 
| 
 | 
     6  | 
//=============
  | 
| 
53
 | 
     7  | 
  | 
| 
192
 | 
     8  | 
//in Java if something unusually happens, you return null;
  | 
| 
53
 | 
     9  | 
//in Scala you use Option
  | 
| 
 | 
    10  | 
//   - if the value is present, you use Some(value)
  | 
| 
 | 
    11  | 
//   - if no value is present, you use None
  | 
| 
 | 
    12  | 
  | 
| 
 | 
    13  | 
  | 
| 
192
 | 
    14  | 
List(7,2,3,4,5,6).find(_ < 4)
  | 
| 
53
 | 
    15  | 
List(5,6,7,8,9).find(_ < 4)
  | 
| 
 | 
    16  | 
  | 
| 
58
 | 
    17  | 
  | 
| 
192
 | 
    18  | 
// Values in types
  | 
| 
 | 
    19  | 
//
  | 
| 
 | 
    20  | 
// Boolean: 
  | 
| 
 | 
    21  | 
// Int: 
  | 
| 
 | 
    22  | 
// String: 
  | 
| 
 | 
    23  | 
//
  | 
| 
 | 
    24  | 
// Option[String]:
  | 
| 
 | 
    25  | 
//   
  | 
| 
 | 
    26  | 
  | 
| 
58
 | 
    27  | 
  | 
| 
51
 | 
    28  | 
val lst = List(None, Some(1), Some(2), None, Some(3))
  | 
| 
 | 
    29  | 
  | 
| 
 | 
    30  | 
lst.flatten
  | 
| 
53
 | 
    31  | 
  | 
| 
192
 | 
    32  | 
Some(1).get
  | 
| 
51
 | 
    33  | 
  | 
| 
53
 | 
    34  | 
Some(1).isDefined
  | 
| 
 | 
    35  | 
None.isDefined
  | 
| 
 | 
    36  | 
  | 
| 
51
 | 
    37  | 
val ps = List((3, 0), (3, 2), (4, 2), (2, 0), (1, 0), (1, 1))
  | 
| 
 | 
    38  | 
  | 
| 
 | 
    39  | 
for ((x, y) <- ps) yield {
 | 
| 
 | 
    40  | 
  if (y == 0) None else Some(x / y)
  | 
| 
 | 
    41  | 
}
  | 
| 
 | 
    42  | 
  | 
| 
192
 | 
    43  | 
// getOrElse is for setting a default value
  | 
| 
53
 | 
    44  | 
  | 
| 
 | 
    45  | 
val lst = List(None, Some(1), Some(2), None, Some(3))
  | 
| 
57
 | 
    46  | 
for (x <- lst) yield x.getOrElse(0)
  | 
| 
 | 
    47  | 
  | 
| 
 | 
    48  | 
  | 
| 
53
 | 
    49  | 
  | 
| 
 | 
    50  | 
  | 
| 
192
 | 
    51  | 
// error handling with Option (no exceptions)
  | 
| 
57
 | 
    52  | 
//
  | 
| 
 | 
    53  | 
//  Try(something).getOrElse(what_to_do_in_an_exception)
  | 
| 
 | 
    54  | 
//
  | 
| 
53
 | 
    55  | 
import scala.util._
  | 
| 
 | 
    56  | 
import io.Source
  | 
| 
 | 
    57  | 
  | 
| 
192
 | 
    58  | 
Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString
 | 
| 
53
 | 
    59  | 
  | 
| 
192
 | 
    60  | 
Try(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString).getOrElse("")
 | 
| 
53
 | 
    61  | 
  | 
| 
192
 | 
    62  | 
Try(Some(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString)).getOrElse(None)
 | 
| 
53
 | 
    63  | 
  | 
| 
57
 | 
    64  | 
// a function that turns strings into numbers
  | 
| 
192
 | 
    65  | 
Integer.parseInt("12u34")
 | 
| 
53
 | 
    66  | 
  | 
| 
 | 
    67  | 
def get_me_an_int(s: String): Option[Int] = 
  | 
| 
 | 
    68  | 
 Try(Some(Integer.parseInt(s))).getOrElse(None)
  | 
| 
 | 
    69  | 
  | 
| 
 | 
    70  | 
val lst = List("12345", "foo", "5432", "bar", "x21")
 | 
| 
 | 
    71  | 
for (x <- lst) yield get_me_an_int(x)
  | 
| 
 | 
    72  | 
  | 
| 
 | 
    73  | 
// summing all the numbers
  | 
| 
192
 | 
    74  | 
val sum = lst.flatMap(get_me_an_int(_)).sum
  | 
| 
53
 | 
    75  | 
  | 
| 
 | 
    76  | 
  | 
| 
 | 
    77  | 
// This may not look any better than working with null in Java, but to
  | 
| 
 | 
    78  | 
// see the value, you have to put yourself in the shoes of the
  | 
| 
 | 
    79  | 
// consumer of the get_me_an_int function, and imagine you didn't
  | 
| 
 | 
    80  | 
// write that function.
  | 
| 
 | 
    81  | 
//
  | 
| 
 | 
    82  | 
// In Java, if you didn't write this function, you'd have to depend on
  | 
| 
192
 | 
    83  | 
// the Javadoc of the get_me_an_int. If you didn't look at the Javadoc, 
  | 
| 
57
 | 
    84  | 
// you might not know that get_me_an_int could return a null, and your 
  | 
| 
 | 
    85  | 
// code could potentially throw a NullPointerException.
  | 
| 
53
 | 
    86  | 
  | 
| 
 | 
    87  | 
  | 
| 
192
 | 
    88  | 
  | 
| 
58
 | 
    89  | 
// even Scala is not immune to problems like this:
  | 
| 
 | 
    90  | 
  | 
| 
192
 | 
    91  | 
List(5,6,7,8,9).indexOf(7)
  | 
| 
 | 
    92  | 
  | 
| 
 | 
    93  | 
  | 
| 
 | 
    94  | 
  | 
| 
 | 
    95  | 
  | 
| 
 | 
    96  | 
  | 
| 
 | 
    97  | 
// Type abbreviations
  | 
| 
 | 
    98  | 
//====================
  | 
| 
 | 
    99  | 
  | 
| 
 | 
   100  | 
// some syntactic convenience
  | 
| 
 | 
   101  | 
type Pos = (int, Int)
  | 
| 
 | 
   102  | 
  | 
| 
 | 
   103  | 
type Board = List[List[Int]]
  | 
| 
 | 
   104  | 
  | 
| 
 | 
   105  | 
  | 
| 
 | 
   106  | 
  | 
| 
 | 
   107  | 
// Implicits
  | 
| 
 | 
   108  | 
//===========
  | 
| 
 | 
   109  | 
//
  | 
| 
 | 
   110  | 
// for example adding your own methods to Strings:
  | 
| 
 | 
   111  | 
// imagine you want to increment strings, like
  | 
| 
 | 
   112  | 
//
  | 
| 
 | 
   113  | 
//     "HAL".increment
  | 
| 
 | 
   114  | 
//
  | 
| 
 | 
   115  | 
// you can avoid ugly fudges, like a MyString, by
  | 
| 
 | 
   116  | 
// using implicit conversions
  | 
| 
 | 
   117  | 
  | 
| 
 | 
   118  | 
  | 
| 
 | 
   119  | 
implicit class MyString(s: String) {
 | 
| 
 | 
   120  | 
  def increment = for (c <- s) yield (c + 1).toChar 
  | 
| 
 | 
   121  | 
}
  | 
| 
 | 
   122  | 
  | 
| 
 | 
   123  | 
"HAL".increment
  | 
| 
58
 | 
   124  | 
  | 
| 
 | 
   125  | 
  | 
| 
192
 | 
   126  | 
// No return in Scala
  | 
| 
 | 
   127  | 
//====================
  | 
| 
 | 
   128  | 
  | 
| 
 | 
   129  | 
//You should not use "return" in Scala:
  | 
| 
 | 
   130  | 
//
  | 
| 
 | 
   131  | 
// A return expression, when evaluated, abandons the 
  | 
| 
 | 
   132  | 
// current computation and returns to the caller of the 
  | 
| 
 | 
   133  | 
// function in which return appears."
  | 
| 
 | 
   134  | 
  | 
| 
 | 
   135  | 
def sq1(x: Int): Int = x * x
  | 
| 
 | 
   136  | 
def sq2(x: Int): Int = return x * x
  | 
| 
 | 
   137  | 
  | 
| 
 | 
   138  | 
def sumq(ls: List[Int]): Int = {
 | 
| 
 | 
   139  | 
  (for (x <- ls) yield (return x * x)).sum[Int]
  | 
| 
 | 
   140  | 
}
  | 
| 
 | 
   141  | 
  | 
| 
 | 
   142  | 
sumq(List(1,2,3,4))
  | 
| 
 | 
   143  | 
  | 
| 
 | 
   144  | 
  | 
| 
 | 
   145  | 
// last expression in a function is the return statement
  | 
| 
 | 
   146  | 
def square(x: Int): Int = {
 | 
| 
 | 
   147  | 
  println(s"The argument is ${x}.")
 | 
| 
 | 
   148  | 
  x * x
  | 
| 
 | 
   149  | 
}
  | 
| 
 | 
   150  | 
  | 
| 
 | 
   151  | 
  | 
| 
 | 
   152  | 
  | 
| 
 | 
   153  | 
// Pattern Matching
  | 
| 
 | 
   154  | 
//==================
  | 
| 
 | 
   155  | 
  | 
| 
 | 
   156  | 
// A powerful tool which is supposed to come to Java in a few years
  | 
| 
 | 
   157  | 
// time (https://www.youtube.com/watch?v=oGll155-vuQ)...Scala already
  | 
| 
 | 
   158  | 
// has it for many years ;o)
  | 
| 
 | 
   159  | 
  | 
| 
 | 
   160  | 
// The general schema:
  | 
| 
 | 
   161  | 
//
  | 
| 
 | 
   162  | 
//    expression match {
 | 
| 
 | 
   163  | 
//       case pattern1 => expression1
  | 
| 
 | 
   164  | 
//       case pattern2 => expression2
  | 
| 
 | 
   165  | 
//       ...
  | 
| 
 | 
   166  | 
//       case patternN => expressionN
  | 
| 
 | 
   167  | 
//    }
  | 
| 
 | 
   168  | 
  | 
| 
 | 
   169  | 
  | 
| 
 | 
   170  | 
  | 
| 
 | 
   171  | 
  | 
| 
 | 
   172  | 
// remember
  | 
| 
 | 
   173  | 
val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
  | 
| 
 | 
   174  | 
  | 
| 
 | 
   175  | 
  | 
| 
 | 
   176  | 
def my_flatten(xs: List[Option[Int]]): List[Int] = {
 | 
| 
 | 
   177  | 
  ...
  | 
| 
 | 
   178  | 
}
  | 
| 
 | 
   179  | 
  | 
| 
 | 
   180  | 
  | 
| 
 | 
   181  | 
def my_flatten(lst: List[Option[Int]]): List[Int] = lst match {
 | 
| 
 | 
   182  | 
  case Nil => Nil
  | 
| 
 | 
   183  | 
  case None::xs => my_flatten(xs)
  | 
| 
 | 
   184  | 
  case Some(n)::xs => n::my_flatten(xs)
  | 
| 
 | 
   185  | 
}
  | 
| 
58
 | 
   186  | 
  | 
| 
 | 
   187  | 
  | 
| 
192
 | 
   188  | 
// another example
  | 
| 
 | 
   189  | 
def get_me_a_string(n: Int): String = n match {
 | 
| 
 | 
   190  | 
  case 0 => "zero"
  | 
| 
 | 
   191  | 
  case 1 => "one"
  | 
| 
 | 
   192  | 
  case 2 => "two"
  | 
| 
 | 
   193  | 
  case _ => "many"
  | 
| 
 | 
   194  | 
}
  | 
| 
 | 
   195  | 
  | 
| 
 | 
   196  | 
get_me_a_string(0)
  | 
| 
 | 
   197  | 
  | 
| 
 | 
   198  | 
// you can also have cases combined
  | 
| 
 | 
   199  | 
def season(month: String) = month match {
 | 
| 
 | 
   200  | 
  case "March" | "April" | "May" => "It's spring"
  | 
| 
 | 
   201  | 
  case "June" | "July" | "August" => "It's summer"
  | 
| 
 | 
   202  | 
  case "September" | "October" | "November" => "It's autumn"
  | 
| 
 | 
   203  | 
  case "December" | "January" | "February" => "It's winter"
  | 
| 
 | 
   204  | 
}
  | 
| 
 | 
   205  | 
 
  | 
| 
 | 
   206  | 
println(season("November"))
 | 
| 
 | 
   207  | 
  | 
| 
 | 
   208  | 
// What happens if no case matches?
  | 
| 
 | 
   209  | 
  | 
| 
 | 
   210  | 
println(season("foobar"))
 | 
| 
 | 
   211  | 
  | 
| 
 | 
   212  | 
// fizz buzz
  | 
| 
 | 
   213  | 
def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
 | 
| 
 | 
   214  | 
  case (0, 0) => "fizz buzz"
  | 
| 
 | 
   215  | 
  case (0, _) => "fizz"
  | 
| 
 | 
   216  | 
  case (_, 0) => "buzz"
  | 
| 
 | 
   217  | 
  case _ => n.toString  
  | 
| 
 | 
   218  | 
}
  | 
| 
 | 
   219  | 
  | 
| 
 | 
   220  | 
for (n <- 0 to 20) 
  | 
| 
 | 
   221  | 
 println(fizz_buzz(n))
  | 
| 
 | 
   222  | 
  | 
| 
 | 
   223  | 
  | 
| 
 | 
   224  | 
// User-defined Datatypes
  | 
| 
 | 
   225  | 
//========================
  | 
| 
 | 
   226  | 
  | 
| 
 | 
   227  | 
abstract class Tree
  | 
| 
 | 
   228  | 
case class Node(elem: Int, left: Tree, right: Tree) extends Tree
  | 
| 
 | 
   229  | 
case class Leaf() extends Tree
  | 
| 
 | 
   230  | 
  | 
| 
 | 
   231  | 
  | 
| 
 | 
   232  | 
def insert(tr: Tree, n: Int): Tree = tr match {
 | 
| 
 | 
   233  | 
  case Leaf() => Node(n, Leaf(), Leaf())
  | 
| 
 | 
   234  | 
  case Node(m, left, right) => 
  | 
| 
 | 
   235  | 
    if (n == m) Node(m, left, right) 
  | 
| 
 | 
   236  | 
    else if (n < m) Node(m, insert(left, n), right)
  | 
| 
 | 
   237  | 
    else Node(m, left, insert(right, n))
  | 
| 
173
 | 
   238  | 
}
  | 
| 
 | 
   239  | 
  | 
| 
192
 | 
   240  | 
  | 
| 
 | 
   241  | 
val t1 = Node(4, Node(2, Leaf(), Leaf()), Node(7, Leaf(), Leaf()))
  | 
| 
 | 
   242  | 
insert(t1, 3)
  | 
| 
 | 
   243  | 
  | 
| 
 | 
   244  | 
def depth(tr: Tree): Int = tr match {
 | 
| 
 | 
   245  | 
  case Leaf() => 0
  | 
| 
 | 
   246  | 
  case Node(_, left, right) => 1 + List(depth(left), depth(right)).max
  | 
| 
 | 
   247  | 
}
  | 
| 
 | 
   248  | 
  | 
| 
 | 
   249  | 
  | 
| 
 | 
   250  | 
def balance(tr: Tree): Int = tr match {
 | 
| 
 | 
   251  | 
  case Leaf() => 0
  | 
| 
 | 
   252  | 
  case Node(_, left, right) => depth(left) - depth(right)
  | 
| 
 | 
   253  | 
}
  | 
| 
 | 
   254  | 
  | 
| 
 | 
   255  | 
balance(insert(t1, 3))
  | 
| 
 | 
   256  | 
  | 
| 
 | 
   257  | 
// another example
  | 
| 
 | 
   258  | 
  | 
| 
 | 
   259  | 
abstract class Person
  | 
| 
 | 
   260  | 
case class King() extends Person
  | 
| 
 | 
   261  | 
case class Peer(deg: String, terr: String, succ: Int) extends Person
  | 
| 
 | 
   262  | 
case class Knight(name: String) extends Person
  | 
| 
 | 
   263  | 
case class Peasant(name: String) extends Person
  | 
| 
 | 
   264  | 
case class Clown() extends Person
  | 
| 
173
 | 
   265  | 
  | 
| 
192
 | 
   266  | 
def title(p: Person): String = p match {
 | 
| 
 | 
   267  | 
  case King() => "His Majesty the King"
  | 
| 
 | 
   268  | 
  case Peer(deg, terr, _) => s"The ${deg} of ${terr}"
 | 
| 
 | 
   269  | 
  case Knight(name) => s"Sir ${name}"
 | 
| 
 | 
   270  | 
  case Peasant(name) => name
  | 
| 
 | 
   271  | 
}
  | 
| 
173
 | 
   272  | 
  | 
| 
192
 | 
   273  | 
def superior(p1: Person, p2: Person): Boolean = (p1, p2) match {
 | 
| 
 | 
   274  | 
  case (King(), _) => true
  | 
| 
 | 
   275  | 
  case (Peer(_,_,_), Knight(_)) => true
  | 
| 
 | 
   276  | 
  case (Peer(_,_,_), Peasant(_)) => true
  | 
| 
 | 
   277  | 
  case (Peer(_,_,_), Clown()) => true
  | 
| 
 | 
   278  | 
  case (Knight(_), Peasant(_)) => true
  | 
| 
 | 
   279  | 
  case (Knight(_), Clown()) => true
  | 
| 
 | 
   280  | 
  case (Clown(), Peasant(_)) => true
  | 
| 
 | 
   281  | 
  case _ => false
  | 
| 
 | 
   282  | 
}
  | 
| 
 | 
   283  | 
  | 
| 
 | 
   284  | 
val people = List(Knight("David"), 
 | 
| 
 | 
   285  | 
                  Peer("Duke", "Norfolk", 84), 
 | 
| 
 | 
   286  | 
                  Peasant("Christian"), 
 | 
| 
 | 
   287  | 
                  King(), 
  | 
| 
 | 
   288  | 
                  Clown())
  | 
| 
 | 
   289  | 
  | 
| 
 | 
   290  | 
println(people.sortWith(superior(_, _)).mkString(", "))
 | 
| 
 | 
   291  | 
  | 
| 
173
 | 
   292  | 
  | 
| 
 | 
   293  | 
  | 
| 
147
 | 
   294  | 
// Higher-Order Functions
  | 
| 
 | 
   295  | 
//========================
  | 
| 
 | 
   296  | 
  | 
| 
 | 
   297  | 
// functions can take functions as arguments
  | 
| 
 | 
   298  | 
  | 
| 
 | 
   299  | 
val lst = (1 to 10).toList
  | 
| 
 | 
   300  | 
  | 
| 
192
 | 
   301  | 
def even(x: Int): Boolean = x % 2 == 0
  | 
| 
 | 
   302  | 
def odd(x: Int): Boolean = x % 2 == 1
  | 
| 
147
 | 
   303  | 
  | 
| 
192
 | 
   304  | 
lst.filter(x => even(x))
  | 
| 
147
 | 
   305  | 
lst.filter(even(_))
  | 
| 
192
 | 
   306  | 
lst.filter(even)
  | 
| 
147
 | 
   307  | 
  | 
| 
 | 
   308  | 
lst.find(_ > 8)
  | 
| 
 | 
   309  | 
  | 
| 
 | 
   310  | 
def square(x: Int): Int = x * x
  | 
| 
 | 
   311  | 
  | 
| 
 | 
   312  | 
lst.map(square)
  | 
| 
 | 
   313  | 
  | 
| 
 | 
   314  | 
lst.map(square).filter(_ > 4)
  | 
| 
 | 
   315  | 
  | 
| 
 | 
   316  | 
lst.map(square).filter(_ > 4).map(square)
  | 
| 
 | 
   317  | 
  | 
| 
192
 | 
   318  | 
// in my collatz.scala
  | 
| 
 | 
   319  | 
//(1 to bnd).map(i => (collatz(i), i)).maxBy(_._1)
  | 
| 
147
 | 
   320  | 
  | 
| 
 | 
   321  | 
  | 
| 
192
 | 
   322  | 
// type of functions, for example f: Int => Int
  | 
| 
147
 | 
   323  | 
  | 
| 
192
 | 
   324  | 
def my_map_int(lst: List[Int], f: Int => Int): List[Int] = lst match {
 | 
| 
 | 
   325  | 
  case Nil => Nil
  | 
| 
 | 
   326  | 
  case x::xs => f(x)::my_map_int(xs, f)
  | 
| 
147
 | 
   327  | 
}
  | 
| 
 | 
   328  | 
  | 
| 
192
 | 
   329  | 
my_map_int(lst, square)
  | 
| 
147
 | 
   330  | 
  | 
| 
 | 
   331  | 
// other function types
  | 
| 
 | 
   332  | 
//
  | 
| 
 | 
   333  | 
// f1: (Int, Int) => Int
  | 
| 
 | 
   334  | 
// f2: List[String] => Option[Int]
  | 
| 
 | 
   335  | 
// ... 
  | 
| 
 | 
   336  | 
  | 
| 
 | 
   337  | 
  | 
| 
192
 | 
   338  | 
def sumOf(f: Int => Int, lst: List[Int]): Int = lst match {
 | 
| 
 | 
   339  | 
  case Nil => 0
  | 
| 
 | 
   340  | 
  case x::xs => f(x) + sumOf(f, xs)
  | 
| 
167
 | 
   341  | 
}
  | 
| 
 | 
   342  | 
  | 
| 
192
 | 
   343  | 
def sum_squares(lst: List[Int]) = sumOf(square, lst)
  | 
| 
 | 
   344  | 
def sum_cubes(lst: List[Int])   = sumOf(x => x * x * x, lst)
  | 
| 
167
 | 
   345  | 
  | 
| 
192
 | 
   346  | 
sum_squares(lst)
  | 
| 
 | 
   347  | 
sum_cubes(lst)
  | 
| 
 | 
   348  | 
  | 
| 
 | 
   349  | 
// lets try it factorial
  | 
| 
 | 
   350  | 
def fact(n: Int): Int = ...
  | 
| 
167
 | 
   351  | 
  | 
| 
192
 | 
   352  | 
def sum_fact(lst: List[Int]) = sumOf(fact, lst)
  | 
| 
 | 
   353  | 
sum_fact(lst)
  | 
| 
167
 | 
   354  | 
  | 
| 
192
 | 
   355  | 
// Avoid being mutable
  | 
| 
 | 
   356  | 
//=====================
  | 
| 
167
 | 
   357  | 
  | 
| 
192
 | 
   358  | 
// a student showed me...
  | 
| 
 | 
   359  | 
import scala.collection.mutable.ListBuffer
  | 
| 
167
 | 
   360  | 
  | 
| 
 | 
   361  | 
  | 
| 
 | 
   362  | 
  | 
| 
192
 | 
   363  | 
def collatz_max(bnd: Long): (Long, Long) = {
 | 
| 
 | 
   364  | 
  val colNos = ListBuffer[(Long, Long)]()
  | 
| 
 | 
   365  | 
  for (i <- (1L to bnd).toList) colNos += ((collatz(i), i))
  | 
| 
 | 
   366  | 
  colNos.max
  | 
| 
 | 
   367  | 
}
  | 
| 
147
 | 
   368  | 
  | 
| 
192
 | 
   369  | 
def collatz_max(bnd: Long): (Long, Long) = {
 | 
| 
 | 
   370  | 
  (1L to bnd).map((i) => (collatz(i), i)).maxBy(_._1)
  | 
| 
147
 | 
   371  | 
}
  | 
| 
 | 
   372  | 
  | 
| 
192
 | 
   373  | 
//views -> lazy collection
  | 
| 
 | 
   374  | 
def collatz_max(bnd: Long): (Long, Long) = {
 | 
| 
 | 
   375  | 
  (1L to bnd).view.map((i) => (collatz(i), i)).maxBy(_._1)
  | 
| 
147
 | 
   376  | 
}
  | 
| 
 | 
   377  | 
  | 
| 
192
 | 
   378  | 
// raises a GC exception
  | 
| 
 | 
   379  | 
(1 to 1000000000).filter(_ % 2 == 0).take(10).toList
  | 
| 
 | 
   380  | 
// ==> java.lang.OutOfMemoryError: GC overhead limit exceeded
  | 
| 
147
 | 
   381  | 
  | 
| 
192
 | 
   382  | 
(1 to 1000000000).view.filter(_ % 2 == 0).take(10).toList
  | 
| 
150
 | 
   383  | 
  | 
| 
 | 
   384  | 
  | 
| 
 | 
   385  | 
  | 
| 
192
 | 
   386  | 
// Sudoku
  | 
| 
 | 
   387  | 
//========
  | 
| 
53
 | 
   388  | 
  | 
| 
57
 | 
   389  | 
// THE POINT OF THIS CODE IS NOT TO BE SUPER
  | 
| 
 | 
   390  | 
// EFFICIENT AND FAST, just explaining exhaustive
  | 
| 
 | 
   391  | 
// depth-first search
  | 
| 
 | 
   392  | 
  | 
| 
 | 
   393  | 
  | 
| 
55
 | 
   394  | 
val game0 = """.14.6.3..
  | 
| 
 | 
   395  | 
              |62...4..9
  | 
| 
 | 
   396  | 
              |.8..5.6..
  | 
| 
 | 
   397  | 
              |.6.2....3
  | 
| 
 | 
   398  | 
              |.7..1..5.
  | 
| 
 | 
   399  | 
              |5....9.6.
  | 
| 
 | 
   400  | 
              |..6.2..3.
  | 
| 
 | 
   401  | 
              |1..5...92
  | 
| 
 | 
   402  | 
              |..7.9.41.""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   403  | 
  | 
| 
 | 
   404  | 
type Pos = (Int, Int)
  | 
| 
 | 
   405  | 
val EmptyValue = '.'
  | 
| 
 | 
   406  | 
val MaxValue = 9
  | 
| 
 | 
   407  | 
  | 
| 
 | 
   408  | 
val allValues = "123456789".toList
  | 
| 
 | 
   409  | 
val indexes = (0 to 8).toList
  | 
| 
 | 
   410  | 
  | 
| 
57
 | 
   411  | 
  | 
| 
 | 
   412  | 
  | 
| 
55
 | 
   413  | 
  | 
| 
192
 | 
   414  | 
def empty(game: String) = game.indexOf(EmptyValue)
  | 
| 
 | 
   415  | 
def isDone(game: String) = empty(game) == -1 
  | 
| 
 | 
   416  | 
def emptyPosition(game: String) = (empty(game) % MaxValue, empty(game) / MaxValue)
  | 
| 
57
 | 
   417  | 
  | 
| 
192
 | 
   418  | 
  | 
| 
 | 
   419  | 
def get_row(game: String, y: Int) = indexes.map(col => game(y * MaxValue + col))
  | 
| 
 | 
   420  | 
def get_col(game: String, x: Int) = indexes.map(row => game(x + row * MaxValue))
  | 
| 
147
 | 
   421  | 
  | 
| 
57
 | 
   422  | 
def get_box(game: String, pos: Pos): List[Char] = {
 | 
| 
55
 | 
   423  | 
    def base(p: Int): Int = (p / 3) * 3
  | 
| 
 | 
   424  | 
    val x0 = base(pos._1)
  | 
| 
 | 
   425  | 
    val y0 = base(pos._2)
  | 
| 
 | 
   426  | 
    val ys = (y0 until y0 + 3).toList
  | 
| 
 | 
   427  | 
    (x0 until x0 + 3).toList.flatMap(x => ys.map(y => game(x + y * MaxValue)))
  | 
| 
 | 
   428  | 
}
  | 
| 
 | 
   429  | 
  | 
| 
 | 
   430  | 
  | 
| 
192
 | 
   431  | 
//get_row(game0, 0)
  | 
| 
 | 
   432  | 
//get_row(game0, 1)
  | 
| 
 | 
   433  | 
//get_box(game0, (3,1))
  | 
| 
 | 
   434  | 
  | 
| 
 | 
   435  | 
def update(game: String, pos: Int, value: Char): String = game.updated(pos, value)
  | 
| 
55
 | 
   436  | 
  | 
| 
 | 
   437  | 
def toAvoid(game: String, pos: Pos): List[Char] = 
  | 
| 
57
 | 
   438  | 
  (get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos))
  | 
| 
55
 | 
   439  | 
  | 
| 
192
 | 
   440  | 
def candidates(game: String, pos: Pos): List[Char] = allValues diff toAvoid(game,pos)
  | 
| 
55
 | 
   441  | 
  | 
| 
 | 
   442  | 
//candidates(game0, (0,0))
  | 
| 
 | 
   443  | 
  | 
| 
192
 | 
   444  | 
def pretty(game: String): String = "\n" + (game sliding (MaxValue, MaxValue) mkString "\n")
  | 
| 
55
 | 
   445  | 
  | 
| 
 | 
   446  | 
def search(game: String): List[String] = {
 | 
| 
 | 
   447  | 
  if (isDone(game)) List(game)
  | 
| 
192
 | 
   448  | 
  else 
  | 
| 
 | 
   449  | 
    candidates(game, emptyPosition(game)).map(c => search(update(game, empty(game), c))).toList.flatten
  | 
| 
55
 | 
   450  | 
}
  | 
| 
 | 
   451  | 
  | 
| 
 | 
   452  | 
  | 
| 
 | 
   453  | 
val game1 = """23.915...
  | 
| 
 | 
   454  | 
              |...2..54.
  | 
| 
 | 
   455  | 
              |6.7......
  | 
| 
 | 
   456  | 
              |..1.....9
  | 
| 
 | 
   457  | 
              |89.5.3.17
  | 
| 
 | 
   458  | 
              |5.....6..
  | 
| 
 | 
   459  | 
              |......9.5
  | 
| 
 | 
   460  | 
              |.16..7...
  | 
| 
 | 
   461  | 
              |...329..1""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   462  | 
  | 
| 
57
 | 
   463  | 
  | 
| 
192
 | 
   464  | 
// game that is in the hard category
  | 
| 
55
 | 
   465  | 
val game2 = """8........
  | 
| 
 | 
   466  | 
              |..36.....
  | 
| 
 | 
   467  | 
              |.7..9.2..
  | 
| 
 | 
   468  | 
              |.5...7...
  | 
| 
 | 
   469  | 
              |....457..
  | 
| 
 | 
   470  | 
              |...1...3.
  | 
| 
 | 
   471  | 
              |..1....68
  | 
| 
 | 
   472  | 
              |..85...1.
  | 
| 
 | 
   473  | 
              |.9....4..""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   474  | 
  | 
| 
 | 
   475  | 
// game with multiple solutions
  | 
| 
 | 
   476  | 
val game3 = """.8...9743
  | 
| 
 | 
   477  | 
              |.5...8.1.
  | 
| 
 | 
   478  | 
              |.1.......
  | 
| 
 | 
   479  | 
              |8....5...
  | 
| 
 | 
   480  | 
              |...8.4...
  | 
| 
 | 
   481  | 
              |...3....6
  | 
| 
 | 
   482  | 
              |.......7.
  | 
| 
 | 
   483  | 
              |.3.5...8.
  | 
| 
 | 
   484  | 
              |9724...5.""".stripMargin.replaceAll("\\n", "")
 | 
| 
 | 
   485  | 
  | 
| 
57
 | 
   486  | 
  | 
| 
192
 | 
   487  | 
search(game0).map(pretty)
  | 
| 
 | 
   488  | 
search(game1).map(pretty)
  | 
| 
55
 | 
   489  | 
  | 
| 
 | 
   490  | 
// for measuring time
  | 
| 
 | 
   491  | 
def time_needed[T](i: Int, code: => T) = {
 | 
| 
 | 
   492  | 
  val start = System.nanoTime()
  | 
| 
 | 
   493  | 
  for (j <- 1 to i) code
  | 
| 
 | 
   494  | 
  val end = System.nanoTime()
  | 
| 
 | 
   495  | 
  ((end - start) / i / 1.0e9) + " secs"
  | 
| 
 | 
   496  | 
}
  | 
| 
 | 
   497  | 
  | 
| 
 | 
   498  | 
search(game2).map(pretty)
  | 
| 
57
 | 
   499  | 
search(game3).distinct.length
  | 
| 
192
 | 
   500  | 
time_needed(3, search(game2))
  | 
| 
 | 
   501  | 
time_needed(3, search(game3))
  | 
| 
55
 | 
   502  | 
  | 
| 
53
 | 
   503  | 
  | 
| 
 | 
   504  | 
  | 
| 
 | 
   505  | 
  | 
| 
192
 | 
   506  | 
  |