--- a/progs/lecture3.scala Tue Nov 19 06:38:20 2019 +0000
+++ b/progs/lecture3.scala Fri Nov 22 16:41:45 2019 +0000
@@ -7,6 +7,32 @@
// higher-order function
+def add(x: Int, y: Int) : Int = x + y
+
+def plus5(x: Int) : Int = add(5, x)
+
+plus5(6)
+
+def add2(x: Int)(y: Int) : Int = x + y
+
+def plus3(y: Int) : Int => Int = add2(3)(y)
+
+plus3(9)
+
+List(1,2,3,4,5).map(add2(3))
+List(1,2,3,4,5).map(add(3, _))
+
+type Pos = (Int, Int)
+
+def test(p: Pos) = {
+ if (p._1 < 5 && p._2 < 5) {
+ Some(p)
+ }
+}
+
+val l = List((1,2), (5,3), (2,5), (1,3))
+
+l.map(test).flatten
// Recursion Again ;o)
//====================
@@ -57,7 +83,7 @@
crawl(startURL, 2)
-
+for (x <- List(1,2,3,4,5,6)) println(x)
// a primitive email harvester
def emails(url: String, n: Int) : Set[String] = {
@@ -66,11 +92,11 @@
println(s" Visiting: $n $url")
val page = get_page(url)
val new_emails = email_pattern.findAllIn(page).toSet
- new_emails ++ (for (u <- get_all_URLs(page)) yield emails(u, n - 1)).flatten
+ new_emails ++ (for (u <- get_all_URLs(page).par) yield emails(u, n - 1)).flatten
}
}
-emails(startURL, 2)
+emails(startURL, 3)
// if we want to explore the internet "deeper", then we
@@ -109,8 +135,8 @@
def moves(xs: List[Int], n: Int) : List[List[Int]] = (xs, n) match {
case (Nil, _) => Nil
- case (xs, 0) => Nil
- case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
+ case (_, 0) => Nil
+ case (y::ys, n) => xs :: moves(ys, n - 1)
}
@@ -181,17 +207,22 @@
// User-defined Datatypes
//========================
+abstract class Tree
+case class Leaf(x: Int) extends Tree
+case class Node(s: String, left: Tree, right: Tree) extends Tree
+
+List(Leaf(20), Node("foo", Leaf(1), Leaf(2)))
sealed abstract class Colour
case object Red extends Colour
case object Green extends Colour
case object Blue extends Colour
+case object Yellow extends Colour
def fav_colour(c: Colour) : Boolean = c match {
- case Red => false
case Green => true
- case Blue => false
+ case _ => false
}
fav_colour(Green)
@@ -209,7 +240,7 @@
type RomanNumeral = List[RomanDigit]
-List(X,I)
+List(X,I,M,D)
/*
I -> 1
@@ -271,6 +302,10 @@
// trees
+
+
+// expressions
+
sealed abstract class Exp
case class N(n: Int) extends Exp // for numbers
case class Plus(e1: Exp, e2: Exp) extends Exp