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