author | Christian Urban <christian.urban@kcl.ac.uk> |
Wed, 25 Nov 2020 17:39:20 +0000 | |
changeset 371 | 14f2bd9db45b |
parent 366 | 1c829680503e |
child 374 | 90b267768329 |
permissions | -rw-r--r-- |
67 | 1 |
// Scala Lecture 3 |
2 |
//================= |
|
3 |
||
320 | 4 |
|
343 | 5 |
// naive quicksort with "On" function |
6 |
||
7 |
def sortOn(f: Int => Int, xs: List[Int]) : List[Int] = { |
|
8 |
if (xs.size < 2) xs |
|
9 |
else { |
|
10 |
val pivot = xs.head |
|
11 |
val (left, right) = xs.partition(f(_) < f(pivot)) |
|
12 |
sortOn(f, left) ::: pivot :: sortOn(f, right.tail) |
|
13 |
} |
|
14 |
} |
|
15 |
||
16 |
sortOn(identity, List(99,99,99,98,10,-3,2)) |
|
17 |
sortOn(n => - n, List(99,99,99,98,10,-3,2)) |
|
18 |
||
19 |
||
320 | 20 |
// Recursion Again ;o) |
21 |
//==================== |
|
22 |
||
217 | 23 |
|
366 | 24 |
// another well-known example: Towers of Hanoi |
25 |
//============================================= |
|
178 | 26 |
|
320 | 27 |
def move(from: Char, to: Char) = |
28 |
println(s"Move disc from $from to $to!") |
|
67 | 29 |
|
320 | 30 |
def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = { |
31 |
if (n == 0) () |
|
32 |
else { |
|
33 |
hanoi(n - 1, from, to, via) |
|
34 |
move(from, to) |
|
35 |
hanoi(n - 1, via, from, to) |
|
36 |
} |
|
37 |
} |
|
67 | 38 |
|
320 | 39 |
hanoi(4, 'A', 'B', 'C') |
67 | 40 |
|
155 | 41 |
|
42 |
||
320 | 43 |
// User-defined Datatypes |
44 |
//======================== |
|
45 |
||
323 | 46 |
abstract class Tree |
47 |
case class Leaf(x: Int) extends Tree |
|
48 |
case class Node(s: String, left: Tree, right: Tree) extends Tree |
|
49 |
||
366 | 50 |
val lf = Leaf(20) |
51 |
val tr = Node("foo", Leaf(10), Leaf(23)) |
|
320 | 52 |
|
366 | 53 |
val lst : List[Tree] = List(lf, tr) |
54 |
||
55 |
||
56 |
abstract class Colour |
|
320 | 57 |
case object Red extends Colour |
58 |
case object Green extends Colour |
|
59 |
case object Blue extends Colour |
|
323 | 60 |
case object Yellow extends Colour |
320 | 61 |
|
62 |
||
63 |
def fav_colour(c: Colour) : Boolean = c match { |
|
64 |
case Green => true |
|
323 | 65 |
case _ => false |
320 | 66 |
} |
67 |
||
366 | 68 |
fav_colour(Blue) |
69 |
||
320 | 70 |
|
71 |
// ... a tiny bit more useful: Roman Numerals |
|
72 |
||
321 | 73 |
sealed abstract class RomanDigit |
320 | 74 |
case object I extends RomanDigit |
75 |
case object V extends RomanDigit |
|
76 |
case object X extends RomanDigit |
|
77 |
case object L extends RomanDigit |
|
78 |
case object C extends RomanDigit |
|
79 |
case object D extends RomanDigit |
|
80 |
case object M extends RomanDigit |
|
81 |
||
82 |
type RomanNumeral = List[RomanDigit] |
|
83 |
||
366 | 84 |
List(X,I,M,A) |
320 | 85 |
|
86 |
/* |
|
87 |
I -> 1 |
|
88 |
II -> 2 |
|
89 |
III -> 3 |
|
90 |
IV -> 4 |
|
91 |
V -> 5 |
|
92 |
VI -> 6 |
|
93 |
VII -> 7 |
|
94 |
VIII -> 8 |
|
95 |
IX -> 9 |
|
96 |
X -> 10 |
|
97 |
*/ |
|
98 |
||
99 |
def RomanNumeral2Int(rs: RomanNumeral): Int = rs match { |
|
100 |
case Nil => 0 |
|
101 |
case M::r => 1000 + RomanNumeral2Int(r) |
|
102 |
case C::M::r => 900 + RomanNumeral2Int(r) |
|
103 |
case D::r => 500 + RomanNumeral2Int(r) |
|
104 |
case C::D::r => 400 + RomanNumeral2Int(r) |
|
105 |
case C::r => 100 + RomanNumeral2Int(r) |
|
106 |
case X::C::r => 90 + RomanNumeral2Int(r) |
|
107 |
case L::r => 50 + RomanNumeral2Int(r) |
|
108 |
case X::L::r => 40 + RomanNumeral2Int(r) |
|
109 |
case X::r => 10 + RomanNumeral2Int(r) |
|
110 |
case I::X::r => 9 + RomanNumeral2Int(r) |
|
111 |
case V::r => 5 + RomanNumeral2Int(r) |
|
112 |
case I::V::r => 4 + RomanNumeral2Int(r) |
|
113 |
case I::r => 1 + RomanNumeral2Int(r) |
|
114 |
} |
|
115 |
||
116 |
RomanNumeral2Int(List(I,V)) // 4 |
|
117 |
RomanNumeral2Int(List(I,I,I,I)) // 4 (invalid Roman number) |
|
118 |
RomanNumeral2Int(List(V,I)) // 6 |
|
119 |
RomanNumeral2Int(List(I,X)) // 9 |
|
120 |
RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979 |
|
121 |
RomanNumeral2Int(List(M,M,X,V,I,I)) // 2017 |
|
122 |
||
123 |
||
366 | 124 |
// expressions (essentially trees) |
125 |
||
126 |
abstract class Exp |
|
127 |
case class N(n: Int) extends Exp // for numbers |
|
128 |
case class Plus(e1: Exp, e2: Exp) extends Exp |
|
129 |
case class Times(e1: Exp, e2: Exp) extends Exp |
|
130 |
||
131 |
def string(e: Exp) : String = e match { |
|
132 |
case N(n) => s"$n" |
|
133 |
case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})" |
|
134 |
case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})" |
|
135 |
} |
|
136 |
||
137 |
val e = Plus(N(9), Times(N(3), N(4))) |
|
138 |
e.toString |
|
139 |
println(string(e)) |
|
140 |
||
141 |
def eval(e: Exp) : Int = e match { |
|
142 |
case N(n) => n |
|
143 |
case Plus(e1, e2) => eval(e1) + eval(e2) |
|
144 |
case Times(e1, e2) => eval(e1) * eval(e2) |
|
145 |
} |
|
146 |
||
147 |
println(eval(e)) |
|
148 |
||
149 |
// simplification rules: |
|
150 |
// e + 0, 0 + e => e |
|
151 |
// e * 0, 0 * e => 0 |
|
152 |
// e * 1, 1 * e => e |
|
153 |
// |
|
154 |
// (....9 ....) |
|
155 |
||
156 |
def simp(e: Exp) : Exp = e match { |
|
157 |
case N(n) => N(n) |
|
158 |
case Plus(e1, e2) => (simp(e1), simp(e2)) match { |
|
159 |
case (N(0), e2s) => e2s |
|
160 |
case (e1s, N(0)) => e1s |
|
161 |
case (e1s, e2s) => Plus(e1s, e2s) |
|
162 |
} |
|
163 |
case Times(e1, e2) => (simp(e1), simp(e2)) match { |
|
164 |
case (N(0), _) => N(0) |
|
165 |
case (_, N(0)) => N(0) |
|
166 |
case (N(1), e2s) => e2s |
|
167 |
case (e1s, N(1)) => e1s |
|
168 |
case (e1s, e2s) => Times(e1s, e2s) |
|
169 |
} |
|
170 |
} |
|
171 |
||
172 |
||
173 |
val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9))) |
|
174 |
println(string(e2)) |
|
175 |
println(string(simp(e2))) |
|
176 |
||
177 |
||
178 |
||
320 | 179 |
// String interpolations as patterns |
180 |
||
181 |
val date = "2019-11-26" |
|
182 |
val s"$year-$month-$day" = date |
|
183 |
||
184 |
def parse_date(date: String) : Option[(Int, Int, Int)]= date match { |
|
185 |
case s"$year-$month-$day" => Some((day.toInt, month.toInt, year.toInt)) |
|
186 |
case s"$day/$month/$year" => Some((day.toInt, month.toInt, year.toInt)) |
|
187 |
case s"$day.$month.$year" => Some((day.toInt, month.toInt, year.toInt)) |
|
188 |
case _ => None |
|
189 |
} |
|
318 | 190 |
|
320 | 191 |
parse_date("2019-11-26") |
192 |
parse_date("26/11/2019") |
|
193 |
parse_date("26.11.2019") |
|
194 |
||
195 |
||
196 |
||
197 |
||
198 |
||
199 |
// Tail recursion |
|
200 |
//================ |
|
201 |
||
202 |
||
203 |
def fact(n: Long): Long = |
|
204 |
if (n == 0) 1 else n * fact(n - 1) |
|
205 |
||
206 |
def factB(n: BigInt): BigInt = |
|
207 |
if (n == 0) 1 else n * factB(n - 1) |
|
208 |
||
209 |
factB(100000) |
|
210 |
||
211 |
fact(10) //ok |
|
212 |
fact(10000) // produces a stackoverflow |
|
213 |
||
214 |
def factT(n: BigInt, acc: BigInt): BigInt = |
|
215 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
216 |
||
217 |
factT(10, 1) |
|
218 |
println(factT(100000, 1)) |
|
219 |
||
220 |
// there is a flag for ensuring a function is tail recursive |
|
221 |
import scala.annotation.tailrec |
|
222 |
||
223 |
@tailrec |
|
224 |
def factT(n: BigInt, acc: BigInt): BigInt = |
|
225 |
if (n == 0) acc else factT(n - 1, n * acc) |
|
226 |
||
227 |
||
228 |
||
229 |
// for tail-recursive functions the Scala compiler |
|
230 |
// generates loop-like code, which does not need |
|
231 |
// to allocate stack-space in each recursive |
|
232 |
// call; Scala can do this only for tail-recursive |
|
233 |
// functions |
|
234 |
||
366 | 235 |
|
236 |
||
237 |
||
238 |
// Sudoku |
|
239 |
//======== |
|
240 |
||
241 |
||
242 |
type Pos = (Int, Int) |
|
243 |
val emptyValue = '.' |
|
244 |
val maxValue = 9 |
|
245 |
||
246 |
val allValues = "123456789".toList |
|
247 |
val indexes = (0 to 8).toList |
|
248 |
||
249 |
||
250 |
def empty(game: String) = game.indexOf(emptyValue) |
|
251 |
def isDone(game: String) = empty(game) == -1 |
|
252 |
def emptyPosition(game: String) : Pos = |
|
253 |
(empty(game) % maxValue, empty(game) / maxValue) |
|
254 |
||
255 |
||
256 |
def get_row(game: String, y: Int) = indexes.map(col => game(y * maxValue + col)) |
|
257 |
def get_col(game: String, x: Int) = indexes.map(row => game(x + row * maxValue)) |
|
258 |
||
259 |
def get_box(game: String, pos: Pos): List[Char] = { |
|
260 |
def base(p: Int): Int = (p / 3) * 3 |
|
261 |
val x0 = base(pos._1) |
|
262 |
val y0 = base(pos._2) |
|
263 |
for (x <- (x0 until x0 + 3).toList; |
|
264 |
y <- (y0 until y0 + 3).toList) yield game(x + y * maxValue) |
|
265 |
} |
|
266 |
||
267 |
||
268 |
def update(game: String, pos: Int, value: Char): String = |
|
269 |
game.updated(pos, value) |
|
270 |
||
271 |
def toAvoid(game: String, pos: Pos): List[Char] = |
|
272 |
(get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos)) |
|
273 |
||
274 |
def candidates(game: String, pos: Pos): List[Char] = |
|
275 |
allValues.diff(toAvoid(game, pos)) |
|
276 |
||
277 |
def search(game: String): List[String] = { |
|
278 |
if (isDone(game)) List(game) |
|
279 |
else |
|
280 |
candidates(game, emptyPosition(game)).par. |
|
281 |
map(c => search(update(game, empty(game), c))).toList.flatten |
|
282 |
} |
|
283 |
||
284 |
def search1T(games: List[String]): Option[String] = games match { |
|
285 |
case Nil => None |
|
286 |
case game::rest => { |
|
287 |
if (isDone(game)) Some(game) |
|
288 |
else { |
|
289 |
val cs = candidates(game, emptyPosition(game)) |
|
290 |
search1T(cs.map(c => update(game, empty(game), c)) ::: rest) |
|
291 |
} |
|
292 |
} |
|
293 |
} |
|
294 |
||
295 |
def pretty(game: String): String = |
|
296 |
"\n" + (game.sliding(maxValue, maxValue).mkString(",\n")) |
|
297 |
||
298 |
||
155 | 299 |
// tail recursive version that searches |
158 | 300 |
// for all solutions |
301 |
||
155 | 302 |
def searchT(games: List[String], sols: List[String]): List[String] = games match { |
303 |
case Nil => sols |
|
304 |
case game::rest => { |
|
305 |
if (isDone(game)) searchT(rest, game::sols) |
|
306 |
else { |
|
307 |
val cs = candidates(game, emptyPosition(game)) |
|
308 |
searchT(cs.map(c => update(game, empty(game), c)) ::: rest, sols) |
|
309 |
} |
|
310 |
} |
|
67 | 311 |
} |
312 |
||
158 | 313 |
searchT(List(game3), List()).map(pretty) |
314 |
||
315 |
||
155 | 316 |
// tail recursive version that searches |
317 |
// for a single solution |
|
158 | 318 |
|
155 | 319 |
def search1T(games: List[String]): Option[String] = games match { |
67 | 320 |
case Nil => None |
155 | 321 |
case game::rest => { |
322 |
if (isDone(game)) Some(game) |
|
323 |
else { |
|
324 |
val cs = candidates(game, emptyPosition(game)) |
|
325 |
search1T(cs.map(c => update(game, empty(game), c)) ::: rest) |
|
326 |
} |
|
327 |
} |
|
67 | 328 |
} |
329 |
||
158 | 330 |
search1T(List(game3)).map(pretty) |
217 | 331 |
time_needed(10, search1T(List(game3))) |
332 |
||
158 | 333 |
|
155 | 334 |
// game with multiple solutions |
335 |
val game3 = """.8...9743 |
|
336 |
|.5...8.1. |
|
337 |
|.1....... |
|
338 |
|8....5... |
|
339 |
|...8.4... |
|
340 |
|...3....6 |
|
341 |
|.......7. |
|
342 |
|.3.5...8. |
|
343 |
|9724...5.""".stripMargin.replaceAll("\\n", "") |
|
344 |
||
158 | 345 |
searchT(List(game3), Nil).map(pretty) |
155 | 346 |
search1T(List(game3)).map(pretty) |
67 | 347 |
|
77
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
348 |
// Moral: Whenever a recursive function is resource-critical |
158 | 349 |
// (i.e. works with large recursion depth), then you need to |
77
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
350 |
// write it in tail-recursive fashion. |
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
351 |
// |
155 | 352 |
// Unfortuantely, Scala because of current limitations in |
353 |
// the JVM is not as clever as other functional languages. It can |
|
77
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
354 |
// only optimise "self-tail calls". This excludes the cases of |
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
355 |
// multiple functions making tail calls to each other. Well, |
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
356 |
// nothing is perfect. |
3cbe3d90b77f
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
73
diff
changeset
|
357 |