--- a/progs/lecture2.scala Sun Sep 15 12:57:59 2024 +0100
+++ b/progs/lecture2.scala Mon Jul 21 16:38:07 2025 +0100
@@ -30,14 +30,23 @@
// Option[Boolean]: None, Some(true), Some(false)
// Option[...]: None, Some(_)
+def div(x: Int, y: Int) : Int =
+ x / y
+
def safe_div(x: Int, y: Int) : Option[Int] =
if (y == 0) None else Some(x / y)
-safe_div(10 + 5, 0)
+def foo_calculation(x: Int) =
+ if (safe_div(x, x) == None) 24 else safe_div(x, x).get
+
+foo_calculation(3)
+foo_calculation(0)
+
+safe_div(10 + 5, 3)
List(1,2,3,4,5,6).indexOf(7)
-List[Int]().min
-List[Int](3,4,5).minOption
+List[Int](3,4,5).min
+List[Int]().minOption
@@ -49,7 +58,7 @@
import scala.util._ // Try,...
import io.Source // fromURL
-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
@@ -94,6 +103,11 @@
val lst = List(None, Some(1), Some(2), None, Some(3))
+for (x <- lst) yield {
+ if (x == None) None
+ else Some(x.get + 1)
+}
+
lst.flatten
Some(1).get
@@ -173,10 +187,13 @@
def inc(x: Int) : Int = x + 1
val lst = (1 to 10).toList
-lst.filter(_ % 2 == 0)
+lst.filter(odd)
+lst.exists(even)
lst.count(odd)
-lst.find(even)
-lst.exists(even)
+
+lst.filter(_ % 2 == 0)
+
+
lst.find(_ < 4)
lst.filter(_ < 4)
@@ -191,8 +208,8 @@
lst.filter(_ % 2 == 0)
-lst.sortWith((x, y) => x < y)
-lst.sortWith(_ > _)
+lst.sortWith((x, y) => x > y)
+lst.sortWith(_ < _)
// but this only works when the arguments are clear, but
// not with multiple occurences
@@ -211,7 +228,7 @@
ps.sortBy(x => x._1)
ps.sortBy(_._2)
-ps.maxBy(_._1)
+ps.maxBy(x => x._2)
ps.maxBy(_._2)
@@ -224,6 +241,10 @@
val lst = (1 to 10).toList
lst.map(square)
+lst.map(n => square(n))
+
+for (n <- lst) yield square(n)
+
lst.map(x => (double(x), square(x)))
// works also for strings