diff -r 99dcfdf5aed8 -r f51e593903ac progs/lecture2.scala --- a/progs/lecture2.scala Thu Nov 17 20:05:36 2022 +0000 +++ b/progs/lecture2.scala Mon Nov 21 15:57:45 2022 +0000 @@ -70,14 +70,19 @@ // List[Int]: Nil, List(_) // // Option[Int]: None, Some(0), Some(1), ... +// Option[Boolean]: None, Some(true), Some(false) // Option[...]: None, Some(_) def safe_div(x: Int, y: Int) : Option[Int] = if (y == 0) None else Some(x / y) -List(1,2,3,4,5,6).indexOf(7) +safe_div(10 + 5, 4 - 1) -def my_min(ls: List[Int]) : Option[Int] = ls.minOption +List(1,2,3,4,5,6).indexOf(7) +List[Int]().minOption + +def my_min(ls: List[Int]) : Option[Int] = + ls.minOption my_min(List(1,2,3,4)) @@ -90,9 +95,10 @@ import scala.util._ import io.Source -val my_url = "https://nms.kcl.ac.uk/christian.urban2/" +val my_url = "https://nms.kcl.ac.uk/christian.urban/" Source.fromURL(my_url)("ISO-8859-1").mkString +Source.fromURL(my_url)("ISO-8859-1").getLines().toList Try(Source.fromURL(my_url)("ISO-8859-1").mkString).getOrElse("") @@ -100,14 +106,18 @@ // the same for files + Try(Some(Source.fromFile("test.txt")("ISO-8859-1").mkString)).getOrElse(None) +Try(Source.fromFile("test.txt")("ISO-8859-1").mkString).toOption + +Using(Source.fromFile("test.txt")("ISO-8859-1"))(_.mkString).toOption // how to implement a function for reading -// (lines) something from files... +// (lines) from files... // def get_contents(name: String) : List[String] = - Source.fromFile(name)("ISO-8859-1").getLines.toList + Source.fromFile(name)("ISO-8859-1").getLines().toList get_contents("text.txt") get_contents("test.txt") @@ -120,7 +130,7 @@ // much better - you record in the type that things can go wrong def get_contents(name: String) : Option[List[String]] = - Try(Some(Source.fromFile(name)("ISO-8859-1").getLines.toList)).getOrElse(None) + Try(Some(Source.fromFile(name)("ISO-8859-1").getLines().toList)).getOrElse(None) get_contents("text.txt") get_contents("test.txt") @@ -158,8 +168,6 @@ val lst = List(None, Some(1), Some(2), None, Some(3)) - - // a function that turns strings into numbers // (similar to .toInt) Integer.parseInt("1234") @@ -234,7 +242,7 @@ lst.find(n => odd(n) && n > 2) - +// lexicographic ordering val ps = List((3, 0), (3, 2), (4, 2), (2, 2), (2, 0), (1, 1), (1, 0))