--- a/progs/lecture2.scala Mon Nov 06 21:49:55 2023 +0000
+++ b/progs/lecture2.scala Fri Dec 08 00:54:36 2023 +0000
@@ -33,16 +33,12 @@
def safe_div(x: Int, y: Int) : Option[Int] =
if (y == 0) None else Some(x / y)
-safe_div(10 + 5, 4 - 1)
+safe_div(10 + 5, 0)
List(1,2,3,4,5,6).indexOf(7)
List[Int]().min
-List[Int]().minOption
+List[Int](3,4,5).minOption
-def my_min(ls: List[Int]) : Option[Int] =
- ls.minOption
-
-my_min(List(1,2,3,4))
// better error handling with Options (no exceptions)
@@ -53,7 +49,7 @@
import scala.util._ // Try,...
import io.Source // fromURL
-val my_url = "https://nms.kcl.ac.uk/christian.urban/"
+val my_url = "https://nms.kcl.ac.uk/christian.urban2/"
Source.fromURL(my_url)("ISO-8859-1").mkString
Source.fromURL(my_url)("ISO-8859-1").getLines().toList
@@ -174,9 +170,10 @@
def even(x: Int) : Boolean = x % 2 == 0
def odd(x: Int) : Boolean = x % 2 == 1
+def inc(x: Int) : Int = x + 1
val lst = (1 to 10).toList
-lst.filter(even)
+lst.filter(_ % 2 == 0)
lst.count(odd)
lst.find(even)
lst.exists(even)
@@ -184,9 +181,11 @@
lst.find(_ < 4)
lst.filter(_ < 4)
+val x = 3 < 4
+
def less4(x: Int) : Boolean = x < 4
lst.find(less4)
-lst.find(_ < 4)
+lst.find(x => !(x < 4))
lst.filter(x => x % 2 == 0)
lst.filter(_ % 2 == 0)
@@ -230,7 +229,7 @@
// works also for strings
def tweet(c: Char) = c.toUpper
-"Hello World".map(tweet)
+"Hello\nWorld".map(tweet)
// this can be iterated
@@ -351,6 +350,19 @@
val grps = lst.groupBy(_.length)
grps.keySet
+// naive quicksort with "On" function
+
+def sortOn(f: Int => Int, xs: List[Int]) : List[Int] = {
+ if (xs.size < 2) xs
+ else {
+ val pivot = xs.head
+ val (left, right) = xs.partition(f(_) < f(pivot))
+ sortOn(f, left) ::: pivot :: sortOn(f, right.tail)
+ }
+}
+
+sortOn(identity, List(99,99,99,98,10,-3,2))
+sortOn(n => - n, List(99,99,99,98,10,-3,2))