-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelp-PharoSmalltalk.txt
2993 lines (2010 loc) · 74.3 KB
/
help-PharoSmalltalk.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
-----
http://pharo.org
A clean, innovative, open-source Smalltalk-inspired environment.
Pharo has a simple dynamically-typed object model:
- Everything is an object (an instance of a class).
- Classes are objects too.
- Computation happens only via message sends (and variable assignment).
- There is single inheritance between classes.
- Instance variables are protected.
- Methods are public.
- Blocks are lexical closure a.k.a. anonymous methods.
- Traits are groups of methods that can be reused orthogonally to inheritance.
Pharo is:
- Pure & elegant
- Fun
- Simple
- Highly productive
- Excellent for teaching
- Empowering
- Fully accessible
Learn Pharo
-----------
http://pharo.org
http://pharo.org/documentation
https://github.com/pharo-open-documentation/pharo-wiki
https://pharoweekly.wordpress.com/
https://thepharo.dev
Learn Pharo in Pharo itself by using professor Stef:
ProfStef go.
ProfStef next.
ProfStef previous.
Massive Open Online Course http://mooc.pharo.org
Pharo Books http://books.pharo.org
Pharo by Example
Entreprise Pharo
Deep into Pharo
Dynamic Web with Seaside: http://book.seaside.st
Updated Pharo by Example https://github.com/SquareBracketAssociates/UpdatedPharoByExample
Numerical Methods https://github.com/SquareBracketAssociates/NumericalMethods
Screen casts https://www.youtube.com/channel/UCp3mNigANqkesFzdm058bvw
Presentations http://www.slideshare.net/pharoproject/
Cheat-sheet https://files.pharo.org/media/flyer-cheat-sheet.pdf
Misc Articles https://medium.com/concerning-pharo
https://medium.com/concerning-pharo/elegant-pharo-code-bb590f0856d0
Notes below are primarily learned from these resources.
The Complete Syntax on a Postcard
---------------------------------
exampleWithNumber: x
"This method illustrates the complete syntax."
<aMethodAnnotation>
|y|
true & false not & (nil isNil)
ifFalse: [ self halt ].
y := self size + super size.
#($a #a 'a' 1 1.0)
do: [ :each | Transcript
show: (each class name);
show: (each printString);
show: ' ' ].
^x<y
Comments
--------
"This is a comment in Pharo Smalltalk"
Assignment
----------
:=
Separator
---------
. is a separator (not a terminator).
Variable Declaration
--------------------
| foo | "Declaration of one variable"
| foo bar | "Declaration of two variables"
Messages, Selectors, Methods
----------------------------
Selector: Name of a message.
Message: Selector with parameter values.
Method: Code found in class for responding to message.
A method is called by sending a message to an object, the message receiver; the message returns an object. Messages are modeled from natural languages, with a subject, a verb and complements.
There are three types of messages:
- unary,
- binary,
- keyword.
A unary message is one with no arguments:
Array new. The message new is sent to the class Array (instance creation).
2 squared. The message squared is sent to an integer.
-3 abs. The message absolute is sent to an integer.
#(1 2 3) size. The message size is sent to an array.
A binary message takes only one argument and is named by one or more symbol characters:
3 + 4. The + message is sent to the object 3 with 4 as the argument.
’Hello’, ’ World’. The string ’Hello’ receives the message , (comma) with ’ World’ as the argument.
A keyword message can take one or more arguments that are inserted in the message name:
’Smalltalk’ allButFirst: 5. Sends the message allButFirst: to a string, with the argument 5 (this returns the string ’talk’).
3 to: 10 by: 2. Sends to:by: to 3, with arguments 10 and 2 (this returns an interval (a collection) containing 3, 5, 7 and 9).
Class methods
-------------
Class methods are normal methods.
Most class methods create new instances.
- but they can be used for other things like parsing.
Message Precedence
------------------
Unary messages are executed first, then binary messages and finally keyword messages:
Unary > Binary > Keyword
Or more precise:
Parentheses > Unary > Binary > Keyword, and finally from left to right.
2 + 3 squared. Returns 11.
2 raisedTo: 3 + 2. Returns 32
Between messages of similar precedence, expressions are executed from left to right:
-3 abs negated reciprocal.
Use parentheses to change order of evaluation
(2 + 3) squared.
(2 raisedTo: 3) + 2.
The rule suffers no exception: Operators are just binary messages with no notion of mathematical precedence.
Traditional precedence rules from mathematics do not apply in Pharo!
Remember that all messages always follow a simple left-to-right precedence rule.
2 * 10 + 2.
2 + 2 * 10.
2 + (2 * 10).
Cascading Messages
------------------
Multiple messages can be sent to the same receiver with ; (semicolon).
; is the cascade operator.
OrderedCollection new
add: #abc;
add: #def;
add: #ghi.
The value of the whole message cascade is the value of the last message sent.
To return the receiver of the message cascade instead, make sure to send yourself as the last message of the cascade.
OrderedCollection new
add: #abc;
add: #def;
add: #ghi;
yourself.
Classes
-------
Object: An instance of some class.
Class: Defines behaviour of instances.
Classes are defined by sending the message subclass: to the class Object.
Class names start with uppercase.
Object subclass: #Counter
instanceVariableNames: 'count'
Object subclass: #Point
instanceVariableNames: 'x y'
A class is an object.
A class is an instance of another class called a metaclass.
A metaclass is just a class whose instances are classes.
Class X is always the unique instance of the class called "X class"
The class called "X class" is automatically created; it is the metaclass.
A class can receive messages.
Method lookup works the same.
Sending a message to a class is handled similarly as sending a message to an instance, because a class is an instance: it is the instance of a metaclass.
Variable Class
--------------
A variable class defines variable size objects.
E.g. Arrays are variable size objects:
Array new: 10
> #(nil nil nil nil nil nil nil nil nil nil)
Array new: 5
> #(nil nil nil nil nil)
Defined by using message variableSubclass: instead of subclass:
ArrayedCollection variableSubclass: #Array
instanceVariableNames: ''
classVariableNames: ''
package: 'Collections-Sequenceable-Base'
Instances of a variable class have a variable size (indexed) zone after the named variables.
Only one indexed instance variable per class (always the last one).
First element starts at index 1.
Create Variable Class instances with new: aMaxValue
myArray := Array new: 4
Access indexed values with at: and at:put:
myArray at: 1
myArray at: 2 put: 'yes yes'.
size returns the number of indexed instance variables:
myArray size
Possible variable classes:
#variableSubclass: example: Array
#variableByteSubclass: example: ByteString
#variableWordSubclass: example: Bitmap
Some methods related to these variable classes:
isPointers
isBits
isBytes
isFixed
isVariable
Please note:
- Classes defined using subclass: can have any kind of subclasses.
- Classes defined using variableSubclass: can only have variableSubclass: subclasses
Metaclasses
-----------
Advanced topic, for details see MOOC or Deep Into Pharo.
Metaclasses in seven Points:
1. Every object is an instance of a class.
2. Every class eventually inherits from Object.
3. Every class is an instance of a metaclass.
4. The metaclass hierarchy parallels the class hierarchy.
5. Every metaclass inherits from Class up to Behavior.
6. Every metaclass is an instance of Metaclass.
7. The metaclass of Metaclass is an instance of Metaclass.
Class Object represents the common object behavior:
- Error handling, halting, announcements.
- All classes eventually inherit from Object.
Every class is an instance of a metaclass.
Classes are objects too!
Every class X is the unique instance of its metaclass, called X class.
Metaclasses are automatically created when creating a class.
Metaclass is responsible for creating and initializing a metaclass’s sole instance (a Class).
Where is method new defined?
- When not overridden, sending message new to a class executes method new defined in Behavior.
- The class Behavior is responsible for creating new instances.
Object/Instance Creation
------------------------
The new method is a class method.
When you send the new message to a class, it creates a new instance of that class and returns it.
Sending the messages new or new: to a class:
Counter new.
Array new: 6
Sending an instance-creation messages to a class:
Counter startingAt: 5.
Sending a message to another object:
10@20 "Creates a point"
'Pharo', ' is Cool' "Creates a string"
"self class" always returns the class of the receiver.
"self class new" returns an instance of the receiver.
"self class new" returns an instance of a potential subclass in case of inheritance.
#TODO, is this correct?
The initialize method is an instance method.
It is called automatically by the new method just after an instance is created.
The purpose of the initialize method is to set up the initial state of the newly created object.
Standard implementation of new is:
new
^self basicNew initialize
#basicNew is a primitive that just creates the object, but does no initialization.
All instance variables will be nil after basicNew.
Class Initialization
--------------------
How and when are classes initialized?
An object is initialized at creation time.
Classes are objects too.
A class is initialized through the class method initialize.
A class is initialized:
- either at load time after its methods are loaded
- or explicitly by the programmer.
Warning:
- Don’t write super initialize in a class initialize method!
- This will initialize superclasses that are already initialized (at load time).
Inheritance
-----------
Inheritance allows a class to refine state and behavior.
A class extends the definition of its superclass.
A subclass can:
- add state and behavior;
- use superclass behavior and state;
- specialize and redefine superclass behavior.
A class has 1 and only 1 superclass.
A class eventually inherits from Object.
Object is the root of most classes.
ProtoObject is Object’s superclass (it is for special purposes).
Inheritance of state is static (i.e. during class creation).
Inheritance of behavior is dynamic (i.e. during execution).
Inheritance of instance variables:
- happens during class definition;
- computed from the class own instance variables and the ones of its superclasses,
Inheritance of behavior:
- happens at runtime;
- the method is searched starting from the receiver’s class then going to the superclass.
Inheritance, Method Lookup, self, super
---------------------------------------
Sending a message is a two-step process:
1. Look up the method matching the message.
2. Execute this method on the receiver.
Method lookup:
- Maps a message to a method.
- Method lookup starts in the class of the receiver
- if the method is defined in the class, it is returned
- if the method is not found the search continues in the superclass (it goes up in the hierarchy).
self always represents the receiver of the message.
self in Pharo, this in Java.
The method lookup starts in the class of the receiver.
super refers to the receiver of the message (just like self) !!!
super changes where the lookup starts.
The method lookup starts in the superclass of the class containing the super expression !!!
NOTE this WRONG definition: super looks for the method in the superclass of the receiver’s class.
So, the key distinction is that super refers to the superclass of the class containing the super
expression and not necessarily to the superclass of the actual runtime class of the object.
So, super always refers to the superclass of the class containing the super expression and is
not dependent on the runtime class of the object.
So, super refers to the receiver, but the method lookup starts in the superclass of the class
defining the method.
When no method is found during lookup in the class hierarchy:
- doesNotUnderstand: is sent to the receiver.
- The initial message is passed as parameter.
- When doesNotUnderstand: arrives at Object instance, an error is raised.
- doesNotUnderstand: is a message and any class can implement the corresponding method;
used for automatic delegation, proxy, distribution.
- When no class redefines doesNotUnderstand: it is executed in Object:
- It raises a MessageNotUnderstood exception;
- When not handled, this exception opens a debugger.
Catching MessageNotUnderstood Error:
[ self sayHi ]
on: MessageNotUnderstood
do: [ Transcript show: 'Something wrong here' ]
Return Values
-------------
Use the caret ^ to return a value from a method.
The caret ^ always terminates the method.
A method returns self by default (a method with no caret ^ returns self).
A block returns the result of its last expression.
Variables
---------
Lowercase are used for local/private/temporary variables.
Uppercase are used for shared or global variables.
Local variables start with lowercase (temporary variables, instance variables, arguments,...).
CounterTest >> testIncrement
|c|
c := Counter new.
...
Shared or global variables start with uppercase (class, class variables).
Object is a class globally accessible:
Object subclass: #Point
Transcript is an object that is globally accessible (a kind of stdout):
Transcript cr.
Transcript show: 'hello world'.
Class variables are shared variables:
- Shared by the instances of the class and subclasses.
- Accessible from instance and class methods.
- Start with an uppercase letter.
- Class variables are initialized at the class side.
- Class variables are listed in the classVariableNames section:
Object subclass: #CombinedChar
instanceVariableNames: 'codes combined'
classVariableNames: 'Compositions Decompositions Diacriticals'
package: 'Kernel−BasicObjects'
Class instance variables:
- A class can have instance variables like any object.
- A class is an instance of a class (its metaclass).
- Accessible from class methods only.
- Start with a lowercase letter.
- A metaclass lists its class instance variables in the instanceVariableNames section:
RPackageSet class
instanceVariableNames: 'cachePackages'
- A class instance variable specifies one value for each instance (each class).
- A metaclass has one direct instance: its associated class.
- A metaclass has several indirect instances: the ones of its subclasses.
- Each subclass inherits the variable and has its own value for the variable.
Special variables cannot be changed: true, false, nil self, super, thisContext
- true, false are the Booleans
- true is the unique instance of the class True
- false is the unique instance of the class False
- nil is a global and special variable that refers to the only instance of class UndefinedObject.
- nil is the unique instance of the class UndefinedObject
- self refers to the receiver of the message (this in Java).
- super refers to the receiver but the method lookup starts in the superclass of the class defining the method.
- thisContext refers to the current execution stack (advanced)
Characters
----------
A Character is instantiated using $ operator:
$A.
$A class.
$B charCode.
Unprintable characters:
Character space.
Character tab.
Character cr.
Print all 256 characters of the ASCII extended set:
Character allByteCharacters.
Code point (Unicode value) of a character:
$A codePoint.
$λ codePoint.
'I love Pharo' collect: #codePoint as: Array.
Strings
-------
A String is a collection of characters, delimited by single quotes.
Use single quotes to create a String object.
'ProfStef'.
'ProfStef' size.
'ProfStef' first.
'ProfStef' last.
'abc' asUppercase.
'abc' asLowercase.
'Hello World' reverse.
You can access each character using at: message. Index starts at 1, not at 0.
'ProfStef' at: 1.
String concatenation uses the comma operator:
'ProfStef' , ' is cool'.
To add a quote in a string just type it twice (escape with '):
'It''s not correct'
Other ways to create strings:
12 asString
12 printString
String with: $a
String with: $a with: $b
#mac asString
String is a collection:
'Hello there' do: [:each | Transcript show: each ; cr ]
Trim whitespace like spaces and tabs:
' Hello World ' trim.
' Hello World ' trimLeft.
' Hello World ' trimRight.
Remove characters from a string:
'ProfStef' copyWithout: $f.
'ProfStef' copyWithoutAll: 'fP'.
('ip is it' copyWithout: ' ') reverse capitalized.
Splitting a string on a certain character, for example a space:
' ' split: 'eclair au chocolat'
Character space split: 'eclair au chocolat'
> an OrderedCollection('eclair' 'au' 'chocolat')
Character space split: 'A Symbol is a String which is guaranteed to be globally unique'
Splitting a string on a dash:
$- split: '1969-07-20'
'-' split: '1969-07-20'
('-' split: '1969-07-20') first
Joining an array of strings with a specific character:
Character space join: #('This' 'is' 'crazy')
$_ join: #('This' 'is' 'crazy')
$/ join: ($- split: '1969-07-20') reverse
'/' join: ('-' split: '1969-07-20') reverse
Collection of lines:
String>>#lines returns a collection containing substrings separated by \n, \r, or \r\n
multiLineString lines
Copy and slice strings:
s := 'abcdefg'.
s first. "$a"
s allButFirst. "bcdefg"
s last. "$g"
s allButLast. "abcdef"
Pass a number argument to change the number of characters removed/kept:
s first: 2. "ab"
s allButFirst: 2. "cdefg"
s last: 2. "fg"
s allButLast: 2. "abcde"
To get the middle of a string use SequenceableCollection>>#copyFrom:to:
s := 'abcdefg'.
s copyFrom: 2 to: 6. "bcdef"
To count back from the end of the string use the size selector
s := 'abcdefg'
s copyFrom: 2 to: s size - 1
Note:
- Take care with message concatenations. Can generate useless intermediate versions.
- Benchmark it.
- If this is worth, use a stream to avoid creating multiple intermediary strings.
String streamContents: [ :stream |
stream nextPutAll: 'This'; nextPutAll: ' is '; nextPutAll: 'crazy' ]
String streamContents: [ :stream |
stream nextPutAll: 'abcdefg';
space;
nextPutAll: '123456';
space.
'7890' putOn: stream. ].
Symbols
-------
Symbols are unique immutable strings.
A symbol starts with a #: #ProfStef
Two symbols with the same representation points to the same object.
Two strings with the same representation may be different objects depending on compiler optimisations.
Symbols vs. Strings:
- A symbol is a read-only and unique object.
- A string is a mutable object (for now; might change in future Pharo version).
- Symbols are used as method selectors.
- Symbols are good candidates for identity based dictionaries (IdentityDictionary).
There is one and only one Symbol #ProfStef.
There may be several 'ProfStef' String objects.
(Message == returns true if the two objects are the SAME).
'ProfStef' asSymbol.
#ProfStef asString.
(2 asString) == (2 asString).
(2 asString) asSymbol == (2 asString) asSymbol.
(Smalltalk globals at: #ProfStef ProfStef) next.
Numbers, Fractions, Floats
--------------------------
#TODO: =, ~=, ==
Number - Integer
----------------
SmallInteger -> Integer -> Number -> Magnitude
1 class.
1 class maxVal.
9 squared.
5 between: 4 and: 6
1 max: 3.
1 odd.
2 even.
-3 abs.
3 negated.
3 reciprocal.
5 factorial
Integer primesUpTo: 14
(Integer primesUpTo: 14) sum
Integer expressed in binary:
2r100 "4"
2r101 "5"
Integer expressed in hexadecimal
16r7 "7'
16rA "10'
16rF "15'
Numbers - Fraction
------------------
Fraction -> Number -> Magnitude
1/3.
(1/3) class. "This is a Fraction"
(1/3) + (4/5).
Number - Real/Float
-------------------
SmallFloat64 -> Float -> Number -> Magnitude
1.5
2.4e1 "24"
2.4e2 "240"
2.4e3 "2400"
(1/3) asFloat. "This is a float"
Float pi.
355 / 113 closeTo: Float pi
Booleans, Conditions
--------------------
true is the unique instance of class True.
false is the unique instance of class False.
& | not
or: and: "lazy evaluation"
xor:
ifTrue:ifFalse:
ifFalse:ifTrue: ...
true
false
false not.
true | false.
true & false.
true or: false.
true and: false.
3 < 10
ifTrue: [Transcript show: 'Indeed, 3 is less than 10'].
myProtocol
ifEmpty: [ 'As yet unclassified' ]
self listItems
ifNotEmpty: [ :aList | aList at: index ]
Notice that when the receiver is not empty we get it as argument (no need to ask it again).
Associations / Pairs
--------------------
An Association defines a key/value pair:
'January' -> 31.
('January' -> 31) key.
('January' -> 31) value.
Teapot configure: { #defaultOutput −> #json. #port −> 8181 . #debugMode −> true }.
Console Output
--------------
Transcript open.
Transcript show: 'Hello '.
Transcript show: 'Pharo'.
Transcript cr.
Transcript clear
Using the cascade operator:
Transcript
show: 'Hello ';
show: 'Pharo';
cr.
Loops
-----
Loops are high-level collection iterators, implemented as regular methods. Some loops:
to:do:
to:by:do:
timesRepeat:
1 to: 100 do: [:i | Transcript show: i asString; cr].
1 to: 100 by: 3 do: [:i | Transcript show: i asString; cr].
100 to: 0 by: -2 do: [:i | Transcript show: i asString; cr].
3 timesRepeat: [Transcript show: 'Yes yes';cr]
whileTrue:
whileFalse:
Collections
===========
First element is at index 1.
Collections can contain any sort of objects (collections are heterogenous).
Common collections:
- Array (fixed size, direct access)
- OrderedCollection (dynamically growing)
- Set (no duplicates)
- Dictionary (key-based, aka. maps)
Common messages working on all collections:
1. Creation: with: anElt, with:with:, withAll: aCollection
2. Accessing: size, at: anIndex, at: anIndex put: anElt
3. Testing: isEmpty, includes: anElt, contains: aBlock
4. Adding: add: anElement, addAll: aCollection
5. Removing: remove: anElt, remove: anElt ifAbsent: aBlock, removeAll: aCollection
6. Enumerating: do: aBlock, collect: aBlock, select: aBlock, reject: aBlock, detect: aBlock, ...
7. Converting: asBag, asSet, asOrderedCollection, asSortedCollection, asArray
Collections - Arrays
--------------------
Collections and thus Arrays start at index 1 (so not 0).
#(7 7 3 13).
#(7 'test' 3 'yes yes').
#(2 4 4 4 5 5 7 9) stdev.
#(2 4 4 4 5 5 7 9) average.
#(2 4 4 4 5 5 7 9) - 1.
Array new: 3.
> #(nil nil nil)
(Array new: 3)
at: 1 put: 'I';
at: 2 put: 'am';
at: 3 put: 'crazy';
yourself.
#('I' 'am' 'crazy') at: 3.
| me |
me := #('I' 'am' 'crazy').
me at: 3 put: 'not crazy'.
Array with: 'I' with: 'am' with: 'crazy'.
Types of arrays:
- Literal array
- Dynamic arrays
Literal array can only contain objects that have a textual (literal) representation: numbers, strings, nil, symbols, boolean
Literal arrays are created at parse time.
Literal arrays are not created using messages.
Examples:
#(1 2 3).
#(1 2 3 #(4 5 6)).
#(45 'milou' 1300 true #tintin)
#(1 2 3 #(4 5 6)) size.
#(1 2 4) isEmpty.
#(1 2 3) first.
#(1 2 3) last.
#(1 2 3) at: 3.
Dynamic arrays are created at runtime using messages.
Literal arrays are created at compile time by the parser when the expression is read and not during the execution.
Dynamic arrays execute expressions.
Examples:
Array with: 45 with: 38 with: 'milou' with: 8
#('hello' 'World') at: 2 put: 'Pharo'; yourself.
Defining dynamic arrays is tedious:
| array |
array := (Array new: 2).
array at: 1 put: 10 @ 10 ; at: 2 put: (Point x: 100 y: 200). array
{ expression1 . expression2 } is syntactic sugar to create dynamic arrays:
{ (2+3) . (6*6) }.
{ (2+3) . (6*6) . 'hello', ' Stef'}
{(10@20) . (100@200)}
{Point x: 10 y: 20 . Point x: 100 y: 200}
{} executes expressions while #() does not!
() inside a literal array produces a nested literal array!
Three ways to create arrays:
- Literal syntax: #( ) (no message)
- Using messages: Array new: 3, Array with: 45
- Syntactic sugar: Dynamic { . . }
Collections - OrderedCollection
-------------------------------
- Sequenceable
- Growing size
- add:
- remove:
- addFirst:
OrderedCollection new: 3.
OrderedCollection new: 3 withAll: 'a'
> an OrderedCollection('a' 'a' 'a')
OrderedCollection withAll: #(7 7 3 13)
> an OrderedCollection(7 7 3 13)
OrderedCollection new
add: 56;
add: 33;
yourself.
| ordCol |
ordCol := OrderedCollection new.
ordCol add: 'Two'; add: 'Three'; addFirst: 'One'.
Collections - Set
-----------------
- Mathematical set, so no duplicates.
- Growing size.
- Can contain any object including other Sets.
- add:
- remove:
Set newFrom: #(1 2 3).
Set newFrom: {1. 2. 3}.
Set withAll: #(1 2 3).
Set with: 1 with:2 with 3.
#(1 2 3) asSet.
#(1 2 3) as: Set.
{1. 2. 3} asSet.
{1. 2. 3} as: Set.
Set withAll: #(7 7 3 13).
> a Set( 7 3 13).
#(a b c d e f) asSet intersection: #(f d b) asSet
Collections - Dictionary
------------------------
- Key/values.
- Growing size.
- Accessing: at:, at:ifAbsent:, keys, values.
- Changing/adding: at:put:, at:ifAbsentPut:
- Iterating: do:, keysDo:, valuesDo:, keysAndValuesDo:
| days |
days := Dictionary new.
days
at: #January put: 31;
at: #February put: 28;
at: #March put: 31.
| days |
days := { #January -> 31. #February -> 28. #March -> 31} asDictionary.
days at: #February.
days at: #FakeMonth.