222
|
1 |
// Scala Lecture 4
|
|
2 |
//=================
|
|
3 |
|
|
4 |
|
|
5 |
// Polymorphic Types
|
|
6 |
//===================
|
|
7 |
|
|
8 |
// You do not want to write functions like contains, first,
|
|
9 |
// length and so on for every type of lists.
|
|
10 |
|
224
|
11 |
|
222
|
12 |
def length_string_list(lst: List[String]): Int = lst match {
|
|
13 |
case Nil => 0
|
|
14 |
case x::xs => 1 + length_string_list(xs)
|
|
15 |
}
|
|
16 |
|
|
17 |
def length_int_list(lst: List[Int]): Int = lst match {
|
|
18 |
case Nil => 0
|
|
19 |
case x::xs => 1 + length_int_list(xs)
|
|
20 |
}
|
|
21 |
|
|
22 |
length_string_list(List("1", "2", "3", "4"))
|
|
23 |
length_int_list(List(1, 2, 3, 4))
|
|
24 |
|
|
25 |
def length[A](lst: List[A]): Int = lst match {
|
|
26 |
case Nil => 0
|
|
27 |
case x::xs => 1 + length(xs)
|
|
28 |
}
|
|
29 |
length(List("1", "2", "3", "4"))
|
|
30 |
length(List(1, 2, 3, 4))
|
|
31 |
|
|
32 |
|
|
33 |
def map[A, B](lst: List[A], f: A => B): List[B] = lst match {
|
|
34 |
case Nil => Nil
|
|
35 |
case x::xs => f(x)::map(xs, f)
|
|
36 |
}
|
|
37 |
|
226
|
38 |
map(List(1, 2, 3, 4), (x: Int) => x.toString)
|
222
|
39 |
|
|
40 |
|
|
41 |
// Remember?
|
|
42 |
def first[A, B](xs: List[A], f: A => Option[B]) : Option[B] = ...
|
|
43 |
|
|
44 |
|
|
45 |
// distinct / distinctBy
|
|
46 |
|
|
47 |
val ls = List(1,2,3,3,2,4,3,2,1)
|
|
48 |
ls.distinct
|
|
49 |
|
226
|
50 |
ls.minBy(_._2)
|
|
51 |
ls.sortBy(_._1)
|
222
|
52 |
|
223
|
53 |
def distinctBy[B, C](xs: List[B],
|
|
54 |
f: B => C,
|
|
55 |
acc: List[C] = Nil): List[B] = xs match {
|
218
|
56 |
case Nil => Nil
|
223
|
57 |
case x::xs => {
|
218
|
58 |
val res = f(x)
|
|
59 |
if (acc.contains(res)) distinctBy(xs, f, acc)
|
|
60 |
else x::distinctBy(xs, f, res::acc)
|
|
61 |
}
|
|
62 |
}
|
|
63 |
|
223
|
64 |
// distinctBy with the identity function is
|
|
65 |
// just distinct
|
222
|
66 |
distinctBy(ls, (x: Int) => x)
|
|
67 |
|
|
68 |
|
|
69 |
val cs = List('A', 'b', 'a', 'c', 'B', 'D', 'd')
|
|
70 |
|
|
71 |
distinctBy(cs, (c:Char) => c.toUpper)
|
|
72 |
|
|
73 |
|
|
74 |
|
|
75 |
// Type inference is local in Scala
|
|
76 |
|
|
77 |
def id[T](x: T) : T = x
|
|
78 |
|
|
79 |
val x = id(322) // Int
|
|
80 |
val y = id("hey") // String
|
226
|
81 |
val z = id(Set[Int](1,2,3,4)) // Set[Int]
|
222
|
82 |
|
|
83 |
|
|
84 |
|
|
85 |
// The type variable concept in Scala can get really complicated.
|
|
86 |
//
|
|
87 |
// - variance (OO)
|
|
88 |
// - bounds (subtyping)
|
|
89 |
// - quantification
|
|
90 |
|
|
91 |
// Java has issues with this too: Java allows
|
223
|
92 |
// to write the following incorrect code, and
|
|
93 |
// only recovers by raising an exception
|
|
94 |
// at runtime.
|
222
|
95 |
|
223
|
96 |
// Object[] arr = new Integer[10];
|
|
97 |
// arr[0] = "Hello World";
|
222
|
98 |
|
|
99 |
|
226
|
100 |
// Scala gives you a compile-time error, which
|
|
101 |
// is much better.
|
222
|
102 |
|
|
103 |
var arr = Array[Int]()
|
|
104 |
arr(0) = "Hello World"
|
|
105 |
|
|
106 |
|
|
107 |
|
|
108 |
|
|
109 |
//
|
|
110 |
// Object Oriented Programming in Scala
|
|
111 |
//
|
|
112 |
// =====================================
|
|
113 |
|
|
114 |
abstract class Animal
|
226
|
115 |
case class Bird(name: String) extends Animal {
|
|
116 |
override def toString = name
|
|
117 |
}
|
222
|
118 |
case class Mammal(name: String) extends Animal
|
|
119 |
case class Reptile(name: String) extends Animal
|
|
120 |
|
226
|
121 |
Bird("Sparrow")
|
|
122 |
|
223
|
123 |
println(Bird("Sparrow"))
|
222
|
124 |
println(Bird("Sparrow").toString)
|
|
125 |
|
|
126 |
|
|
127 |
// you can override methods
|
|
128 |
case class Bird(name: String) extends Animal {
|
|
129 |
override def toString = name
|
|
130 |
}
|
|
131 |
|
|
132 |
|
|
133 |
// There is a very convenient short-hand notation
|
226
|
134 |
// for constructors:
|
222
|
135 |
|
|
136 |
class Fraction(x: Int, y: Int) {
|
|
137 |
def numer = x
|
|
138 |
def denom = y
|
|
139 |
}
|
|
140 |
|
|
141 |
|
|
142 |
case class Fraction(numer: Int, denom: Int)
|
|
143 |
|
|
144 |
val half = Fraction(1, 2)
|
|
145 |
|
|
146 |
half.denom
|
|
147 |
|
|
148 |
|
223
|
149 |
// In mandelbrot.scala I used complex (imaginary) numbers
|
|
150 |
// and implemented the usual arithmetic operations for complex
|
|
151 |
// numbers.
|
222
|
152 |
|
|
153 |
case class Complex(re: Double, im: Double) {
|
|
154 |
// represents the complex number re + im * i
|
|
155 |
def +(that: Complex) = Complex(this.re + that.re, this.im + that.im)
|
|
156 |
def -(that: Complex) = Complex(this.re - that.re, this.im - that.im)
|
|
157 |
def *(that: Complex) = Complex(this.re * that.re - this.im * that.im,
|
|
158 |
this.re * that.im + that.re * this.im)
|
|
159 |
def *(that: Double) = Complex(this.re * that, this.im * that)
|
|
160 |
def abs = Math.sqrt(this.re * this.re + this.im * this.im)
|
|
161 |
}
|
|
162 |
|
|
163 |
val test = Complex(1, 2) + Complex (3, 4)
|
|
164 |
|
|
165 |
// this could have equally been written as
|
|
166 |
val test = Complex(1, 2).+(Complex (3, 4))
|
|
167 |
|
|
168 |
// this applies to all methods, but requires
|
|
169 |
import scala.language.postfixOps
|
|
170 |
|
|
171 |
List(5, 2, 3, 4).sorted
|
|
172 |
List(5, 2, 3, 4) sorted
|
|
173 |
|
|
174 |
|
223
|
175 |
// ...to allow the notation n + m * i
|
222
|
176 |
import scala.language.implicitConversions
|
223
|
177 |
|
226
|
178 |
val i = Complex(0, 1)
|
222
|
179 |
implicit def double2complex(re: Double) = Complex(re, 0)
|
|
180 |
|
|
181 |
|
|
182 |
val inum1 = -2.0 + -1.5 * i
|
|
183 |
val inum2 = 1.0 + 1.5 * i
|
|
184 |
|
|
185 |
|
|
186 |
|
223
|
187 |
// All is public by default....so no public is needed.
|
|
188 |
// You can have the usual restrictions about private
|
|
189 |
// values and methods, if you are MUTABLE !!!
|
222
|
190 |
|
|
191 |
case class BankAccount(init: Int) {
|
|
192 |
|
|
193 |
private var balance = init
|
|
194 |
|
|
195 |
def deposit(amount: Int): Unit = {
|
|
196 |
if (amount > 0) balance = balance + amount
|
|
197 |
}
|
|
198 |
|
|
199 |
def withdraw(amount: Int): Int =
|
|
200 |
if (0 < amount && amount <= balance) {
|
|
201 |
balance = balance - amount
|
|
202 |
balance
|
|
203 |
} else throw new Error("insufficient funds")
|
|
204 |
}
|
|
205 |
|
223
|
206 |
// BUT since we are completely IMMUTABLE, this is
|
|
207 |
// virtually of not concern to us.
|
222
|
208 |
|
|
209 |
|
|
210 |
|
243
|
211 |
// another example about Fractions
|
|
212 |
import scala.language.implicitConversions
|
|
213 |
import scala.language.reflectiveCalls
|
|
214 |
|
|
215 |
|
|
216 |
case class Fraction(numer: Int, denom: Int) {
|
|
217 |
override def toString = numer.toString + "/" + denom.toString
|
|
218 |
|
|
219 |
def +(other: Fraction) = Fraction(numer + other.numer, denom + other.denom)
|
|
220 |
def /(other: Fraction) = Fraction(numer * other.denom, denom * other.numer)
|
|
221 |
def /% (other: Fraction) = Fraction(numer * other.denom, denom * other.numer)
|
|
222 |
|
|
223 |
}
|
|
224 |
|
|
225 |
implicit def Int2Fraction(x: Int) = Fraction(x, 1)
|
|
226 |
|
|
227 |
|
|
228 |
val half = Fraction(1, 2)
|
|
229 |
val third = Fraction (1, 3)
|
|
230 |
|
|
231 |
half + third
|
|
232 |
half / third
|
|
233 |
|
|
234 |
// not sure if one can get this to work
|
|
235 |
// properly, since Scala just cannot find out
|
|
236 |
// if / is for ints or for Fractions
|
|
237 |
(1 / 3) + half
|
|
238 |
(1 / 2) + third
|
|
239 |
|
|
240 |
// either you have to force the Fraction-type by
|
|
241 |
// using a method that is not defined for ints
|
|
242 |
(1 /% 3) + half
|
|
243 |
(1 /% 2) + third
|
|
244 |
|
|
245 |
|
|
246 |
// ...or explicitly give the type in order to allow
|
|
247 |
// Scala to do the conversion to Fractions
|
|
248 |
((1:Fraction) / 3) + half
|
|
249 |
(1 / (3: Fraction)) + half
|
|
250 |
|
222
|
251 |
|
|
252 |
|
|
253 |
// DFAs in Scala
|
226
|
254 |
//===============
|
222
|
255 |
import scala.util.Try
|
218
|
256 |
|
|
257 |
|
222
|
258 |
// A is the state type
|
|
259 |
// C is the input (usually characters)
|
|
260 |
|
223
|
261 |
case class DFA[A, C](start: A, // starting state
|
|
262 |
delta: (A, C) => A, // transition function
|
|
263 |
fins: A => Boolean) { // final states (Set)
|
222
|
264 |
|
|
265 |
def deltas(q: A, s: List[C]) : A = s match {
|
|
266 |
case Nil => q
|
|
267 |
case c::cs => deltas(delta(q, c), cs)
|
|
268 |
}
|
|
269 |
|
|
270 |
def accepts(s: List[C]) : Boolean =
|
|
271 |
Try(fins(deltas(start, s))) getOrElse false
|
|
272 |
}
|
|
273 |
|
|
274 |
// the example shown in the handout
|
|
275 |
abstract class State
|
|
276 |
case object Q0 extends State
|
|
277 |
case object Q1 extends State
|
|
278 |
case object Q2 extends State
|
|
279 |
case object Q3 extends State
|
|
280 |
case object Q4 extends State
|
|
281 |
|
|
282 |
val delta : (State, Char) => State =
|
|
283 |
{ case (Q0, 'a') => Q1
|
|
284 |
case (Q0, 'b') => Q2
|
|
285 |
case (Q1, 'a') => Q4
|
|
286 |
case (Q1, 'b') => Q2
|
|
287 |
case (Q2, 'a') => Q3
|
|
288 |
case (Q2, 'b') => Q2
|
|
289 |
case (Q3, 'a') => Q4
|
|
290 |
case (Q3, 'b') => Q0
|
|
291 |
case (Q4, 'a') => Q4
|
|
292 |
case (Q4, 'b') => Q4
|
|
293 |
case _ => throw new Exception("Undefined") }
|
|
294 |
|
|
295 |
val dfa = DFA(Q0, delta, Set[State](Q4))
|
|
296 |
|
|
297 |
dfa.accepts("abaaa".toList) // true
|
|
298 |
dfa.accepts("bbabaab".toList) // true
|
|
299 |
dfa.accepts("baba".toList) // false
|
|
300 |
dfa.accepts("abc".toList) // false
|
|
301 |
|
223
|
302 |
// another DFA with a Sink state
|
222
|
303 |
abstract class S
|
|
304 |
case object S0 extends S
|
|
305 |
case object S1 extends S
|
|
306 |
case object S2 extends S
|
|
307 |
case object Sink extends S
|
|
308 |
|
|
309 |
// transition function with a sink state
|
223
|
310 |
val sigma : (S, Char) => S =
|
222
|
311 |
{ case (S0, 'a') => S1
|
|
312 |
case (S1, 'a') => S2
|
|
313 |
case _ => Sink
|
|
314 |
}
|
|
315 |
|
|
316 |
val dfa2 = DFA(S0, sigma, Set[S](S2))
|
|
317 |
|
|
318 |
dfa2.accepts("aa".toList) // true
|
|
319 |
dfa2.accepts("".toList) // false
|
|
320 |
dfa2.accepts("ab".toList) // false
|
|
321 |
|
223
|
322 |
// we could also have a dfa for numbers
|
|
323 |
val sigmai : (S, Int) => S =
|
|
324 |
{ case (S0, 1) => S1
|
|
325 |
case (S1, 1) => S2
|
|
326 |
case _ => Sink
|
|
327 |
}
|
|
328 |
|
|
329 |
val dfa3 = DFA(S0, sigmai, Set[S](S2))
|
|
330 |
|
|
331 |
dfa3.accepts(List(1, 1)) // true
|
|
332 |
dfa3.accepts(Nil) // false
|
|
333 |
dfa3.accepts(List(1, 2)) // false
|
|
334 |
|
222
|
335 |
|
|
336 |
|
|
337 |
|
|
338 |
// NFAs (Nondeterministic Finite Automata)
|
|
339 |
|
|
340 |
|
223
|
341 |
case class NFA[A, C](starts: Set[A], // starting states
|
|
342 |
delta: (A, C) => Set[A], // transition function
|
|
343 |
fins: A => Boolean) { // final states
|
222
|
344 |
|
|
345 |
// given a state and a character, what is the set of
|
|
346 |
// next states? if there is none => empty set
|
|
347 |
def next(q: A, c: C) : Set[A] =
|
|
348 |
Try(delta(q, c)) getOrElse Set[A]()
|
|
349 |
|
242
|
350 |
def nexts(qs: Set[A], c: C) : Set[A] =
|
|
351 |
qs.flatMap(next(_, c))
|
|
352 |
|
222
|
353 |
// depth-first version of accepts
|
|
354 |
def search(q: A, s: List[C]) : Boolean = s match {
|
|
355 |
case Nil => fins(q)
|
|
356 |
case c::cs => next(q, c).exists(search(_, cs))
|
|
357 |
}
|
|
358 |
|
|
359 |
def accepts(s: List[C]) : Boolean =
|
|
360 |
starts.exists(search(_, s))
|
|
361 |
}
|
|
362 |
|
|
363 |
|
|
364 |
|
|
365 |
// NFA examples
|
|
366 |
|
|
367 |
val nfa_trans1 : (State, Char) => Set[State] =
|
|
368 |
{ case (Q0, 'a') => Set(Q0, Q1)
|
|
369 |
case (Q0, 'b') => Set(Q2)
|
|
370 |
case (Q1, 'a') => Set(Q1)
|
|
371 |
case (Q2, 'b') => Set(Q2) }
|
|
372 |
|
|
373 |
val nfa = NFA(Set[State](Q0), nfa_trans1, Set[State](Q2))
|
|
374 |
|
|
375 |
nfa.accepts("aa".toList) // false
|
|
376 |
nfa.accepts("aaaaa".toList) // false
|
|
377 |
nfa.accepts("aaaaab".toList) // true
|
|
378 |
nfa.accepts("aaaaabbb".toList) // true
|
|
379 |
nfa.accepts("aaaaabbbaaa".toList) // false
|
|
380 |
nfa.accepts("ac".toList) // false
|
|
381 |
|
|
382 |
|
223
|
383 |
// Q: Why the kerfuffle about the polymorphic types in DFAs/NFAs?
|
226
|
384 |
// A: Subset construction. Here the state type for the DFA is
|
|
385 |
// sets of states.
|
222
|
386 |
|
|
387 |
def subset[A, C](nfa: NFA[A, C]) : DFA[Set[A], C] = {
|
|
388 |
DFA(nfa.starts,
|
|
389 |
{ case (qs, c) => nfa.nexts(qs, c) },
|
|
390 |
_.exists(nfa.fins))
|
|
391 |
}
|
|
392 |
|
|
393 |
subset(nfa1).accepts("aa".toList) // false
|
|
394 |
subset(nfa1).accepts("aaaaa".toList) // false
|
|
395 |
subset(nfa1).accepts("aaaaab".toList) // true
|
|
396 |
subset(nfa1).accepts("aaaaabbb".toList) // true
|
|
397 |
subset(nfa1).accepts("aaaaabbbaaa".toList) // false
|
|
398 |
subset(nfa1).accepts("ac".toList) // false
|
|
399 |
|
|
400 |
|
|
401 |
|
|
402 |
|
|
403 |
|
|
404 |
|
|
405 |
|
|
406 |
// Cool Stuff in Scala
|
|
407 |
//=====================
|
|
408 |
|
|
409 |
|
|
410 |
// Implicits or How to Pimp my Library
|
|
411 |
//=====================================
|
|
412 |
//
|
|
413 |
// For example adding your own methods to Strings:
|
|
414 |
// Imagine you want to increment strings, like
|
|
415 |
//
|
|
416 |
// "HAL".increment
|
|
417 |
//
|
|
418 |
// you can avoid ugly fudges, like a MyString, by
|
|
419 |
// using implicit conversions.
|
|
420 |
|
|
421 |
|
|
422 |
implicit class MyString(s: String) {
|
|
423 |
def increment = for (c <- s) yield (c + 1).toChar
|
|
424 |
}
|
|
425 |
|
|
426 |
"HAL".increment
|
|
427 |
|
|
428 |
|
278
|
429 |
// Abstract idea:
|
|
430 |
// In that version implicit conversions were used to solve the
|
|
431 |
// late extension problem; namely, given a class C and a class T,
|
|
432 |
// how to have C extend T without touching or recompiling C.
|
|
433 |
// Conversions add a wrapper when a member of T is requested
|
|
434 |
// from an instance of C.
|
|
435 |
|
319
|
436 |
//Another example (TimeUnit in 2.13?)
|
278
|
437 |
|
|
438 |
case class Duration(time: Long, unit: TimeUnit) {
|
|
439 |
def +(o: Duration) = Duration(time + unit.convert(o.time, o.unit), unit)
|
|
440 |
}
|
|
441 |
|
|
442 |
implicit class Int2Duration(that: Int) {
|
|
443 |
def seconds = new Duration(that, SECONDS)
|
|
444 |
def minutes = new Duration(that, MINUTES)
|
|
445 |
}
|
|
446 |
|
|
447 |
5.seconds + 2.minutes //Duration(125L, SECONDS )
|
|
448 |
|
|
449 |
|
222
|
450 |
|
|
451 |
// Regular expressions - the power of DSLs in Scala
|
|
452 |
//==================================================
|
|
453 |
|
|
454 |
abstract class Rexp
|
226
|
455 |
case object ZERO extends Rexp // nothing
|
|
456 |
case object ONE extends Rexp // the empty string
|
|
457 |
case class CHAR(c: Char) extends Rexp // a character c
|
|
458 |
case class ALT(r1: Rexp, r2: Rexp) extends Rexp // alternative r1 + r2
|
|
459 |
case class SEQ(r1: Rexp, r2: Rexp) extends Rexp // sequence r1 . r2
|
|
460 |
case class STAR(r: Rexp) extends Rexp // star r*
|
222
|
461 |
|
|
462 |
|
|
463 |
|
226
|
464 |
// writing (ab)* in the format above is
|
|
465 |
// tedious
|
222
|
466 |
val r0 = STAR(SEQ(CHAR('a'), CHAR('b')))
|
|
467 |
|
|
468 |
|
|
469 |
// some convenience for typing in regular expressions
|
|
470 |
import scala.language.implicitConversions
|
|
471 |
import scala.language.reflectiveCalls
|
|
472 |
|
|
473 |
def charlist2rexp(s: List[Char]): Rexp = s match {
|
|
474 |
case Nil => ONE
|
|
475 |
case c::Nil => CHAR(c)
|
|
476 |
case c::s => SEQ(CHAR(c), charlist2rexp(s))
|
|
477 |
}
|
224
|
478 |
implicit def string2rexp(s: String): Rexp =
|
|
479 |
charlist2rexp(s.toList)
|
222
|
480 |
|
|
481 |
|
|
482 |
val r1 = STAR("ab")
|
|
483 |
val r2 = STAR(ALT("ab", "baa baa black sheep"))
|
|
484 |
val r3 = STAR(SEQ("ab", ALT("a", "b")))
|
|
485 |
|
|
486 |
implicit def RexpOps (r: Rexp) = new {
|
|
487 |
def | (s: Rexp) = ALT(r, s)
|
|
488 |
def % = STAR(r)
|
|
489 |
def ~ (s: Rexp) = SEQ(r, s)
|
|
490 |
}
|
|
491 |
|
226
|
492 |
|
222
|
493 |
implicit def stringOps (s: String) = new {
|
|
494 |
def | (r: Rexp) = ALT(s, r)
|
|
495 |
def | (r: String) = ALT(s, r)
|
|
496 |
def % = STAR(s)
|
|
497 |
def ~ (r: Rexp) = SEQ(s, r)
|
|
498 |
def ~ (r: String) = SEQ(s, r)
|
|
499 |
}
|
|
500 |
|
|
501 |
//example regular expressions
|
|
502 |
val digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
|
|
503 |
val sign = "+" | "-" | ""
|
|
504 |
val number = sign ~ digit ~ digit.%
|
|
505 |
|
|
506 |
|
|
507 |
|
|
508 |
// Lazy Evaluation
|
|
509 |
//=================
|
|
510 |
//
|
226
|
511 |
// Do not evaluate arguments just yet:
|
|
512 |
// this uses the => in front of the type
|
|
513 |
// of the code-argument
|
222
|
514 |
|
|
515 |
def time_needed[T](i: Int, code: => T) = {
|
|
516 |
val start = System.nanoTime()
|
|
517 |
for (j <- 1 to i) code
|
|
518 |
val end = System.nanoTime()
|
|
519 |
(end - start)/(i * 1.0e9)
|
|
520 |
}
|
|
521 |
|
|
522 |
// same examples using the internal regexes
|
|
523 |
val evil = "(a*)*b"
|
|
524 |
|
|
525 |
("a" * 10 ++ "b").matches(evil)
|
|
526 |
("a" * 10).matches(evil)
|
|
527 |
("a" * 10000).matches(evil)
|
|
528 |
("a" * 20000).matches(evil)
|
226
|
529 |
("a" * 50000).matches(evil)
|
222
|
530 |
|
226
|
531 |
time_needed(1, ("a" * 50000).matches(evil))
|