238
|
1 |
// Scala Lecture 5
|
222
|
2 |
//=================
|
|
3 |
|
494
|
4 |
def foo(n: Int) = ???
|
481
|
5 |
|
494
|
6 |
fop(10)
|
481
|
7 |
|
494
|
8 |
List.fill(1)(100)
|
|
9 |
// (Immutable) OOP
|
481
|
10 |
|
326
|
11 |
// Object Oriented Programming in Scala
|
|
12 |
// =====================================
|
238
|
13 |
|
329
|
14 |
|
|
15 |
abstract class Animal
|
326
|
16 |
case class Bird(name: String) extends Animal {
|
|
17 |
override def toString = name
|
|
18 |
}
|
|
19 |
case class Mammal(name: String) extends Animal
|
|
20 |
case class Reptile(name: String) extends Animal
|
|
21 |
|
|
22 |
Mammal("Zebra")
|
|
23 |
println(Mammal("Zebra"))
|
|
24 |
println(Mammal("Zebra").toString)
|
|
25 |
|
238
|
26 |
|
326
|
27 |
Bird("Sparrow")
|
|
28 |
println(Bird("Sparrow"))
|
|
29 |
println(Bird("Sparrow").toString)
|
|
30 |
|
383
|
31 |
Bird("Sparrow").copy(name = "House Sparrow")
|
|
32 |
|
|
33 |
def group(a : Animal) = a match {
|
|
34 |
case Bird(_) => "It's a bird"
|
|
35 |
case Mammal(_) => "It's a mammal"
|
|
36 |
}
|
|
37 |
|
326
|
38 |
|
|
39 |
// There is a very convenient short-hand notation
|
|
40 |
// for constructors:
|
|
41 |
|
|
42 |
class Fraction(x: Int, y: Int) {
|
|
43 |
def numer = x
|
|
44 |
def denom = y
|
238
|
45 |
}
|
|
46 |
|
481
|
47 |
val half = Fraction(1, 2)
|
383
|
48 |
half.numer
|
326
|
49 |
|
481
|
50 |
// does not work with "vanilla" classes
|
|
51 |
half match {
|
|
52 |
case Fraction(x, y) => x / y
|
|
53 |
}
|
|
54 |
|
|
55 |
|
326
|
56 |
case class Fraction(numer: Int, denom: Int)
|
|
57 |
|
|
58 |
val half = Fraction(1, 2)
|
|
59 |
|
383
|
60 |
half.numer
|
326
|
61 |
half.denom
|
|
62 |
|
481
|
63 |
// works with case classes
|
|
64 |
half match {
|
|
65 |
case Fraction(x, y) => x / y
|
|
66 |
}
|
|
67 |
|
326
|
68 |
|
|
69 |
|
|
70 |
// All is public by default....so no public is needed.
|
|
71 |
// You can have the usual restrictions about private
|
|
72 |
// values and methods, if you are MUTABLE !!!
|
|
73 |
|
|
74 |
case class BankAccount(init: Int) {
|
|
75 |
|
|
76 |
private var balance = init
|
|
77 |
|
|
78 |
def deposit(amount: Int): Unit = {
|
|
79 |
if (amount > 0) balance = balance + amount
|
|
80 |
}
|
238
|
81 |
|
326
|
82 |
def withdraw(amount: Int): Int =
|
|
83 |
if (0 < amount && amount <= balance) {
|
|
84 |
balance = balance - amount
|
|
85 |
balance
|
|
86 |
} else throw new Error("insufficient funds")
|
238
|
87 |
}
|
|
88 |
|
326
|
89 |
// BUT since we are completely IMMUTABLE, this is
|
383
|
90 |
// virtually of no concern to us.
|
326
|
91 |
|
|
92 |
|
|
93 |
|
|
94 |
// another example about Fractions
|
|
95 |
import scala.language.implicitConversions
|
|
96 |
import scala.language.reflectiveCalls
|
|
97 |
|
|
98 |
case class Fraction(numer: Int, denom: Int) {
|
|
99 |
override def toString = numer.toString + "/" + denom.toString
|
|
100 |
|
383
|
101 |
def +(other: Fraction) =
|
|
102 |
Fraction(numer * other.denom + other.numer * denom,
|
|
103 |
denom * other.denom)
|
481
|
104 |
def *(other: Fraction) =
|
|
105 |
Fraction(numer * other.numer, denom * other.denom)
|
326
|
106 |
}
|
|
107 |
|
481
|
108 |
given Conversion[Int, Fraction] = (x => Fraction(x, 1))
|
326
|
109 |
|
|
110 |
val half = Fraction(1, 2)
|
|
111 |
val third = Fraction (1, 3)
|
|
112 |
|
|
113 |
half + third
|
383
|
114 |
half * third
|
326
|
115 |
|
383
|
116 |
1 + half
|
|
117 |
|
|
118 |
|
326
|
119 |
|
|
120 |
|
|
121 |
// DFAs in Scala
|
|
122 |
//===============
|
|
123 |
import scala.util.Try
|
238
|
124 |
|
326
|
125 |
|
|
126 |
// A is the state type
|
|
127 |
// C is the input (usually characters)
|
|
128 |
|
|
129 |
case class DFA[A, C](start: A, // starting state
|
|
130 |
delta: (A, C) => A, // transition function
|
|
131 |
fins: A => Boolean) { // final states (Set)
|
|
132 |
|
|
133 |
def deltas(q: A, s: List[C]) : A = s match {
|
|
134 |
case Nil => q
|
|
135 |
case c::cs => deltas(delta(q, c), cs)
|
|
136 |
}
|
|
137 |
|
|
138 |
def accepts(s: List[C]) : Boolean =
|
383
|
139 |
Try(fins(deltas(start, s))).getOrElse(false)
|
238
|
140 |
}
|
|
141 |
|
326
|
142 |
// the example shown in the handout
|
|
143 |
abstract class State
|
|
144 |
case object Q0 extends State
|
|
145 |
case object Q1 extends State
|
|
146 |
case object Q2 extends State
|
|
147 |
case object Q3 extends State
|
|
148 |
case object Q4 extends State
|
238
|
149 |
|
326
|
150 |
val delta : (State, Char) => State =
|
|
151 |
{ case (Q0, 'a') => Q1
|
|
152 |
case (Q0, 'b') => Q2
|
|
153 |
case (Q1, 'a') => Q4
|
|
154 |
case (Q1, 'b') => Q2
|
|
155 |
case (Q2, 'a') => Q3
|
|
156 |
case (Q2, 'b') => Q2
|
|
157 |
case (Q3, 'a') => Q4
|
|
158 |
case (Q3, 'b') => Q0
|
|
159 |
case (Q4, 'a') => Q4
|
|
160 |
case (Q4, 'b') => Q4
|
|
161 |
case _ => throw new Exception("Undefined") }
|
|
162 |
|
|
163 |
val dfa = DFA(Q0, delta, Set[State](Q4))
|
|
164 |
|
|
165 |
dfa.accepts("abaaa".toList) // true
|
|
166 |
dfa.accepts("bbabaab".toList) // true
|
|
167 |
dfa.accepts("baba".toList) // false
|
|
168 |
dfa.accepts("abc".toList) // false
|
|
169 |
|
238
|
170 |
|
326
|
171 |
// NFAs (Nondeterministic Finite Automata)
|
|
172 |
|
|
173 |
|
|
174 |
case class NFA[A, C](starts: Set[A], // starting states
|
|
175 |
delta: (A, C) => Set[A], // transition function
|
|
176 |
fins: A => Boolean) { // final states
|
|
177 |
|
|
178 |
// given a state and a character, what is the set of
|
|
179 |
// next states? if there is none => empty set
|
|
180 |
def next(q: A, c: C) : Set[A] =
|
383
|
181 |
Try(delta(q, c)).getOrElse(Set[A]())
|
326
|
182 |
|
|
183 |
def nexts(qs: Set[A], c: C) : Set[A] =
|
|
184 |
qs.flatMap(next(_, c))
|
|
185 |
|
|
186 |
// depth-first version of accepts
|
|
187 |
def search(q: A, s: List[C]) : Boolean = s match {
|
|
188 |
case Nil => fins(q)
|
|
189 |
case c::cs => next(q, c).exists(search(_, cs))
|
|
190 |
}
|
|
191 |
|
|
192 |
def accepts(s: List[C]) : Boolean =
|
|
193 |
starts.exists(search(_, s))
|
238
|
194 |
}
|
|
195 |
|
|
196 |
|
326
|
197 |
|
|
198 |
// NFA examples
|
|
199 |
|
|
200 |
val nfa_trans1 : (State, Char) => Set[State] =
|
|
201 |
{ case (Q0, 'a') => Set(Q0, Q1)
|
|
202 |
case (Q0, 'b') => Set(Q2)
|
|
203 |
case (Q1, 'a') => Set(Q1)
|
|
204 |
case (Q2, 'b') => Set(Q2) }
|
238
|
205 |
|
326
|
206 |
val nfa = NFA(Set[State](Q0), nfa_trans1, Set[State](Q2))
|
238
|
207 |
|
326
|
208 |
nfa.accepts("aa".toList) // false
|
|
209 |
nfa.accepts("aaaaa".toList) // false
|
|
210 |
nfa.accepts("aaaaab".toList) // true
|
|
211 |
nfa.accepts("aaaaabbb".toList) // true
|
|
212 |
nfa.accepts("aaaaabbbaaa".toList) // false
|
|
213 |
nfa.accepts("ac".toList) // false
|
222
|
214 |
|
238
|
215 |
|
326
|
216 |
// Q: Why the kerfuffle about the polymorphic types in DFAs/NFAs?
|
|
217 |
// A: Subset construction. Here the state type for the DFA is
|
|
218 |
// sets of states.
|
238
|
219 |
|
383
|
220 |
|
326
|
221 |
def subset[A, C](nfa: NFA[A, C]) : DFA[Set[A], C] = {
|
|
222 |
DFA(nfa.starts,
|
|
223 |
{ case (qs, c) => nfa.nexts(qs, c) },
|
|
224 |
_.exists(nfa.fins))
|
238
|
225 |
}
|
|
226 |
|
326
|
227 |
subset(nfa).accepts("aa".toList) // false
|
|
228 |
subset(nfa).accepts("aaaaa".toList) // false
|
|
229 |
subset(nfa).accepts("aaaaab".toList) // true
|
|
230 |
subset(nfa).accepts("aaaaabbb".toList) // true
|
|
231 |
subset(nfa).accepts("aaaaabbbaaa".toList) // false
|
|
232 |
subset(nfa).accepts("ac".toList) // false
|
238
|
233 |
|
384
|
234 |
|
455
|
235 |
// Laziness with style
|
|
236 |
//=====================
|
|
237 |
|
|
238 |
// The concept of lazy evaluation doesn’t really
|
|
239 |
// exist in non-functional languages. C-like languages
|
|
240 |
// are (sort of) strict. To see the difference, consider
|
|
241 |
|
|
242 |
def square(x: Int) = x * x
|
|
243 |
|
|
244 |
square(42 + 8)
|
|
245 |
|
|
246 |
// This is called "strict evaluation".
|
|
247 |
|
470
|
248 |
// In contrast say we have a pretty expensive operation:
|
455
|
249 |
|
|
250 |
def peop(n: BigInt): Boolean = peop(n + 1)
|
|
251 |
|
|
252 |
val a = "foo"
|
|
253 |
val b = "foo"
|
|
254 |
|
|
255 |
if (a == b || peop(0)) println("true") else println("false")
|
|
256 |
|
|
257 |
// This is called "lazy evaluation":
|
|
258 |
// you delay compuation until it is really
|
|
259 |
// needed. Once calculated though, the result
|
|
260 |
// does not need to be re-calculated.
|
|
261 |
|
|
262 |
// A useful example is
|
|
263 |
|
|
264 |
def time_needed[T](i: Int, code: => T) = {
|
|
265 |
val start = System.nanoTime()
|
|
266 |
for (j <- 1 to i) code
|
|
267 |
val end = System.nanoTime()
|
|
268 |
f"${(end - start) / (i * 1.0e9)}%.6f secs"
|
|
269 |
}
|
|
270 |
|
|
271 |
// A slightly less obvious example: Prime Numbers.
|
|
272 |
// (I do not care how many) primes: 2, 3, 5, 7, 9, 11, 13 ....
|
|
273 |
|
|
274 |
def generatePrimes (s: LazyList[Int]): LazyList[Int] =
|
|
275 |
s.head #:: generatePrimes(s.tail.filter(_ % s.head != 0))
|
|
276 |
|
|
277 |
val primes = generatePrimes(LazyList.from(2))
|
|
278 |
|
|
279 |
// the first 10 primes
|
|
280 |
primes.take(100).toList
|
|
281 |
|
|
282 |
time_needed(1, primes.filter(_ > 100).take(3000).toList)
|
|
283 |
time_needed(1, primes.filter(_ > 100).take(3000).toList)
|
|
284 |
|
|
285 |
// A Stream (LazyList) of successive numbers:
|
|
286 |
|
|
287 |
LazyList.from(2).take(10)
|
|
288 |
LazyList.from(2).take(10).force
|
|
289 |
|
|
290 |
// An Iterative version of the Fibonacci numbers
|
|
291 |
def fibIter(a: BigInt, b: BigInt): LazyList[BigInt] =
|
|
292 |
a #:: fibIter(b, a + b)
|
|
293 |
|
|
294 |
|
|
295 |
fibIter(1, 1).take(10).force
|
|
296 |
fibIter(8, 13).take(10).force
|
|
297 |
|
|
298 |
fibIter(1, 1).drop(10000).take(1)
|
|
299 |
fibIter(1, 1).drop(10000).take(1).force
|
|
300 |
|
|
301 |
|
|
302 |
// LazyLists are good for testing
|
|
303 |
|
|
304 |
|
|
305 |
// Regular expressions - the power of DSLs in Scala
|
|
306 |
// and Laziness
|
|
307 |
//==================================================
|
|
308 |
|
|
309 |
abstract class Rexp
|
|
310 |
case object ZERO extends Rexp // nothing
|
|
311 |
case object ONE extends Rexp // the empty string
|
|
312 |
case class CHAR(c: Char) extends Rexp // a character c
|
|
313 |
case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative r1 + r2
|
|
314 |
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence r1 . r2
|
|
315 |
case class STAR(r: Rexp) extends Rexp // star r*
|
|
316 |
|
|
317 |
|
|
318 |
// some convenience for typing in regular expressions
|
|
319 |
import scala.language.implicitConversions
|
|
320 |
import scala.language.reflectiveCalls
|
|
321 |
|
|
322 |
def charlist2rexp(s: List[Char]): Rexp = s match {
|
|
323 |
case Nil => ONE
|
|
324 |
case c::Nil => CHAR(c)
|
|
325 |
case c::s => SEQ(CHAR(c), charlist2rexp(s))
|
|
326 |
}
|
|
327 |
|
481
|
328 |
given Conversion[String, Rexp] = (s => charlist2rexp(s.toList))
|
|
329 |
|
|
330 |
extension (r: Rexp) {
|
455
|
331 |
def | (s: Rexp) = ALT(r, s)
|
|
332 |
def % = STAR(r)
|
|
333 |
def ~ (s: Rexp) = SEQ(r, s)
|
|
334 |
}
|
|
335 |
|
|
336 |
|
|
337 |
|
|
338 |
//example regular expressions
|
|
339 |
val digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
|
|
340 |
val sign = "+" | "-" | ""
|
|
341 |
val number = sign ~ digit ~ digit.%
|
|
342 |
|
|
343 |
// Task: enumerate exhaustively regular expressions
|
|
344 |
// starting from small ones towards bigger ones.
|
|
345 |
|
|
346 |
// 1st idea: enumerate them all in a Set
|
|
347 |
// up to a level
|
|
348 |
|
|
349 |
def enuml(l: Int, s: String) : Set[Rexp] = l match {
|
494
|
350 |
case 0 => Set(ZERO, ONE) ++ s.map(CHAR(_)).toSet
|
455
|
351 |
case n =>
|
|
352 |
val rs = enuml(n - 1, s)
|
|
353 |
rs ++
|
|
354 |
(for (r1 <- rs; r2 <- rs) yield ALT(r1, r2)) ++
|
|
355 |
(for (r1 <- rs; r2 <- rs) yield SEQ(r1, r2)) ++
|
|
356 |
(for (r1 <- rs) yield STAR(r1))
|
|
357 |
}
|
|
358 |
|
|
359 |
enuml(1, "a")
|
|
360 |
enuml(1, "a").size
|
|
361 |
enuml(2, "a").size
|
470
|
362 |
enuml(3, "a").size
|
|
363 |
enuml(4, "a").size // out of heap space
|
455
|
364 |
|
|
365 |
|
|
366 |
def enum(rs: LazyList[Rexp]) : LazyList[Rexp] =
|
|
367 |
rs #::: enum( (for (r1 <- rs; r2 <- rs) yield ALT(r1, r2)) #:::
|
|
368 |
(for (r1 <- rs; r2 <- rs) yield SEQ(r1, r2)) #:::
|
|
369 |
(for (r1 <- rs) yield STAR(r1)) )
|
|
370 |
|
|
371 |
|
|
372 |
enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(200).force
|
470
|
373 |
enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(5_000_000).force // out of memory
|
455
|
374 |
|
|
375 |
|
|
376 |
def depth(r: Rexp) : Int = r match {
|
|
377 |
case ZERO => 0
|
|
378 |
case ONE => 0
|
|
379 |
case CHAR(_) => 0
|
|
380 |
case ALT(r1, r2) => Math.max(depth(r1), depth(r2)) + 1
|
|
381 |
case SEQ(r1, r2) => Math.max(depth(r1), depth(r2)) + 1
|
|
382 |
case STAR(r1) => depth(r1) + 1
|
|
383 |
}
|
|
384 |
|
|
385 |
|
|
386 |
val is =
|
|
387 |
(enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b')))
|
|
388 |
.dropWhile(depth(_) < 3)
|
|
389 |
.take(10).foreach(println))
|
|
390 |
|
|
391 |
|
384
|
392 |
|
|
393 |
|
|
394 |
|
|
395 |
|
|
396 |
|
|
397 |
|
|
398 |
|
|
399 |
|
|
400 |
|
238
|
401 |
|
222
|
402 |
|
240
|
403 |
// The End ... Almost Christmas
|
238
|
404 |
//===============================
|
|
405 |
|
|
406 |
// I hope you had fun!
|
|
407 |
|
|
408 |
// A function should do one thing, and only one thing.
|
|
409 |
|
|
410 |
// Make your variables immutable, unless there's a good
|
326
|
411 |
// reason not to. Usually there is not.
|
238
|
412 |
|
326
|
413 |
// I did it once, but this is actually not a good reason:
|
240
|
414 |
// generating new labels:
|
|
415 |
|
238
|
416 |
var counter = -1
|
222
|
417 |
|
238
|
418 |
def Fresh(x: String) = {
|
|
419 |
counter += 1
|
|
420 |
x ++ "_" ++ counter.toString()
|
|
421 |
}
|
|
422 |
|
|
423 |
Fresh("x")
|
|
424 |
Fresh("x")
|
|
425 |
|
|
426 |
|
|
427 |
|
326
|
428 |
// I think you can be productive on Day 1, but the
|
|
429 |
// language is deep.
|
238
|
430 |
//
|
|
431 |
// http://scalapuzzlers.com
|
|
432 |
//
|
|
433 |
// http://www.latkin.org/blog/2017/05/02/when-the-scala-compiler-doesnt-help/
|
|
434 |
|
328
|
435 |
val two = 0.2
|
|
436 |
val one = 0.1
|
|
437 |
val eight = 0.8
|
|
438 |
val six = 0.6
|
|
439 |
|
|
440 |
two - one == one
|
|
441 |
eight - six == two
|
329
|
442 |
eight - six
|
328
|
443 |
|
|
444 |
|
329
|
445 |
// problems about equality and type-errors
|
328
|
446 |
|
329
|
447 |
List(1, 2, 3).contains("your cup") // should not compile, but retruns false
|
|
448 |
|
|
449 |
List(1, 2, 3) == Vector(1, 2, 3) // again should not compile, but returns true
|
326
|
450 |
|
238
|
451 |
|
326
|
452 |
|