forked from RussianSmalltalk/pharo-by-example-ru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pbe1-examples.txt
2307 lines (2234 loc) · 69.4 KB
/
pbe1-examples.txt
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
===== PHARO BY EXAMPLE ==========
Below follow all the (displayed) code examples from the book "Pharo by
Example".
For details about this book, see: http://pharo-project.org/PharoByExample
The examples are provided, as is, for your convenience, in case you want
to copy and paste fragments to Pharo to try out.
Note that in almost all cases the annotation "--> ..." suggests that you
can select and apply <print it> to the previous expression and you should
obtain as a result the value following the arrow.
Many of these actually serve as test cases for the book. For more details
about testing, see the Wiki link under:
http://www.squeaksource.com/PharoByExample.html
Last update: 2012-03-13T22:35:55+06:00
===== CHAPTER: Preface ==========
-----
3 + 4 "--> 7 if you select 3+4 and 'print it', you will see 7"
-----
===== CHAPTER: A quick tour of Pharo ==========
-----
BouncingAtomsMorph new openInWorld
-----
Transcript show: 'hello world'; cr.
-----
3 + 4 "--> 7"
-----
testShout
self assert: ('Don''t panic' shout = 'DON''T PANIC!')
-----
shout
^ self asUppercase, '!'
-----
===== CHAPTER: Первое приложение ==========
-----
SimpleSwitchMorph subclass: #LOCell
instanceVariableNames: 'mouseAction'
classVariableNames: ''
poolDictionaries: ''
category: 'PBE-LightsOut'
-----
initialize
super initialize.
self label: ''.
self borderWidth: 2.
bounds := 0@0 corner: 16@16.
offColor := Color paleYellow.
onColor := Color paleBlue darker.
self useSquareCorners.
self turnOff
-----
BorderedMorph subclass: #LOGame
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'PBE-LightsOut'
-----
initialize
| sampleCell width height n |
super initialize.
n := self cellsPerSide.
sampleCell := LOCell new.
width := sampleCell width.
height := sampleCell height.
self bounds: (5@5 extent: ((width*n) @(height*n)) + (2 * self borderWidth)).
cells := Matrix new: n tabulate: [ :i :j | self newCellAt: i at: j ].
-----
LOGame>>cellsPerSide
"Количество ячеек, приходящееся на одну сторону игрового поля"
^ 10
-----
LOGame>>newCellAt: i at: j
"Создаёт ячейку в позиции (i,j) и добавляет её на экран. Возвращает новую ячейку."
| c origin |
c := LOCell new.
origin := self innerBounds origin.
self addMorph: c.
c position: ((i - 1) * c width) @ ((j - 1) * c height) + origin.
c mouseAction: [self toggleNeighboursOfCellAt: i at: j]
-----
LOGame>>toggleNeighboursOfCellAt: i at: j
(i > 1) ifTrue: [ (cells at: i - 1 at: j ) toggleState].
(i < self cellsPerSide) ifTrue: [ (cells at: i + 1 at: j) toggleState].
(j > 1) ifTrue: [ (cells at: i at: j - 1) toggleState].
(j < self cellsPerSide) ifTrue: [ (cells at: i at: j + 1) toggleState].
-----
LOCell>>mouseAction: aBlock
^ mouseAction := aBlock
-----
LOCell>>mouseUp: anEvent
mouseAction value
-----
LOGame>>newCellAt: i at: j
"Создаёт ячейку в позиции (i,j) и добавляет её на экран. Возвращает новую ячейку."
| c origin |
c := LOCell new.
origin := self innerBounds origin.
self addMorph: c.
c position: ((i - 1) * c width) @ ((j - 1) * c height) + origin.
c mouseAction: [self toggleNeighboursOfCellAt: i at: j].
^ c
-----
MCHttpRepository
location: 'http://www.squeaksource.com/!\emph{ваш проект}!'
user: '!\emph{ваши инициалы}!'
password: '!\emph{ваш пароль}!'
-----
MCHttpRepository
location: 'http://www.squeaksource.com/!\emph{YourProject}!'
user: ''
password: ''
-----
===== CHAPTER: Синтаксис в двух словах ==========
-----
(Smalltalk includes: Class) ifTrue: [ Transcript show: Class superclass ]
-----
+ - / \ * ~ < > = @ % | & ! ? ,
-----
2 raisedTo: 1 + 3 factorial "--> 128"
-----
1 + 2 * 3 "--> 9"
-----
1 + (2 * 3) "--> 7"
-----
Transcript cr.
Transcript show: 'hello world'.
Transcript cr
-----
Transcript cr;
show: 'hello world';
cr
-----
String>>lineCount
"Answer the number of lines represented by the receiver,
where every cr adds one line."
| cr count |
cr := Character cr.
count := 1 min: self size.
self do:
[:c | c == cr ifTrue: [count := count + 1]].
^ count
-----
[ 1 + 2 ] value "--> 3"
-----
[ :x | 1 + x ] value: 2 "--> 3"
[ :x :y | x + y ] value: 1 value: 2 "--> 3"
-----
[ :x :y | | z | z := x+ y. z ] value: 1 value: 2 "--> 3"
-----
| x |
x := 1.
[ :y | x + y ] value: 2 "--> 3"
-----
(17 * 13 > 220)
ifTrue: [ 'bigger' ]
ifFalse: [ 'smaller' ] "--> 'bigger'"
-----
n := 1.
[ n < 1000 ] whileTrue: [ n := n*2 ].
n "--> 1024"
-----
n := 1.
[ n > 1000 ] whileFalse: [ n := n*2 ].
n "--> 1024"
-----
n := 1.
10 timesRepeat: [ n := n*2 ].
n "--> 1024"
-----
result := String new.
1 to: 10 do: [:n | result := result, n printString, ' '].
result "--> '1 2 3 4 5 6 7 8 9 10 '"
-----
result := String new.
(1 to: 10) do: [:n | result := result, n printString, ' '].
result "--> '1 2 3 4 5 6 7 8 9 10 '"
-----
(1 to: 10) collect: [ :each | each * each ] "--> #(1 4 9 16 25 36 49 64 81 100)"
-----
'hello there' select: [ :char | char isVowel ] "--> 'eoee'"
'hello there' reject: [ :char | char isVowel ] "--> 'hll thr'"
'hello there' detect: [ :char | char isVowel ] "--> $e"
-----
(1 to: 10) inject: 0 into: [ :sum :each | sum + each ] "--> 55"
-----
+ aNumber
"Primitive. Add the receiver to the argument and answer with the result
if it is a SmallInteger. Fail if the argument or the result is not a
SmallInteger Essential No Lookup. See Object documentation whatIsAPrimitive."
<primitive: 1>
^ super + aNumber
-----
===== CHAPTER: Подробнее о синтаксисе сообщений ==========
-----
89 sin "--> 0.860069405812453"
3 sqrt "--> 1.732050807568877"
Float pi "--> 3.141592653589793"
'blop' size "--> 4"
true not "--> false"
Object class "--> Object class Класс класса Object -- это Object class (!)"
-----
100@100 "--> 100@100 создаёт объект класса Point"
3 + 4 "--> 7"
10 - 1 "--> 9"
4 <= 3 "--> false"
(4/3) * 3 = 4 "--> true равенство -- это бинарное сообщение, а дроби (Fractions) -- обыкновенные"
(3/4) == (3/4) "--> false равные дроби -- разные объекты"
-----
1 to: 10 "--> (1 to: 10) создаёт интервал"
Color r: 1 g: 0 b: 0 "--> Color red создаёт новый цвет"
12 between: 8 and: 15 "--> true"
nums := Array newFrom: (1 to: 5).
nums at: 1 put: 6.
nums "--> #(6 2 3 4 5)"
-----
1000 factorial / 999 factorial "--> 1000"
2 raisedTo: 1 + 3 factorial "--> 128"
-----
1 + 2 * 3 "--> 9"
1 + (2 * 3) "--> 7"
-----
[:aClass | aClass methodDict keys select: [:aMethod | (aClass>>aMethod) isAbstract ]] value: Boolean "--> an IdentitySet(#or: #| #and: #& #ifTrue: #ifTrue:ifFalse: #ifFalse: #not #ifFalse:ifTrue:)"
-----
aPen color: Color yellow
(1) Color yellow "унарное сообщение посылается первым"
"--> aColor"
(2) aPen color: aColor "затем посылается сообщение с ключевыми словами"
-----
aPen go: 100 + 20
(1) 100 + 20 "сначала бинарное сообщение"
"--> 120"
(2) aPen go: 120 "потом сообщение с ключевыми словами"
-----
1.5 tan rounded asString = (((1.5 tan) rounded) asString) "--> true здесь скобки не нужны"
3 + 4 factorial "--> 27 (не 5040)"
(3 + 4) factorial "--> 5040"
-----
(FMSound lowMajorScaleOn: FMSound clarinet) play
"(1) отправить сообщение clarinet классу FMSound чтобы создать звук кларнета.
(2) отправить этот звук классу FMSound как аргумент сообщения с ключевыми словами lowMajorScaleOn:.
(3) проиграть полученный звук."
-----
(65 @ 325 extent: 134 @ 100) center
(1) 65@325 "бинарное"
"--> aPoint"
(2) 134@100 "бинарное"
"--> anotherPoint"
(3) aPoint extent: anotherPoint "с ключевыми словами"
"--> aRectangle"
(4) aRectangle center "унарное"
"--> 132@375"
-----
3 + 4 * 5 "--> 35 (не 23) Бинарные сообщения посылаются слева направо"
3 + (4 * 5) "--> 23"
1 + 1/3 "--> (2/3) и не 4/3"
1 + (1/3) "--> (4/3)"
1/3 + 2/3 "--> (7/9) и не 1"
(1/3) + (2/3) "--> 1"
-----
"Поскольку все бинарные сообщения имеют один приоритет, крайнее слева сообщение + выполняется первым, даже если правила арифметики гласят, что первым должно быть отправлено сообщение *."
20 + 2 * 5
(1) 20 + 2 "--> 22"
(2) 22 * 5 "--> 110"
-----
"Сообщения, заключённые в скобки выполняются в первую очередь, поэтому * посылается перед +, что приводит к правильному результату."
20 + (2 * 5)
(1) (2 * 5) "--> 10"
(2) 20 + 10 "--> 30"
-----
aDict
at: (rotatingForm
rotateBy: angle
magnify: 2
smoothing: 1)
put: 3
-----
(x isNil)
ifTrue:[...]
-----
ord := OrderedCollection new.
(ord includes: $a)
ifTrue:[...]
-----
[ x isReady ] whileTrue: [ y doSomething ] "и получатель, и аргумент должны быть блоками"
4 timesRepeat: [ Beeper beep ] "аргумент выполняется больше одного раза, поэтому должен быть блоком"
(x isReady) ifTrue: [ y doSomething ] "получатель выполняется лишь один раз, а значит, это не блок"
-----
| box |
box := 20@30 corner: 60@90.
box containsPoint: 40@50 "--> true"
-----
Transcript show: 'Pharo -- это '.
Transcript show: 'весело '.
Transcript cr.
-----
Transcript
show: 'Pharo -- это ';
show: 'весело ';
cr
-----
Point new setX: 25 setY: 35; isZero "--> false"
-----
===== CHAPTER: Объектная модель Smalltalk ==========
-----
3 + 4 "--> 7 послать сообщение '+ 4' объекту 3, вернёт 7"
20 factorial "--> 2432902008176640000 послать сообщение “факториал”, возвращает большое число"
-----
1 class "--> SmallInteger"
20 factorial class "--> LargePositiveInteger"
'hello' class "--> ByteString"
#(1 2 3) class "--> Array"
(4@5) class "--> Point"
Object new class "--> Object"
-----
Point>>dist: aPoint
"Answer the distance between aPoint and the receiver."
| dx dy |
dx := aPoint x - x.
dy := aPoint y - y.
^ ((dx * dx) + (dy * dy)) sqrt
-----
1@1 dist: 4@5 "--> 5.0"
-----
aColor := Color blue. "Class side method blue"
aColor "--> Color blue"
aColor red "--> 0.0 Instance side accessor method red"
aColor blue "--> 1.0 Instance side accessor method blue"
-----
Object subclass: #Dog
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'PBE-CIV'
Dog class
instanceVariableNames: 'count'
Dog subclass: #Hyena
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'PBE-CIV'
-----
Dog class>>initialize
super initialize.
count := 0.
Dog class>>new
count := count +1.
^ super new
Dog class>>count
^ count
-----
Dog initialize.
Hyena initialize.
Dog count "--> 0"
Hyena count "--> 0"
Dog new.
Dog count "--> 1"
Dog new.
Dog count "--> 2"
Hyena new.
Hyena count "--> 1"
-----
Object subclass: #WebServer
instanceVariableNames: 'sessions'
classVariableNames: ''
poolDictionaries: ''
category: 'Web'
-----
WebServer class
instanceVariableNames: 'uniqueInstance'
-----
WebServer class>>uniqueInstance
uniqueInstance ifNil: [uniqueInstance := self new].
^ uniqueInstance
-----
SmallInteger superclass "--> Integer"
Integer superclass "--> Number"
Number superclass "--> Magnitude"
Magnitude superclass "--> Object"
Object superclass "--> ProtoObject"
ProtoObject superclass "--> nil"
-----
Magnitude>>< aMagnitude
"Answer whether the receiver is less than the argument."
^self subclassResponsibility
-----
>= aMagnitude
"Answer whether the receiver is greater than or equal to the argument."
^(self < aMagnitude) not
-----
Character>>< aCharacter
"Answer true if the receiver's value < aCharacter's value."
^self asciiValue < aCharacter asciiValue
-----
Trait named: #TAuthor
uses: { }
category: 'PBE-LightsOut'
-----
TAuthor>>author
"Returns author initials"
^ 'on' "oscar nierstrasz"
-----
BorderedMorph subclass: #LOGame
uses: TAuthor
instanceVariableNames: 'cells'
classVariableNames: ''
poolDictionaries: ''
category: 'PBE-LightsOut'
-----
LOGame new author "--> 'on'"
-----
Object subclass: #Behavior
uses: TPureBehavior @ {#basicAddTraitSelector:withMethod:->#addTraitSelector:withMethod:}
instanceVariableNames: 'superclass methodDict format'
classVariableNames: 'ObsoleteSubclasses'
poolDictionaries: ''
category: 'Kernel-Classes'
-----
3 + 4 "--> 7 send message + with argument 4 to integer 3"
(1@2) + 4 "--> 5@6 send message + with argument 4 to point (1@2)"
-----
anEllipse := EllipseMorph new.
-----
anEllipse defaultColor "--> Color yellow"
-----
EllipseMorph>>defaultColor
"answer the default color/fill style for the receiver"
^ Color yellow
-----
Morph>>openInWorld
"Add this morph to the world."
self openInWorld: self currentWorld
-----
Morph>>openInWorld
"Add this morph to the world."
self openInWorld: self currentWorld
^ self "Don't do this unless you mean it!"
-----
BorderedMorph>>initialize
"initialize the state of the receiver"
super initialize.
self borderInitialize
-----
anEllipse constructorString "--> '((EllipseMorph newBounds: (0@0 corner: 50@40) color: Color yellow) setBorderWidth: 1 borderColor: Color black)'"
-----
Morph>>constructorString
^ String streamContents: [:s | self printConstructorOn: s indent: 0].
-----
BorderedMorph>>fullPrintOn: aStream
aStream nextPutAll: '('.
!\textbf{super fullPrintOn: aStream.}!
aStream nextPutAll: ') setBorderWidth: '; print: borderWidth;
nextPutAll: ' borderColor: ' , (self colorString: borderColor)
-----
Transcript show: 'Pharo is fun and powerful' ; cr
-----
Smalltalk at: #Boolean "--> Boolean"
-----
Smalltalk at: #Smalltalk "-->a SystemDictionary(lots of globals)}"
-----
(Smalltalk at: #Smalltalk) == Smalltalk "--> true"
-----
SystemOrganization categoryOfElement: #Magnitude "--> #'Kernel-Numbers'"
-----
Object subclass: #Color
instanceVariableNames: 'rgb cachedDepth cachedBitPattern'
classVariableNames: 'Black Blue BlueShift Brown CachedColormaps ColorChart ColorNames ComponentMask ComponentMax Cyan DarkGray Gray GrayToIndexMap Green GreenShift HalfComponentMask HighLightBitmaps IndexedColors LightBlue LightBrown LightCyan LightGray LightGreen LightMagenta LightOrange LightRed LightYellow Magenta MaskingMap Orange PaleBlue PaleBuff PaleGreen PaleMagenta PaleOrange PalePeach PaleRed PaleTan PaleYellow PureBlue PureCyan PureGreen PureMagenta PureRed PureYellow RandomStream Red RedShift TranslucentPatterns Transparent VeryDarkGray VeryLightGray VeryPaleRed VeryVeryDarkGray VeryVeryLightGray White Yellow'
poolDictionaries: ''
category: 'Graphics-Primitives'
-----
Color class>>colorNames
ColorNames ifNil: [self initializeNames].
^ ColorNames
-----
Color class>>initialize
!\ldots!
self initializeNames
-----
ArrayedCollection subclass: #Text
instanceVariableNames: 'string runs'
classVariableNames: ''
!\textbf{poolDictionaries: 'TextConstants'}!
category: 'Collections-Text'
-----
Text>>testCR
^ CR == Character cr
-----
===== CHAPTER: Pharo - современная среда разработки ==========
-----
SystemNavigation default browseAllCallsOn: #drawOn:
-----
SystemNavigation default browseAllCallsOn: #drawOn: from: ImageMorph
-----
SystemNavigation default browseAllImplementorsOf: #drawOn:
-----
Object>>asSQL
String>>asSQL
Date>>asSQL
-----
mc := PackageInfo named: 'Monticello'
-----
MCHttpRepository
location: 'http://squeaksource.com/PharoByExample'
user: ''
password: ''
-----
self - TimeStamp today
-----
suffix
"assumes that I'm a file name, and answers my suffix, the part after the last dot"
"предполагает, что я представляю собой имя файла и возвращает мой суффикс, часть после точки"
| dot dotPosition |
dot := FileDirectory dot.
dotPosition := (self size to: 1 by: -1) detect: [ :i | (self at: i) = dot ].
^ self copyFrom: dotPosition to: self size
-----
testSuffixFound
self assert: 'readme.txt' suffix = 'txt'
-----
testSuffixFound
self assert: 'readme.txt' suffix = 'txt'.
self assert: 'read.me.txt' suffix = 'txt'
-----
suffix
"assumes that I'm a file name, and answers my suffix, the part after the last dot"
| dot dotPosition |
dot := FileDirectory dot first.
dotPosition := (self size to: 1 by: -1) detect: [ :i | (self at: i) = dot ].
self halt.
^ self copyFrom: dotPosition to: self size
-----
testSuffixNotFound
self assert: 'readme' suffix = ''
-----
===== CHAPTER: SUnit ==========
-----
TestCase subclass: #ExampleSetTest
instanceVariableNames: 'full empty'
classVariableNames: ''
poolDictionaries: ''
category: 'MySetTest'
-----
ExampleSetTest>>setUp
empty := Set new.
full := Set with: 5 with: 6
-----
ExampleSetTest>>testIncludes
self assert: (full includes: 5).
self assert: (full includes: 6)
-----
ExampleSetTest>>testOccurrences
self assert: (empty occurrencesOf: 0) = 0.
self assert: (full occurrencesOf: 5) = 1.
full add: 5.
self assert: (full occurrencesOf: 5) = 1
-----
ExampleSetTest>>testRemove
full remove: 5.
self assert: (full includes: 6).
self deny: (full includes: 5)
-----
ExampleSetTest>>testIllegal
self should: [empty at: 5] raise: Error.
self should: [empty at: 5 put: #zork] raise: Error
-----
ExampleSetTest>>testIllegal
self should: [empty at: 5] raise: TestResult error.
self should: [empty at: 5 put: #zork] raise: TestResult error
-----
ExampleSetTest run: #testRemove "--> 1 run, 1 passed, 0 failed, 0 errors"
-----
ExampleSetTest suite run "--> 5 run, 5 passed, 0 failed, 0 errors"
-----
TestResource subclass: #MyTestResource
instanceVariableNames: ''
MyTestCase class>>resources
"associate the resource with this class of test cases"
^{ MyTestResource }
-----
| e |
e := 42.
self assert: e = 23
description: 'expected 23, got ', e printString
-----
#assert:description:
#deny:description:
#should:description:
#shouldnt:description:
-----
aCollection do: [ :each | self assert: each even]
-----
aCollection do:
[:each |
self
assert: each even
description: each printString , ' is not even'
resumable: true]
-----
TestCase>>run
| result |
result := TestResult new.
self run: result.
^result
-----
TestCase>>run: aResult
aResult runCase: self
-----
TestResult>>runCase: aTestCase
| testCasePassed |
testCasePassed := true.
[[aTestCase runCase]
on: self class failure
do:
[:signal |
failures add: aTestCase.
testCasePassed := false.
signal return: false]]
on: self class error
do:
[:signal |
errors add: aTestCase.
testCasePassed := false.
signal return: false].
testCasePassed ifTrue: [passed add: aTestCase]
-----
TestCase>>runCase
[self setUp.
self performTest] ensure: [self tearDown]
-----
TestCase class>>testSelectors
^self selectors asSortedCollection asOrderedCollection select: [:each |
('test*' match: each) and: [each numArgs isZero]]
-----
\begin{method}[testsuiterun]{Выполнение набора тестов}
TestSuite>>run
| result |
result := TestResult new.
self resources do: [ :res |
res isAvailable ifFalse: [^res signalInitializationError]].
[self run: result] ensure: [self resources do: [:each | each reset]].
^result
-----
TestSuite>>run: aResult
self tests do: [:each |
self changed: each.
each run: aResult].
-----
TestResource class>>isAvailable
^self current notNil and: [self current isAvailable]
-----
TestResource class>>current
current isNil ifTrue: [current := self new].
^current
-----
TestResource>>initialize
super initialize.
self setUp
-----
===== CHAPTER: Базовые классы ==========
-----
Browser new printString "--> 'a Browser'"
-----
Color>>printOn: aStream
| name |
(name := self name) ifNotNil:
[ ^ aStream
nextPutAll: 'Color ';
nextPutAll: name ].
self storeOn: aStream
-----
Color red printString "--> 'Color red'"
-----
true "--> true"
3@4 "--> 3@4"
$a "--> $a"
#(1 2 3) "--> #(1 2 3)"
Color red "--> Color red"
-----
{10@10 . 100@100} "--> {10@10 . 100@100}"
{Browser new . 100@100} "--> an Array(a Browser 100@100)"
-----
#(10@10 100@100) "--> #(10 #@ 10 100 #@ 100)"
-----
Point>>printOn: aStream
"The receiver prints on aStream in terms of infix notation."
x printOn: aStream.
aStream nextPut: $@.
y printOn: aStream
-----
Interval>>printOn: aStream
aStream nextPut: $(;
print: start;
nextPutAll: ' to: ';
print: stop.
step ~= 1 ifTrue: [aStream nextPutAll: ' by: '; print: step].
aStream nextPut: $)
-----
1 to: 10 "--> (1 to: 10) intervals are self-evaluating"
-----
Object>>= anObject
"Answer whether the receiver and the argument represent the same object.
Если = переопределено в каком-либо потомке, рекомендуется так же
переопределить сообщение hash."
^ self == anObject
-----
(1 + 2 i) = (1 + 2 i) "--> true одно и то же значние"
(1 + 2 i) == (1 + 2 i) "--> false но разные объекты"
-----
Complex>>= anObject
anObject isComplex
ifTrue: [^ (real = anObject real) & (imaginary = anObject imaginary)]
ifFalse: [^ anObject adaptToComplex: self andSend: #=]
-----
(1 + 2 i) ~= (1 + 4 i) "--> true"
-----
Complex>>hash
"Hash is reimplemented because = is implemented."
^ real hash bitXor: imaginary hash.
-----
#'lulu' = 'lulu' "--> true"
'lulu' = #'lulu' "--> true"
-----
1 class "--> SmallInteger"
-----
1 isMemberOf: SmallInteger "--> true must be precisely this class"
1 isMemberOf: Integer "--> false"
1 isMemberOf: Number "--> false"
1 isMemberOf: Object "--> false"
-----
1 isKindOf: SmallInteger "--> true"
1 isKindOf: Integer "--> true"
1 isKindOf: Number "--> true"
1 isKindOf: Object "--> true"
1 isKindOf: String "--> false"
1/3 isKindOf: Number "--> true"
1/3 isKindOf: Integer "--> false"
-----
1 respondsTo: #, "--> false"
-----
a1 := { { 'harry' } }.
a1 "--> #(#('harry'))"
a2 := a1 shallowCopy.
a2 "--> #(#('harry'))"
(a1 at: 1) at: 1 put: 'sally'.
a1 "--> #(#('sally'))"
a2 "--> #(#('sally')) the subarray is shared!"
-----
a1 := { { 'harry' } } .
a2 := a1 copyTwoLevel.
(a1 at: 1) at: 1 put: 'sally'.
a1 "--> #(#('sally'))"
a2 "--> #(#('harry')) fully independent state"
-----
a1 := { { { 'harry' } } } .
a2 := a1 deepCopy.
(a1 at: 1) at: 1 put: 'sally'.
a1 "--> #(#('sally'))"
a2 "--> #(#(#('harry')))"
-----
a1 := { 'harry' }.
a2 := { a1 }.
a1 at: 1 put: a2.
a1 deepCopy "--> !\emph{... does not terminate!}!"
-----
Object>>copy
"Answer another instance just like the receiver.
Subclasses typically override postCopy;
they typically do not override shallowCopy."
^self shallowCopy postCopy
-----
Stack>>pop
"Return the first element and remove it from the stack."
self assert: [ self isEmpty not ].
^self linkedList removeFirst element
-----
1 doIfNotNil: [ :arg | arg printString, ' is not nil' ]
"--> !\emph{SmallInteger(Object)>>doIfNotNil: has been deprecated. use ifNotNilDo:}!"
-----
Object>>subclassResponsibility
"This message sets up a framework for the behavior of the class' subclasses.
Announce that the subclass should have implemented this message."
self error: 'My subclass should have overridden ', thisContext sender selector printString
-----
Number new + 1 "--> !\emph{Error: My subclass should have overridden \#+}!"
-----
ProtoObject>>initialize
"Subclasses should redefine this method to perform initializations on instance creation"
-----
Behavior>>new
"Answer a new initialized instance of the receiver (which is a class) with no indexable
variables. Fail if the class is indexable."
^ self basicNew initialize
-----
Magnitude>> < aMagnitude
"Answer whether the receiver is less than the argument."
^self subclassResponsibility
Magnitude>> > aMagnitude
"Answer whether the receiver is greater than the argument."
^aMagnitude < self
-----
1 + 2.5 "--> 3.5 Сумма двух чисел"
3.4 * 5 "--> 17.0 Произведение двух чисел"
8 / 2 "--> 4 Частное двух чисел"
10 - 8.3 "--> 1.7 Разность двух чисел"
12 = 11 "--> false Равентсно двух чисел"
12 ~= 11 "--> true Проверка, являются ли числа различными"
12 > 9 "--> true Больше, чем"
12 >= 10 "--> true Больше либо равно"
12 < 10 "--> false Меньше, чем"
100@10 "--> 100@10 Создание точки"
-----
1000 factorial / 999 factorial "--> 1000"
-----
Float pi "--> 3.141592653589793"
Float infinity "--> Infinity"
Float infinity isInfinite "--> true"
-----
6/8 "--> (3/4)"
(6/8) class "--> Fraction"
-----
6/8 * 4 "--> 3"
-----
SmallInteger maxVal = ((2 raisedTo: 30) - 1) "--> true"
SmallInteger minVal = (2 raisedTo: 30) negated "--> true"
-----
(SmallInteger maxVal + 1) class "--> LargePositiveInteger"
(SmallInteger minVal - 1) class "--> LargeNegativeInteger"
-----
n := 2.
3 timesRepeat: [ n := n*n ].
n "--> 256"
-----
$a < $b "--> true"
-----
Character space = (Character value: Character space asciiValue) "--> true"
-----
Character value: 1 "--> Character home"
Character value: 2 "--> Character value: 2"
Character value: 32 "--> Character space"
Character value: 97 "--> $a"
-----
$a asString "--> 'a'"
$a "--> $a"
$a printString "--> '$a'"
-----
(Character value: 97) == $a "--> true"
-----
Character characterTable size "--> 256"
(Character value: 500) == (Character value: 500) "--> false"
-----
'hello world' class "--> ByteString"
-----
'hel','lo' == 'hello' "--> false"
-----
('hel','lo') asSymbol == #hello "--> true"
-----
'hello' at: 2 put: $u; yourself "--> 'hullo'"
-----
#hello at: 2 put: $u "--> error!"
-----
#hello indexOf: $o "--> 5"
-----
'*or*' match: 'zorro' "--> true"
-----
(4 factorial > 20) ifTrue: [ 'bigger' ] ifFalse: [ 'smaller' ] "--> 'bigger'"
-----
True>>ifTrue: trueAlternativeBlock ifFalse: falseAlternativeBlock
^trueAlternativeBlock value
False>>ifTrue: trueAlternativeBlock ifFalse: falseAlternativeBlock
^falseAlternativeBlock value
-----
True>>not
"Negation--answer false since the receiver is true."
^false
-----
(1>2) & (3<4) "--> false должно вычислить обе стороны"
(1>2) and: [ 3<4 ] "--> false вычислит только получателя"
(1>2) and: [ (1/0) > 0 ] "--> false блок-аргумент не будет вычислен, поэтому не произойдёт исключения"
-----
===== CHAPTER: Коллекции ==========
-----
students select: [ :each | each gpa < threshold ]
-----
Array with: 1 "--> #(1)"
Array with: 1 with: 2 "--> #(1 2)"
Array with: 1 with: 2 with: 3 "--> #(1 2 3)"
Array with: 1 with: 2 with: 3 with: 4 "--> #(1 2 3 4)"
Array with: 1 with: 2 with: 3 with: 4 with: 5 "--> #(1 2 3 4 5)"
Array with: 1 with: 2 with: 3 with: 4 with: 5 with: 6 "--> #(1 2 3 4 5 6)"
-----
(1 to: 5) asOrderedCollection addAll: '678'; yourself "--> an OrderedCollection(1 2 3 4 5 $6 $7 $8)"
-----
Array withAll: #(7 3 1 3) "--> #(7 3 1 3)"
OrderedCollection withAll: #(7 3 1 3) "--> an OrderedCollection(7 3 1 3)"
SortedCollection withAll: #(7 3 1 3) "--> a SortedCollection(1 3 3 7)"
Set withAll: #(7 3 1 3) "--> a Set(7 1 3)"
Bag withAll: #(7 3 1 3) "--> a Bag(7 1 3 3)"
Dictionary withAll: #(7 3 1 3) "--> a Dictionary(1->7 2->3 3->1 4->3 )"
-----
Array newFrom: #(7 3 1 3) "--> #(7 3 1 3)"
OrderedCollection newFrom: #(7 3 1 3) "--> an OrderedCollection(7 3 1 3)"
SortedCollection newFrom: #(7 3 1 3) "--> a SortedCollection(1 3 3 7)"
Set newFrom: #(7 3 1 3) "--> a Set(7 1 3)"
Bag newFrom: #(7 3 1 3) "--> a Bag(7 1 3 3)"
Dictionary newFrom: {1 -> 7. 2 -> 3. 3 -> 1. 4 -> 3} "--> a Dictionary(1->7 2->3 3->1 4->3 )"
-----
anArray := Array new: 5.
anArray at: 1 put: 4.
anArray at: 2 put: 3/2.
anArray at: 3 put: 'ssss'.
anArray at: 1 "--> 4"
-----
Array with: 4 with: 3/2 with: 'lulu' "--> {4 . (3/2) . 'lulu'}"
-----
#(1 'here') size "--> 2"
-----
#(1+2) "--> #(1 #+ 2)"
-----
{ 1 + 2 } "--> #(3)"
{(1/2) asFloat} at: 1 "--> 0.5"
{10 atRandom . 1/3} at: 2 "--> (1/3)"
-----
anArray := #(1 2 3 4 5 6) copy.
anArray at: 3 "--> 3"
anArray at: 3 put: 33.
anArray at: 3 "--> 33"
-----
ordCol := OrderedCollection new.
ordCol add: 'Seaside'; add: 'SqueakSource'; addFirst: 'Monticello'.
ordCol "--> an OrderedCollection('Monticello' 'Seaside' 'SqueakSource')"
-----
ordCol add: 'Monticello'.
ordCol remove: 'Monticello'.
ordCol "--> an OrderedCollection('Seaside' 'SqueakSource' 'Monticello')"
-----
res := ordCol remove: 'zork' ifAbsent: [33].
res "--> 33"
-----
#(1 2 3) asOrderedCollection "--> an OrderedCollection(1 2 3)"
'hello' asOrderedCollection "--> an OrderedCollection($h $e $l $l $o)"
-----
Interval from: 1 to: 100 "--> (1 to: 100)"
-----
(Interval from: 1 to: 100) = (1 to: 100) "--> true"
-----
(Interval from: 1 to: 100 by: 0.5) size "--> 199"
(1 to: 100 by: 0.5) at: 198 "--> 99.5"
(1/2 to: 54/7 by: 1/3) last "--> (15/2)"
-----
colors := Dictionary new.
colors at: #yellow put: Color yellow.
colors at: #blue put: Color blue.
colors at: #red put: Color red.
colors at: #yellow "--> Color yellow"
colors keys "--> a Set(#blue #yellow #red)"
colors values "--> {Color blue . Color yellow . Color red}"
-----
colors := Dictionary newFrom: { #blue->Color blue. #red->Color red. #yellow->Color yellow }.
colors removeKey: #blue.
colors associations "--> {#yellow->Color yellow . #red->Color red}"
-----