// Scala Lecture 2
//=================
// Option type
//=============
//in Java if something unusually happens, you return null
//in Scala you use Option
// - if the value is present, you use Some(value)
// - if no value is present, you use None
List(7,2,3,4,5,6).find(_ < 4)
List(5,6,7,8,9).find(_ < 4)
val lst = List(None, Some(1), Some(2), None, Some(3))
lst.flatten
Some(1).get
Some(1).isDefined
None.isDefined
val ps = List((3, 0), (3, 2), (4, 2), (2, 0), (1, 0), (1, 1))
for ((x, y) <- ps) yield {
if (y == 0) None else Some(x / y)
}
// getOrElse is to set a default value
val lst = List(None, Some(1), Some(2), None, Some(3))
for (x <- lst) yield x getOrElse 0
import scala.util._
import io.Source
// error handling with option
//
// Try(something).getOrElse(what_to_do_in_an_exception)
Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanccc/""").mkString
Try(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString).getOrElse("")
Try(Some(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString)).getOrElse(None)
Integer.parseInt("12u34")
def get_me_an_int(s: String): Option[Int] =
Try(Some(Integer.parseInt(s))).getOrElse(None)
val lst = List("12345", "foo", "5432", "bar", "x21")
for (x <- lst) yield get_me_an_int(x)
// summing all the numbers
val sum = lst.flatMap(get_me_an_int(_)).sum
// This may not look any better than working with null in Java, but to
// see the value, you have to put yourself in the shoes of the
// consumer of the get_me_an_int function, and imagine you didn't
// write that function.
//
// In Java, if you didn't write this function, you'd have to depend on
// the Javadoc of the get_me_an_int. If you didn't look at the Javadoc
// for the Java, you might not know that get_me_an_int could return a
// null, and your code could potentially throw a NullPointerException.
// Type abbreviations
//====================
// some syntactic convenience
type Pos = (int, Int)
type Board = List[List[Int]]
// No return in Scala
//====================
//You should not use "return" in Scala:
//
// A return expression, when evaluated, abandons the
// current computation and returns to the caller of the
// function in which return appears."
def sq1(x: Int): Int = x * x
def sq2(x: Int): Int = return x * x
def sumq(ls: List[Int]): Int = {
(for (x <- ls) yield (return x * x)).sum[Int]
}
sumq(List(1,2,3,4))
// last expression in a function is the return statement
def square(x: Int): Int = {
println(s"The argument is ${x}.")
x * x
}
// Pattern Matching
//==================
// A powerful tool which is supposed to come to Java in a few years
// time (https://www.youtube.com/watch?v=oGll155-vuQ)...Scala already
// has it for many years ;o)
// The general schema:
//
// expression match {
// case pattern1 => expression1
// case pattern2 => expression2
// ...
// case patternN => expressionN
// }
// remember
val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
def my_flatten(xs: List[Option[Int]]): List[Int] = {
...
}
def my_flatten(lst: List[Option[Int]]): List[Int] = lst match {
case Nil => Nil
case None::xs => my_flatten(xs)
case Some(n)::xs => n::my_flatten(xs)
}
// another example
def get_me_a_string(n: Int): String = n match {
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "many"
}
// Higher-Order Functions
//========================
// functions can take functions as arguments
val lst = (1 to 10).toList
def even(x: Int): Boolean = x % 2 == 0
def odd(x: Int): Boolean = x % 2 == 1
lst.filter(x => even(x))
lst.filter(even(_))
lst.filter(even)
lst.find(_ > 8)
def square(x: Int): Int = x * x
lst.map(square)
lst.map(square).filter(_ > 4)
// Sudoku
//========
//sorting, higher-order functions
//lexicographic ordering
// Implicits
//===========
//
// for example adding your own methods to Strings:
// imagine you want to increment strings, like
//
// "HAL".increment
//
// you can avoid ugly fudges, like a MyString, by
// using implicit conversions
implicit class MyString(s: String) {
def increment = for (c <- s) yield (c + 1).toChar
}
"HAL".increment