progs/lecture5.scala
changeset 383 c02929f2647c
parent 380 d19b0a50ceb9
child 384 6e1237691307
--- a/progs/lecture5.scala	Wed Dec 02 01:15:14 2020 +0000
+++ b/progs/lecture5.scala	Mon Dec 07 01:25:41 2020 +0000
@@ -1,8 +1,6 @@
 // Scala Lecture 5
 //=================
 
-// TODO: word count for a very large file (40GB or so)
-// Transform Farenheit into Celsius
 
 
 // Laziness with style
@@ -174,7 +172,6 @@
 
 // (Immutable)
 // Object Oriented Programming in Scala
-//
 // =====================================
 
 
@@ -194,6 +191,13 @@
 println(Bird("Sparrow"))
 println(Bird("Sparrow").toString)
 
+Bird("Sparrow").copy(name = "House Sparrow")
+
+def group(a : Animal) = a match {
+  case Bird(_) => "It's a bird"
+  case Mammal(_) => "It's a mammal"
+}
+
 
 // There is a very convenient short-hand notation
 // for constructors:
@@ -204,11 +208,13 @@
 }
 
 val half = new Fraction(1, 2)
+half.numer
 
 case class Fraction(numer: Int, denom: Int)
 
 val half = Fraction(1, 2)
 
+half.numer
 half.denom
 
 
@@ -228,6 +234,9 @@
 
 val test = Complex(1, 2) + Complex (3, 4)
 
+import scala.language.postfixOps
+List(5,4,3,2,1).sorted.reverse
+
 // this could have equally been written as
 val test = Complex(1, 2).+(Complex (3, 4))
 
@@ -270,7 +279,7 @@
 }
 
 // BUT since we are completely IMMUTABLE, this is 
-// virtually of not concern to us.
+// virtually of no concern to us.
 
 
 
@@ -278,25 +287,26 @@
 import scala.language.implicitConversions
 import scala.language.reflectiveCalls
 
-
 case class Fraction(numer: Int, denom: Int) {
   override def toString = numer.toString + "/" + denom.toString
 
-  def +(other: Fraction) = Fraction(numer + other.numer, denom + other.denom)
-  def /(other: Fraction) = Fraction(numer * other.denom, denom * other.numer)
+  def +(other: Fraction) = 
+    Fraction(numer * other.denom + other.numer * denom, 
+             denom * other.denom)
+  def *(other: Fraction) = Fraction(numer * other.numer, denom * other.denom)
  }
 
 implicit def Int2Fraction(x: Int) = Fraction(x, 1)
 
-
 val half = Fraction(1, 2)
 val third = Fraction (1, 3)
 
 half + third
-half / third
+half * third
 
-(1 / 3) + half
-(1 / 2) + third
+1 + half
+
+
 
 
 // DFAs in Scala  
@@ -317,7 +327,7 @@
   }
 
   def accepts(s: List[C]) : Boolean = 
-    Try(fins(deltas(start, s))) getOrElse false
+    Try(fins(deltas(start, s))).getOrElse(false)
 }
 
 // the example shown in the handout 
@@ -359,7 +369,7 @@
   // given a state and a character, what is the set of 
   // next states? if there is none => empty set
   def next(q: A, c: C) : Set[A] = 
-    Try(delta(q, c)) getOrElse Set[A]() 
+    Try(delta(q, c)).getOrElse(Set[A]()) 
 
   def nexts(qs: Set[A], c: C) : Set[A] =
     qs.flatMap(next(_, c))
@@ -398,6 +408,7 @@
 // A: Subset construction. Here the state type for the DFA is
 //    sets of states.
 
+
 def subset[A, C](nfa: NFA[A, C]) : DFA[Set[A], C] = {
   DFA(nfa.starts, 
       { case (qs, c) => nfa.nexts(qs, c) },