forked from oucs-cosc346-s2-2018/lab05-polymorphism
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab05.html
More file actions
1899 lines (1733 loc) · 111 KB
/
lab05.html
File metadata and controls
1899 lines (1733 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>COSC346 Week 5 - Polymorphism</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="http://cs.otago.ac.nz/cosc346/labs/phplabbook/labbookswift.css">
<link rel="stylesheet" type="text/css" href="http://cs.otago.ac.nz/cosc346/labs/cosc346labstyle.css">
<script src="http://cs.otago.ac.nz/cosc346/labs/jquery-1.11.1.min.js"></script>
<script src="http://cs.otago.ac.nz/cosc346/labs/toc.min.js"></script>
<script src="http://cs.otago.ac.nz/cosc346/labs/cosc346labscript.js"></script>
</head>
<body>
<!-- Banner -->
<div class="banner">
<a href="http://cs.otago.ac.nz/cosc346/labs/../labs.php">COSC346 - Object Oriented Programming and User Interfaces</a>
</div>
<!-- Lab title -->
<h1>Week 5—Polymorphism</h1>
<!-- Table of Contents -->
<div id="toc"></div>
<h2>Goals</h2>
<div class="block">
<ul class="toplist">
<ul class="toplist">
<li>To rewrite our Simple Container Library using generics</li>
<li>To get some practice with the use of protocols</li>
<li>To create a parser for evaluating fraction and complex number expressions</li>
</ul>
</ul>
</div>
<h2>Preparation</h2>
<div class="block">
<ul class="toplist">
<li>Complete Lab 3—you'll be using the Fraction and Complex classes from that lab
<li>Complete Lab 4—you'll be modifying the Simple Container Library I from that lab
<li>From Apple's "The Swift Programming Language" read:
<ul>
<li><a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html">Protocols</a></li>
<li><a href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html">Generics</a></li>
</ul>
</li>
</ul>
</div>
<h2>Simple Container Library III</h2>
<div class="block">
<p>
The SCL library you developed in the previous lab is capable of storing objects/items of <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> type. In this exercise, you'll be modifying the first version of the library, SCL I, to use generic types in place of the <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> type.
</p>
<h3><em><span class="swiftcode"><span class="swiftclass">Any</span></span></em></h3>
<p>
In the previous lab, <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> type was used to refer to a variable that can take any type. However, <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> is not really a type—it's a protocol. Protocols are a bit like interfaces in Java—they specify methods, but don't implement them. In Swift protocols function a bit like abstract classes. A class that includes a protocol through inheritance relationship must implement the methods listed in the protocol (just like it would if it was inheriting from an abstract class). An object of such class can up-cast its type to the protocol it inherits from. Also, multiple inheritance from protocols is allowed in Swift—there is no <em>diamond of death</em> problem as the methods given by the protocol are all abstract. <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> is a protocol that doesn't specify any methods—any type conforms to that protocol, and so any type can be up-cast to <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em>. Of course, once up-cast to <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em>, there's not much that the compiler will allow to be done with that object. The <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> protocol doesn't specify any methods that can be used on the corresponding object. That's why objects removed from SCL containers had to be down-cast to their original type in order to invoke their methods. There will be a bit more about protocols in the second part of this exercise. In this part, you'll modify SCL library to use a generic type instead of <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em>.
</p>
<h3>Generics</h3>
<p>
The need for down-casting <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> to an object's proper type when removing items from SCL containers is quite inelegant. Coupled with the fact that different types of objects can be stored in the same list, since <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> works with any type, this makes for an SCL library that is quite prone to errors. It's possible for a programmer, an SCL library user, to fetch an object from SCL container and force down-casts to an incorrect type, causing a run-time error. It would be better if there was no need to down-cast at all. This is exactly the type of problem that <em>generic</em> types are meant to solve.
</p>
<p>
A generic type is kind of a template, a place holder that corresponds to an unspecified type. This unspecified type can be used in class signatures allowing the object user to specify the type they are after.
</p>
<h3>Generic LinkedList</h3>
<p>
Below is a visualisation of differences between the <em>LinkedList.swift</em> from the previous lab, and one where <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em> is replaced with a generic type. The code to be removed is shown in red (with a strike line across), and the code to be inserted is shown in blue (underlined). The usual Swift syntax colouring is turned off to make the differences stand out. Do not copy and paste this into Xcode—it will not compile. What you have to do is to create a new Xcode project and add a copy of <a href="https://raw.githubusercontent.com/oucs-cosc346-s2-2018/lab04-inheritance-and-composition/master/code/01/LinkedList.swift">LinkedList.swift</a> file from the previous lab. Then, make the changes according to the modifications shown below:
</p>
<div class="codeblock">
<div class="codeblocktitle">Differences between two versions of LinkedList.swift </div>
<pre class="filediff">
/**
A list node containing a reference to an object
and a reference to the next node
*/
class Node<ins><T></ins> {
// STORED PROPERTIES
var object: <del>Any</del><ins>T</ins> //Reference to the listed object
var next : Node<ins><T></ins>? //Optional reference to the next node
// INITIALISERS
/**
Designated initialiser
- parameter object: Object referenced by the node
*/
init(object: <del>Any</del><ins>T</ins>) {
self.object = object
// By default, this node
// doesn't have a next node
// to point to
self.next = nil;
}
}
/**
Linked list of objects
*/
class LinkedList<ins><U></ins> : CustomStringConvertible {
// STORED PROPERTIES
var head: Node<ins><U></ins>? // Reference to the head node
var tail: Node<ins><U></ins>? // Reference to the tail node
// COMPUTED PROPERTIES
/**
Checks if list is empty
- returns: Bool True if list is empty, false otherwise.
*/
var empty: Bool {
if tail != nil {
return false
} else {
return true
}
}
/**
Counts the number of the items in the list
- returns: Int Number of items in the list.
*/
var count: Int {
var nodeCount: Int = 0
//Starting with the head, walk
//through the list until the next
//node points to nil
var node: Node<ins><U></ins>? = head;
while let n = node {
//Count the node
nodeCount += 1
//Get the reference to the next node
node = n.next
}
return nodeCount
}
/**
String representation of the list
- returns: String String representation of the list.
*/
var description: String {
//The beginning of the list is marked
//with the left-square bracket
var descStr: String = "["
//Walk through all the nodes and a string
//representation of each object's contents
//to descStr
var node: Node<ins><U></ins>? = head
while let n = node {
descStr += "\(n.object)"
node = n.next
if(node != nil) {
descStr += ", "
}
}
//Close the description string
//with the right-square bracket
descStr += "]"
return descStr
}
// INITIALISERS
/**
Designated initialiser
- parameter list: Linked list to initialise with (nil by default)
*/
init(list: LinkedList<ins><U></ins>? = nil) {
//Set the list to empy
self.head = nil
self.tail = nil
//If argument is not nil, then
//add objects from that list to
//this one
if let newList = list {
var node: Node<ins><U></ins>? = newList.head
while let n = node {
self.add(object: n.object)
node = n.next
}
}
}
// METHODS
/**
Adds an object to the list
- parameter object: Object to add to the list
*/
func add(object: <del>Any</del><ins>U</ins>) {
//Create a new node pointing to the
//object to be added
let node: Node<ins><U></ins> = Node<ins><U></ins>(object: object)
//Add the node to the list
if let t = tail {
// If list is not empty, point its
// last node to the new node and
// point the tail to the new node
t.next = node
tail = node
} else {
// If list is empty, point the
// head and tail to the new node
head = node
tail = node
}
}
/**
Removes a node from list
- parameter node: Node to remove from the list
- returns: Bool True if node found in the list and removed,
false otherwise.
*/
func remove(node: Node<ins><U></ins>) -> Bool {
var nodeFound = false
//Find the node preceding the one
//to be removed - list is not double
//linked, so we need to walk through it
//form the head until we find the node
//with next link to the node to be removed
var prevNode: Node<ins><U></ins>? = nil
var nextNode: Node<ins><U></ins>? = head
while let n = nextNode {
//Check if next node is the node
//to be removed...the === is an
//address comparison operator;
//the n is the unwrapped
//optional
if(n === node) {
nodeFound = true
break;
}
prevNode = nextNode;
nextNode = n.next
}
if nextNode !== node {
prevNode = nil;
}
// If node to be removed is
// the last one in the list,
// set tail to the previous node,
if tail === node {
nodeFound = true
if let n = prevNode {
n.next = nil
}
tail = prevNode
prevNode = nil
}
// If the list is empty,
// set head to nil as well
if tail == nil {
head = nil
}
// If node to be removed is
// the first one in the list,
// set head to the next node
if head === node {
nodeFound = true
head = node.next
}
// If head points to nil,
// then we have empty list
// and need to set tail accordingly
if head == nil {
tail = nil
}
// Relink the node preceeding
// the one that we are removing
// to the node following the one
// that we are removing
if let n = prevNode {
n.next = node.next
}
return nodeFound
}
/**
Removes all objects from the list
*/
func removeAll() {
head = nil
tail = nil
}
}
</pre>
</div>
<p>
In the new version of <em>LinkedList.swift</em>, <em><span class="swiftcode">Node<T></span></em> is a class with generic type <em><span class="swiftcode">T</span></em>. T corresponds to the type of the object referenced by the node. Note that the "next" property references a node of the same generic type. This means, nodes can link only to nodes that hold objects of the same type (resulting list must contain items of the same type). The <em><span class="swiftcode">LinkedList<U></span></em> is a class with generic type <em><span class="swiftcode">U</span></em>. The tail and head nodes specify the type of the object contained by these nodes—that type is U. So, the <em><span class="swiftcode">T</span></em> in the instances of <em><span class="swiftcode">Node<T></span></em> created inside <em><span class="swiftcode">LinkedList<U></span></em> is mapped to generic type <em><span class="swiftcode">U</span></em>.
</p>
<p>Write the following program in <em>main.swift</em>—it's a modified version of the testing code from the previous lab. <em><span class="swiftcode">LinkedList</span></em> is now defined as <em><span class="swiftcode">LinkedList<<span class="swiftclass">String</span>></span></em>. The new definition maps the generic type <em><span class="swiftcode">U</span></em> to <em><span class="swiftcode">Sring</span></em>. The instantiated list can hold <em><span class="swiftcode"><span class="swiftclass">String</span></span></em>s only.
</p>
<div class="codeblock">
<div class="codeblocktitle"><a href="code/01/main.swift">main.swift</a></div>
<pre class="linenumbers unselectable" style="float: left;">01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
</pre><pre class="code">
<span class="swiftcode"><span class="swiftkeyword">import</span> Foundation</span>
<span class="swiftcode"></span>
<span class="swiftcode"><span class="swiftkeyword">let</span> str1: <span class="swiftclass">String</span> = <span class="swiftstring">"Item V"</span>;</span>
<span class="swiftcode"><span class="swiftkeyword">let</span> str2: <span class="swiftclass">String</span> = <span class="swiftstring">"Item E"</span>;</span>
<span class="swiftcode"><span class="swiftkeyword">let</span> str3: <span class="swiftclass">String</span> = <span class="swiftstring">"Item S"</span>;</span>
<span class="swiftcode"><span class="swiftkeyword">let</span> str4: <span class="swiftclass">String</span> = <span class="swiftstring">"Item M"</span>;</span>
<span class="swiftcode"></span>
<span class="swiftcode"><span class="swiftkeyword">var</span> list: LinkedList<<span class="swiftclass">String</span>> = LinkedList<<span class="swiftclass">String</span>>()</span>
<span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"</span></span><span class="codeswift">\<span class="swiftstring">(</span>list<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span>
<span class="swiftcode"></span>
<span class="swiftcode">list.add(object: str1)</span>
<span class="swiftcode">list.add(object: str2)</span>
<span class="swiftcode">list.add(object: str3)</span>
<span class="swiftcode">list.add(object: str4)</span>
<span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"</span></span><span class="codeswift">\<span class="swiftstring">(</span>list<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span>
</pre>
</div>
<p>
Make sure the program compiles and runs—the output should be exactly the same as it was in the previous lab.
</p>
<h3>Generic Queue</h3>
<p>
Just like in the previous lab, you'll be implementing other containers. Grab <a href="https://raw.githubusercontent.com/oucs-cosc346-s2-2018/lab04-inheritance-and-composition/master/code/01/Queue.swift">Queue.swift</a> from the previous lab and add it to the current project. Modify the code to use the generic type, as shown on the file difference output below.
</p>
<div class="codeblock">
<div class="codeblocktitle">Differences between two versions of Queue.swift </div>
<pre class="filediff">
import Foundation
/**
A queue of objects
*/
class Queue<ins><T></ins> : LinkedList<ins><T></ins> {
/**
Queue desription - adds a string indicating the
container is a queue before invoking super's description
- returns: String String representation of the queue
*/
override var description: String {
return "(Queue)<--"+super.description+"<--"
}
<ins> override init(list: LinkedList<T>? = nil) {
super.init(list: list)
}
</ins> /**
Puts an an object at the end of the queue
- parameter object: Object to put in the queue.
*/
func put(object: <del>Any</del><ins>T</ins>) {
// Use inherited method to add object
// to the list
self.add(object: object);
}
/**
Gets an an object from the start of the queue
- returns: <del>Any</del><ins>T</ins>? Object removed from the start of the queue,
nil if queue is empy.
*/
func get() -> <del>Any</del><ins>T</ins>? {
// If head points to a non-nil node,
// remove that node and return its
// object
if let n = head {
//Use inherited method to remove
//node from the list
self.remove(node: n)
return n.object
} else {
return nil
}
}
}
</pre>
</div>
<p>
<em><span class="swiftcode">Queue<T></span></em> inherits from <em><span class="swiftcode">LinkedList<T></span></em>. However, inheritance with generic classes is a bit tricky...and for some reason Swift insists that <em><span class="swiftcode">LinkedList<T></span></em>'s init method cannot be inherited—it must be overridden. That's why there's an additional override of the init method, which wraps <em><span class="swiftcode"><span class="swiftkeyword">super</span></span></em>'s init.
</p>
<p>Add the test code for the new queue to <em>main.swift</em>. Again, the code is just a modification from the code in the previous lab. <em><span class="swiftcode">Queue</span></em> becomes <em><span class="swiftcode">Queue<<span class="swiftclass">String</span>></span></em>. This time the object removed from the container does not need to be down-cast, because <em><span class="swiftcode">Queue<<span class="swiftclass">String</span>></span></em>'s get method returns a <em><span class="swiftcode"><span class="swiftclass">String</span></span></em>.
</p>
<div class="codeblock">
<div class="codeblocktitle"><a href="code/01/main.swift">main.swift</a></div>
<pre class="linenumbers unselectable" style="float: left;"><span class="codeold">01:
</span><span class="codeold">02:
</span><span class="codeold">03:
</span><span class="codeold">04:
</span><span class="codeold">05:
</span><span class="codeold">06:
</span><span class="codeold">07:
</span><span class="codeold">08:
</span><span class="codeold">09:
</span><span class="codeold">10:
</span><span class="codeold">11:
</span><span class="codeold">12:
</span><span class="codeold">13:
</span><span class="codeold">14:
</span><span class="codeold">15:
</span><span class="codeold">16:
</span>17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
</pre><pre class="code">
<span class="codeold"><span class="swiftcode"><span class="swiftkeyword">import</span> Foundation</span></span>
<span class="codeold"><span class="swiftcode"></span></span>
<span class="codeold"><span class="swiftcode"><span class="swiftkeyword">let</span> str1: <span class="swiftclass">String</span> = <span class="swiftstring">"Item V"</span>;</span></span>
<span class="codeold"><span class="swiftcode"><span class="swiftkeyword">let</span> str2: <span class="swiftclass">String</span> = <span class="swiftstring">"Item E"</span>;</span></span>
<span class="codeold"><span class="swiftcode"><span class="swiftkeyword">let</span> str3: <span class="swiftclass">String</span> = <span class="swiftstring">"Item S"</span>;</span></span>
<span class="codeold"><span class="swiftcode"><span class="swiftkeyword">let</span> str4: <span class="swiftclass">String</span> = <span class="swiftstring">"Item M"</span>;</span></span>
<span class="codeold"><span class="swiftcode"></span></span>
<span class="codeold"><span class="swiftcode"><span class="swiftkeyword">var</span> list: LinkedList<<span class="swiftclass">String</span>> = LinkedList<<span class="swiftclass">String</span>>()</span></span>
<span class="codeold"><span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"</span></span><span class="codeswift">\<span class="swiftstring">(</span>list<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span></span>
<span class="codeold"><span class="swiftcode"></span></span>
<span class="codeold"><span class="swiftcode">list.add(object: str1)</span></span>
<span class="codeold"><span class="swiftcode">list.add(object: str2)</span></span>
<span class="codeold"><span class="swiftcode">list.add(object: str3)</span></span>
<span class="codeold"><span class="swiftcode">list.add(object: str4)</span></span>
<span class="codeold"><span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"</span></span><span class="codeswift">\<span class="swiftstring">(</span>list<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span></span>
<span class="codeold"><span class="swiftcode"></span></span>
<span class="swiftcode"><span class="swiftkeyword">var</span> queue: Queue<<span class="swiftclass">String</span>> = Queue<<span class="swiftclass">String</span>>(list: list)</span>
<span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"\n</span></span><span class="codeswift">\<span class="swiftstring">(</span>queue<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span>
<span class="swiftcode"></span>
<span class="swiftcode"><span class="swiftkeyword">let</span> item1 = queue.<span class="swiftkeyword">get</span>()</span>
<span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"Got item: </span></span><span class="codeswift">\<span class="swiftstring">(</span>item1<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span>
<span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"</span></span><span class="codeswift">\<span class="swiftstring">(</span>queue<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span>
<span class="swiftcode"></span>
<span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"Putting item: </span></span><span class="codeswift">\<span class="swiftstring">(</span>str2<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span>
<span class="swiftcode">queue.put(object: str2)</span>
<span class="swiftcode"><span class="swiftfunction">print</span>(<span class="swiftstring">"</span></span><span class="codeswift">\<span class="swiftstring">(</span>queue<span class="swiftstring">)</span></span><span class="swiftcode"><span class="swiftstring">"</span>)</span>
</pre>
</div>
<p>Compile and run; check that it works.</p>
<h3>Generic Stack and Array</h3>
<p>
Just like in the previous lab, you need to create the stack and array containers yourself—this time with generic type instead of <em><span class="swiftcode"><span class="swiftclass">Any</span></span></em>. Implementation of <em><span class="swiftcode">SortableList<T></span></em> is given to you as well, but again in the difference format from the <a href="https://raw.githubusercontent.com/oucs-cosc346-s2-2018/lab04-inheritance-and-composition/master/code/01/SortableList.swift">SortableList.swift</a> of the previous lab.
</p>
<div class="codeblock">
<div class="codeblocktitle">Differences between two versions of SortableList.swift </div>
<pre class="filediff">
/**
Extending the node class to provide it with a method
for swapping objects between nodes
*/
extension Node {
/**
Swaps objects between self and another node nodes - useful for
sorting - instead of swapping and relinking the nodes, it's easier
to leave the nodes where they are, and just swap their
objects
- parameter n Node to swap objects with
*/
func swapObjectsWith(n: Node<ins><T></ins>) {
let temp: <del>Any</del><ins>T</ins> = self.object
self.object = n.object
n.object = temp
}
}
class SortableList<ins><T></ins> : LinkedList<ins><T></ins> {
<ins>
override init(list: LinkedList<T>? = nil) {
super.init(list: list)
}
</ins>
/**
Get the Nth node from the LinkedList
- parameter index: Index of the node to Get
- returns: Node? The node at the specified index, or nil
if index exceeds list count
*/
func getNodeAtIndex(index: Int) -> Node<ins><T></ins>? {
var node: Node<ins><T></ins>? = head;
// Walk through the list until the
// specified index
if index > 0 {
for _ in 1...index {
if let n = node {
node = n.next;
} else {
// Exit early if index
// exceeds number of
// items on the list
return nil;
}
}
}
return node;
}
/**
Sort the list using the provided compare function
- parameter isObject: A function that compares two objects and
returns true if the first one is smaller than the second one
*/
func sort(isObject: (<del>Any</del><ins>T</ins>, <del>Any</del><ins>T</ins>) -> Bool) {
while true {
var swap: Bool = false;
var nodeLeft: Node<ins><T></ins>? = head
// Walk through the nodes in the list
while let nLeft = nodeLeft {
// Get the next node in the list
if let nRight = nLeft.next {
// Invoked the function that got passed
// in as a parameter to check if the
// object that follows the current one
// on the list is smaller - if yes,
// then swap the object of the two nodes
if(isObject(nRight.object, nLeft.object)) {
nLeft.swapObjectsWith(n: nRight)
swap = true
}
}
nodeLeft = nLeft.next
}
// Check if anything got swapped in this
// pass through the entire list - if not,
// then the entire list has been completely
// sorted
if !swap {
break;
}
}
}
}
</pre>
</div>
<p>
Once you have an implementation of the generic stack and array container, test it. You will need to modify the code from previous lab's <a href="https://raw.githubusercontent.com/oucs-cosc346-s2-2018/lab04-inheritance-and-composition/master/code/01/main_05.swift">main.swift</a>. Some of the changes have been already done in the previous sections of this exercise—the rest should be pretty straightforward. In case you're having trouble, here is are the changes (on the entire <em>main.swift</em> file) you're expected to make:
<div class="codeblock">
<div class="codeblocktitle">Differences between two versions of main.swift </div>
<pre class="filediff">
import Foundation
let str1: String = "Item V";
let str2: String = "Item E";
let str3: String = "Item S";
let str4: String = "Item M";
var list: LinkedList<ins><String></ins> = LinkedList<ins><String></ins>()
print("\(list)")
list.add(object: str1)
list.add(object: str2)
list.add(object: str3)
list.add(object: str4)
print("\(list)")
var queue: Queue<ins><String></ins> = Queue<ins><String></ins>(list: list)
print("\n\(queue)")
<del>if </del>let item1 = queue.get()<del> {</del>
<del> </del>print("Got item: \(item1<del> as! String</del>)")
<del>}
</del>print("\(queue)")
print("Putting item: \(str2)")
queue.put(object: str2)
print("\(queue)")
var stack: Stack<ins><String></ins> = Stack<ins><String></ins>(list: list)
print("\n\(stack)")
<del>if </del>let item2 = stack.pop()<del> {</del>
<del> </del>print("Popped item: \(item2<del> as! String</del>)")
<del>}
</del>print("\(stack)")
print("Pushing item: \(str2)")
stack.push(object: str2)
print("\(stack)")
var array: Array<ins><String></ins> = Array<ins><String></ins>(list: list)
print("\n\(array)")
print("Setting array[2] to \(str1)")
array[2] = str1
print("\(array)")
print("Sorting array");
array.sort(isObject: { o1, o2 in <del>(</del>o1 <del>as! String) </del>< <del>(</del>o2 <del>as! String) </del>})
for index in 0..<array.count {
print("array[\(index)]=\(array[index])")
}
</pre>
</div>
<p>Compile and run, check that it works.</p>
</div>
<h2>Parsing fractions and complex numbers</h2>
<div class="block">
<p>
The SCL library is capable of storing objects of any type, but it does not expect any specific behaviour from them. Polymorphism becomes much more interesting when the objects of unspecified form are expected to provide certain functionality. This is where protocols become extremely useful, as they allow definition of the behaviour that generic types are expected to provide. In this part of the lab, you will be given a <em><span class="swiftcode"><span class="swiftdefined">Parser</span></span></em> class that is capable of evaluating mathematical expressions. The evaluation can be customised by providing the class capable of reading number values from strings. The provided class will need to implement methods of newly defined protocol. In this lab, you will modifying <em><span class="swiftcode"><span class="swiftdefined">Fraction</span></span></em> class and <em><span class="swiftcode"><span class="swiftdefined">Complex</span></span></em> class from <a href="https://github.com/oucs-cosc346-s2-2018/lab03-optionals-and-objects">Lab 3</a> to conform to that protocol.
</p>
<h3>Parser</h3>
<p>
Create new Xcode project, name it <em>prog5.2</em>. The code for the <em><span class="swiftcode"><span class="swiftdefined">Parser</span></span></em> is given below. Do not type this one out—it's quite long and complex. Click on the file link at the top of the box, download it and add to your project. Some of the file content in the box is highlighted. In this particular case, the highlighted parts are not meant to mark additions to the code. The contents of the entire file are given, some parts are made to stand out to aid the discussion that will follow.
</p>
<div class="codeblock">
<div class="codeblocktitle"><a href="code/02/Parser.swift">Parser.swift</a></div>
<pre class="linenumbers unselectable" style="float: left;">001:
002:
003:
004:
005:
006:
007:
008:
009:
010:
011:
012:
013:
014:
015:
016:
017:
018:
019:
020:
021:
022:
023:
024:
025:
026:
027:
028:
029:
030:
031:
032:
033:
034:
035:
036:
037:
038:
039:
040:
041:
042:
043:
044:
045:
046:
047:
048:
049:
050:
051:
052:
053:
054:
055:
056:
057:
058:
059:
060:
061:
062:
063:
064:
065:
066:
067:
068:
069:
070:
071:
072:
073:
074:
075:
076:
077:
078:
079:
080:
081:
082:
083:
084:
085:
086:
087:
088:
089:
090:
091:
092:
093:
094:
095:
096:
097:
098:
099:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288: