### Smalltalk Transcript Output Examples Source: https://learnxinyminutes.com/smalltalk/index Demonstrates how to use the Transcript to display various types of output, including strings, characters, and control characters like spaces and newlines. It also shows how to clear the transcript and flush the output buffer. ```Smalltalk Transcript clear. Transcript show: 'Hello World'. Transcript nextPutAll: 'Hello World'. Transcript nextPut: $A. Transcript space. Transcript tab. Transcript cr. 'Hello' printOn: Transcript. 'Hello' storeOn: Transcript. Transcript endEntry. ``` -------------------------------- ### Smalltalk Array Initialization and Basic Operations Source: https://learnxinyminutes.com/smalltalk/index Demonstrates how to create and initialize arrays in Smalltalk, along with fundamental operations such as checking emptiness, getting size, accessing elements, and testing for inclusion. It also shows subarray creation and finding element indices. ```Smalltalk | b x y z sum max | x := #(4 3 2 1). "constant array" z := #(1 2 3 'hi'). "mixed type array" x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements" x := Array new: 4. "allocate an array with specified size" x "set array elements" at: 1 put: 5; at: 2 put: 4; at: 3 put: 3; at: 4 put: 2. b := x isEmpty. "test if array is empty" y := x size. "array size" y := x at: 4. "get array element at index" b := x includes: 3. "test if element is in array" y := x copyFrom: 2 to: 4. "subarray" y := x indexOf: 3 ifAbsent: [0]. "first position of element within array" y := x occurrencesOf: 3. "number of times object in collection" ``` -------------------------------- ### Smalltalk Variable Assignment Examples Source: https://learnxinyminutes.com/smalltalk/index Illustrates different ways to assign values to variables in Smalltalk, including simple assignment, compound assignment, and assigning newly allocated object instances. It also shows syntax variations like `_` for assignment in Squeak. ```Smalltalk | x y | x _ 4. x := 5. x := y := z := 6. x := (y := 6) + 1. x := Object new. ``` -------------------------------- ### Smalltalk Iteration Statements: Loops and Blocks Source: https://learnxinyminutes.com/smalltalk/index Provides examples of various iteration constructs in Smalltalk, including `whileTrue:`, `whileFalse:`, `timesRepeat:`, `to:do:`, `to:by:do:`, and iterating over array elements. ```smalltalk | x y | x := 4. y := 1. [x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" [x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop" x timesRepeat: [y := y * 2]. "times repeat loop (i := 1 to x)" 1 to: x do: [:a | y := y * 2]. "for loop" 1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" #(5 4 3) do: [:a | x := x + a]. "iterate over array elements" ``` -------------------------------- ### Smalltalk Rectangle Creation Source: https://learnxinyminutes.com/smalltalk/index A simple example of creating a Rectangle object from user input in Smalltalk. This snippet assumes a context where user input can be captured and used to define a rectangle. ```Smalltalk Rectangle fromUser. ``` -------------------------------- ### Smalltalk Conditional Execution Example Source: https://learnxinyminutes.com/smalltalk/index An example of conditional execution in Smalltalk, where a block of code is executed only if a certain condition is met. This snippet shows message sending for comparison and conditional logic. ```Smalltalk self size > 4 ifTrue: [^argumentObject sizeRelatingTo: self]. ``` -------------------------------- ### Smalltalk SortedCollection Properties and Access Source: https://learnxinyminutes.com/smalltalk/index Covers methods for checking the state and retrieving information about a SortedCollection. This includes checking if the collection is empty, getting the size, accessing elements by index, retrieving the first and last elements, and checking for element inclusion. ```Smalltalk b := x isEmpty. "test if empty" y := x size. "number of elements" y := x at: 2. "retrieve element at index" y := x first. "retrieve first element in collection" y := x last. "retrieve last element in collection" b := x includes: 4. "test if element is in collection" ``` -------------------------------- ### Smalltalk SortedCollection Creation and Initialization Source: https://learnxinyminutes.com/smalltalk/index Demonstrates how to create and initialize a SortedCollection in Smalltalk. This includes creating a collection with a specific capacity, allocating a new collection, and setting custom sorting criteria using a sort block. ```Smalltalk | b x y sum max | x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" x := SortedCollection new. "allocate collection" x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria" ``` -------------------------------- ### Smalltalk Interval Creation and Operations Source: https://learnxinyminutes.com/smalltalk/index Demonstrates creating intervals with and without specified increments, and performing various operations like checking emptiness, size, element inclusion, iteration, conditional testing, selection, rejection, collection, detection, summation, and conversion to different collection types. ```Smalltalk | b x y sum max | x := Interval from: 5 to: 10. "create interval object" x := 5 to: 10. x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment" x := 5 to: 10 by: 2. b := x isEmpty. "test if empty" y := x size. "number of elements" x includes: 9. "test if element is in collection" x do: [:k | Transcript show: k printString; cr]. "iterate over interval" b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" y := x select: [:a | a > 7]. "return collection of elements that pass test" y := x reject: [:a | a < 2]. "return collection of elements that fail test" y := x collect: [:a | a + a]. "transform each element for new collection" y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" sum := x inject: 0 into: [:a :c | a + c]. "sum elements" max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" ifTrue: [a] ifFalse: [c]]. y := x asArray. "convert to array" y := x asOrderedCollection. "convert to ordered collection" y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" ``` -------------------------------- ### Smalltalk Association Key-Value Operations Source: https://learnxinyminutes.com/smalltalk/index Illustrates the creation of an association (key-value pair) in Smalltalk and how to retrieve the key and value from it. ```Smalltalk | x y | x := #myVar->'hello'. y := x key. y := x value. ``` -------------------------------- ### Date Manipulation and Creation in Smalltalk Source: https://learnxinyminutes.com/smalltalk/index Illustrates various ways to create, manipulate, and query Date objects in Smalltalk. Covers creating dates from the current time, strings, and components, as well as calculating days in months/years, weekdays, and date comparisons. No external dependencies beyond the standard Date class. ```Smalltalk | x y | x := Date today. "create date for today" x := Date dateAndTimeNow. "create date from current time/date" x := Date readFromString: '01/02/1999'. "create date from formatted string" x := Date newDay: 12 month: #July year: 1999 "create date from parts" x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901" y := Date dayOfWeek: #Monday. "day of week as int (1-7)" y := Date indexOfMonth: #January. "month of year as int (1-12)" y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)" y := Date daysInYear: 1996. "days in year (365|366)" y := Date nameOfDay: 1 "weekday name (#Monday,...)" y := Date nameOfMonth: 1. "month name (#January,...)" y := Date leapYear: 1996. "1 if leap year; 0 if not leap year" y := x weekday. "day of week (#Monday,...)" y := x previous: #Monday. "date for previous day of week" y := x dayOfMonth. "day of month (1-31)" y := x day. "day of year (1-366)" y := x firstDayOfMonth. "day of year for first day of month" y := x monthName. "month of year (#January,...)" y := x monthIndex. "month of year (1-12)" y := x daysInMonth. "days in month (1-31)" y := x year. "year (19xx)" y := x daysInYear. "days in year (365|366)" y := x daysLeftInYear. "days left in year (364|365)" y := x asSeconds. "seconds elapsed since 1/1/1901" y := x addDays: 10. "add days to date object" y := x subtractDays: 10. "subtract days to date object" y := x subtractDate: (Date today). "subtract date (result in days)" y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date" b := (x <= Date today). "comparison" ``` -------------------------------- ### Smalltalk ReadWriteStream Operations Source: https://learnxinyminutes.com/smalltalk/index Illustrates the use of Smalltalk's ReadWriteStream for both reading and writing to a stream. This includes creating streams, setting positions, reading lines and characters, writing new data, peeking, and checking for the end of the stream. It also shows how to initialize streams with specific content and ranges. ```Smalltalk | b x ios | ios := ReadWriteStream on: 'Hello read stream'. ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5. ios := ReadWriteStream with: 'Hello read stream'. ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10. ios position: 0. [(x := ios nextLine) notNil] whileTrue: [Transcript show: x; cr]. ios position: 6. ios position. ios nextPutAll: 'Chris'. x := ios next. x := ios peek. x := ios contents. b := ios atEnd. ``` -------------------------------- ### FileStream Operations in Smalltalk Source: https://learnxinyminutes.com/smalltalk/index Demonstrates creating, writing to, and reading from files using FileStream. Includes methods for sequential and random access, as well as checking for the end of a file. Requires a file named 'ios.txt' to exist for reading operations. ```Smalltalk | b x ios | ios := FileStream newFileNamed: 'ios.txt'. ios nextPut: $H; cr. ios nextPutAll: 'Hello File'; cr. 'Hello File' printOn: ios. 'Hello File' storeOn: ios. ios close. ios := FileStream oldFileNamed: 'ios.txt'. [(x := ios nextLine) notNil] whileTrue: [Transcript show: x; cr]. ios position: 3. x := ios position. x := ios next. x := ios peek. b := ios atEnd. ios close. ``` -------------------------------- ### Smalltalk IdentityDictionary Operations Source: https://learnxinyminutes.com/smalltalk/index Demonstrates the usage of IdentityDictionary in Smalltalk for managing key-value pairs. It covers initialization, adding elements, checking for emptiness, size, inclusion, retrieval, removal, and various iteration methods. It also shows how to interact with global dictionaries like Smalltalk. ```Smalltalk | b x y | x := Dictionary new. "allocate collection" x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection" x at: #e put: 3. "set element at index" b := x isEmpty. "test if empty" y := x size. "number of elements" y := x at: #a ifAbsent: []. "retrieve element at index" y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block" y := x removeKey: #e ifAbsent: []. "remove element from collection" b := x includes: 3. "test if element is in values collection" b := x includesKey: #a. "test if element is in keys collection" y := x occurrencesOf: 3. "number of times object in collection" y := x keys. "set of keys" y := x values. "bag of values" x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection" x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection" x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations" x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values" show: aKey printString; space; show: aValue printString; cr]. b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" y := x select: [:a | a > 2]. "return collection of elements that pass test" y := x reject: [:a | a < 2]. "return collection of elements that fail test" y := x collect: [:a | a + a]. "transform each element for new collection" y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" sum := x inject: 0 into: [:a :c | a + c]. "sum elements" max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" ifTrue: [a] ifFalse: [c]]. y := x asArray. "convert to array" y := x asOrderedCollection. "convert to ordered collection" y := x asSortedCollection. "convert to sorted collection" y := x asBag. "convert to bag collection" y := x asSet. "convert to set collection" Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary" x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary" Transcript show: (CMRGlobal printString). "entries are directly accessible by name" Smalltalk keys do: [ :k | "print out all classes" ((Smalltalk at: k) isKindOf: Class) ifFalse: [Transcript show: k printString; cr]]. Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary" CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary" CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo" CMRDictionary size. "dictionary size" CMRDictionary keys do: [ :k | "print out keys in dictionary" Transcript show: k printString; cr]. CMRDictionary values do: [ :k | "print out values in dictionary" Transcript show: k printString; cr]. CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values" Transcript show: aKey printString; space; show: aValue printString; cr]. CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values" Transcript show: aKeyValue printString; cr]. Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary" Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary" ``` -------------------------------- ### Time Operations and Creation in Smalltalk Source: https://learnxinyminutes.com/smalltalk/index Demonstrates creating and manipulating Time objects in Smalltalk. Includes creating times from current time, strings, and seconds since midnight, as well as performing arithmetic on times and timing code execution. No external dependencies beyond the standard Time class. ```Smalltalk | x y | x := Time now. "create time from current time" x := Time dateAndTimeNow. "create time from current time/date" x := Time readFromString: '3:47:26 pm'. "create time from formatted string" x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight" y := Time millisecondClockValue. "milliseconds since midnight" y := Time totalSeconds. "total seconds since 1/1/1901" y := x seconds. "seconds past minute (0-59)" y := x minutes. "minutes past hour (0-59)" y := x hours. "hours past midnight (0-23)" y := x addTime: (Time now). "add time to time object" y := x subtractTime: (Time now). "subtract time to time object" y := x asSeconds. "convert time to seconds" x := Time millisecondsToRun: [ "timing facility" 1 to: 1000 do: [:index | y := 3.14 * index]]. b := (x <= Time now). "comparison" ``` -------------------------------- ### Smalltalk Point Operations Source: https://learnxinyminutes.com/smalltalk/index Demonstrates various arithmetic and utility operations on Point objects in Smalltalk. These include creation, coordinate access, negation, absolute value, rounding, truncation, scaling, addition, subtraction, multiplication, division, modulo, and dot product. ```Smalltalk | x y | x := 200@100. "obtain a new point" y := x x. "x coordinate" y := x y. "y coordinate" x := 200@100 negated. "negates x and y" x := (-200@-100) abs. "absolute value of x and y" x := (200.5@100.5) rounded. "round x and y" x := (200.5@100.5) truncated. "truncate x and y" x := 200@100 + 100. "add scale to both x and y" x := 200@100 - 100. "subtract scale from both x and y" x := 200@100 * 2. "multiply x and y by scale" x := 200@100 / 2. "divide x and y by scale" x := 200@100 // 2. "divide x and y by scale" x := 200@100 \ 3. "remainder of x and y by scale" x := 200@100 + 50@25. "add points" x := 200@100 - 50@25. "subtract points" x := 200@100 * 3@4. "multiply points" x := 200@100 // 3@4. "divide points" x := 200@100 max: 50@200. "max x and y" x := 200@100 min: 50@200. "min x and y" x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)" ``` -------------------------------- ### Smalltalk SortedCollection Detection and Aggregation Source: https://learnxinyminutes.com/smalltalk/index Shows how to detect specific elements and aggregate collection values. Includes finding the first element that meets a condition and calculating sums or finding maximum values using injection. ```Smalltalk y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" sum := x inject: 0 into: [:a :c | a + c]. "sum elements" max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" ifTrue: [a] ifFalse: [c]]. ``` -------------------------------- ### Smalltalk Block Usage and Arguments Source: https://learnxinyminutes.com/smalltalk/index Demonstrates the creation and usage of Smalltalk blocks, including simple blocks, blocks with arguments, and the use of local variables. Note that local variables in blocks are not supported in Squeak. ```smalltalk | x y z | x := [ y := 1. z := 2. ]. x value. "simple block usage" x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing" Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing" "x := [ | z | z := 1.]. *** localvars not available in squeak blocks" ``` -------------------------------- ### Smalltalk Array Iteration and Transformation Source: https://learnxinyminutes.com/smalltalk/index Explains how to iterate over array elements using `do:`, and how to transform arrays using methods like `select:`, `reject:`, and `collect:`. It also covers conditional testing of elements with `conform:` and detecting specific elements with `detect:ifNone:`. ```Smalltalk x do: [:a | Transcript show: a printString; cr]. "iterate over the array" b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" y := x select: [:a | a > 2]. "return collection of elements that pass test" y := x reject: [:a | a < 2]. "return collection of elements that fail test" y := x collect: [:a | a + a]. "transform each element for new collection" y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" ``` -------------------------------- ### Smalltalk Pen Drawing Operations Source: https://learnxinyminutes.com/smalltalk/index Illustrates how to use the Pen class in Smalltalk for graphical drawing. It covers pen initialization, setting nib properties, color, positioning, drawing actions (up/down), movement, and text rendering. ```Smalltalk | myPen | Display restoreAfter: [ Display fillWhite. myPen := Pen new. "get graphic pen" myPen squareNib: 1. myPen color: (Color blue). "set pen color" myPen home. "position pen at center of display" myPen up. "makes nib unable to draw" myPen down. "enable the nib to draw" myPen north. "points direction towards top" myPen turn: -180. "add specified degrees to direction" myPen direction. "get current angle of pen" myPen go: 50. "move pen specified number of pixels" myPen location. "get the pen position" myPen goto: 200@200. "move to specified point" myPen place: 250@250. "move to specified point without drawing" myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1). Display extent. "get display width@height" Display width. "get display width" Display height. "get display height" ]. ``` -------------------------------- ### Smalltalk Dynamic Message Calling Source: https://learnxinyminutes.com/smalltalk/index Demonstrates dynamic message sending and evaluation in Smalltalk using `perform:`, `Compiler evaluate:`, and `Message` objects. It covers unary, binary, and keyword messages with varying arguments. ```Smalltalk | receiver message result argument keyword1 keyword2 argument1 argument2 | "unary message" receiver := 5. message := 'factorial' asSymbol. result := receiver perform: message. result := Compiler evaluate: ((receiver storeString), ' ', message). result := (Message new setSelector: message arguments: #()) sentTo: receiver. "binary message" receiver := 1. message := '+' asSymbol. argument := 2. result := receiver perform: message withArguments: (Array with: argument). result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)). result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver. "keyword messages" receiver := 12. keyword1 := 'between:' asSymbol. keyword2 := 'and:' asSymbol. argument1 := 10. argument2 := 20. result := receiver perform: (keyword1, keyword2) asSymbol withArguments: (Array with: argument1 with: argument2). result := Compiler evaluate: ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)). result := (Message new setSelector: (keyword1, keyword2) asSymbol arguments: (Array with: argument1 with: argument2)) sentTo: receiver. ``` -------------------------------- ### Smalltalk Miscellaneous Operations: Hashing, Copying, and Input Source: https://learnxinyminutes.com/smalltalk/index This snippet covers a range of miscellaneous but useful operations in Smalltalk. It demonstrates how to compute hash values, perform different types of object copying (shallow, deep, very deep), condense change files, and prompt the user for input. ```Smalltalk | x | x := 1.2 hash. "hash value for object" y := x copy. "copy object" y := x shallowCopy. "copy object (not overridden)" y := x deepCopy. "copy object and instance vars" y := x veryDeepCopy. "complete tree copy using a dictionary" "Smalltalk condenseChanges." "compress the change file" x := FillInTheBlank request: 'Prompt Me'. "prompt user for input" Utilities openCommandKeyHelp ``` -------------------------------- ### Smalltalk Debugging and Error Handling Techniques Source: https://learnxinyminutes.com/smalltalk/index This snippet illustrates various debugging tools and error-handling mechanisms available in Smalltalk. It includes methods for inspecting objects, setting breakpoints, raising errors, and handling unimplemented messages. ```Smalltalk | a b x | x yourself. "returns receiver" String browse. "browse specified class" x inspect. "open object inspector window" x confirm: 'Is this correct?'. x halt. "breakpoint to open debugger window" x halt: 'Halt message'. x notify: 'Notify text'. x error: 'Error string'. "open up error window with title" x doesNotUnderstand: #cmrMessage. "flag message is not handled" x shouldNotImplement. "flag message should not be implemented" x subclassResponsibility. "flag message as abstract" x errorImproperStore. "flag an improper store into indexable object" x errorNonIntegerIndex. "flag only integers should be used as index" x errorSubscriptBounds. "flag subscript out of bounds" x primitiveFailed. "system primitive failed" a := 'A1'. b := 'B2'. a become: b. "switch two objects" Transcript show: a, b; cr. ``` -------------------------------- ### Smalltalk OrderedCollection Creation and Manipulation Source: https://learnxinyminutes.com/smalltalk/index Demonstrates how to create an OrderedCollection and perform various operations such as adding, removing, and modifying elements. This includes methods for adding at the beginning or end, adding multiple elements, and updating elements by index. ```Smalltalk | b x y sum max | x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" x := OrderedCollection new. "allocate collection" x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" y := x addFirst: 5. "add element at beginning of collection" y := x removeFirst. "remove first element in collection" y := x addLast: 6. "add element at end of collection" y := x removeLast. "remove last element in collection" y := x addAll: #(7 8 9). "add multiple elements to collection" y := x removeAll: #(7 8 9). "remove multiple elements from collection" x at: 2 put: 3. "set element at index" y := x remove: 5 ifAbsent: []. "remove element from collection" b := x isEmpty. "test if empty" y := x size. "number of elements" y := x at: 2. "retrieve element at index" y := x first. "retrieve first element in collection" y := x last. "retrieve last element in collection" b := x includes: 5. "test if element is in collection" y := x copyFrom: 2 to: 3. "subcollection" y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" y := x occurrencesOf: 3. "number of times object in collection" ``` -------------------------------- ### Smalltalk Array Aggregation and Shuffling Source: https://learnxinyminutes.com/smalltalk/index Illustrates methods for aggregating array elements, such as calculating the sum and finding the maximum element using `inject:into:`. It also demonstrates how to randomly shuffle the elements of an array using the `shuffled` method. ```Smalltalk sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements" sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements" sum := x inject: 0 into: [:a :c | a + c]. "sum array elements" max := x inject: 0 into: [:a :c | (a > c) "find max element in array" ifTrue: [a] ifFalse: [c]]. y := x shuffled. "randomly shuffle collection" ``` -------------------------------- ### Smalltalk: Boolean Operations and Comparisons Source: https://learnxinyminutes.com/smalltalk/index Illustrates various boolean operations and comparison methods in Smalltalk. This includes equality, inequality, identity, logical AND, OR, NOT, and specific tests for numeric properties, character casing, and object types. Short-circuiting logical operators are also shown. ```Smalltalk | b x y | x := 1. y := 2. b := (x = y). "equals" b := (x ~= y). "not equals" b := (x == y). "identical" b := (x ~~ y). "not identical" b := (x > y). "greater than" b := (x < y). "less than" b := (x >= y). "greater than or equal" b := (x <= y). "less than or equal" b := b not. "boolean not" b := (x < 5) & (y > 1). "boolean and" b := (x < 5) | (y > 1). "boolean or" b := (x < 5) and: [y > 1]. "boolean and (short-circuit)" b := (x < 5) or: [y > 1]. "boolean or (short-circuit)" b := (x < 5) eqv: (y > 1). "test if both true or both false" b := (x < 5) xor: (y > 1). "test if one true and other false" b := 5 between: 3 and: 12. "between (inclusive)" b := 123 isKindOf: Number. "test if object is class or subclass of" b := 123 isMemberOf: SmallInteger. "test if object is type of class" b := 123 respondsTo: #sqrt. "test if object responds to message" b := x isNil. "test if object is nil" b := x isZero. "test if number is zero" b := x positive. "test if number is positive" b := x strictlyPositive. "test if number is greater than zero" b := x negative. "test if number is negative" b := x even. "test if number is even" b := x odd. "test if number is odd" b := x isLiteral. "test if literal constant" b := x isInteger. "test if object is integer" b := x isFloat. "test if object is float" b := x isNumber. "test if object is number" b := $A isUppercase. "test if upper case character" b := $A isLowercase. "test if lower case character" ``` -------------------------------- ### Smalltalk SortedCollection Subcollection and Indexing Source: https://learnxinyminutes.com/smalltalk/index Explains how to create subcollections and find element positions within a SortedCollection. Methods include copying a range of elements and finding the index of a specific element. ```Smalltalk y := x copyFrom: 2 to: 3. "subcollection" y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" ``` -------------------------------- ### Smalltalk OrderedCollection Iteration and Transformation Source: https://learnxinyminutes.com/smalltalk/index Shows how to iterate over elements in an OrderedCollection, test conditions on elements, and transform them into new collections. This includes methods for performing actions on each element, selecting, rejecting, and collecting elements based on criteria. ```Smalltalk x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" y := x select: [:a | a > 2]. "return collection of elements that pass test" y := x reject: [:a | a < 2]. "return collection of elements that fail test" y := x collect: [:a | a + a]. "transform each element for new collection" y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" ``` -------------------------------- ### Smalltalk Data Type Conversions Source: https://learnxinyminutes.com/smalltalk/index Shows how to convert between different data types in Smalltalk, such as numbers to integers, floats, fractions, characters, and strings. It also covers base conversions for numbers. ```Smalltalk | x | x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" x := 3.99 asFraction. "convert number to fraction" x := 3 asFloat. "convert number to float" x := 65 asCharacter. "convert integer to character" x := $A asciiValue. "convert character to integer" x := 3.99 printString. "convert object to string via printOn:" x := 3.99 storeString. "convert object to string via storeOn:" x := 15 radix: 16. "convert to string in given base" x := 15 printStringBase: 16. x := 15 storeStringBase: 16. ``` -------------------------------- ### Smalltalk Conditional Statements: ifTrue, ifFalse, and Dictionary-based Switch Source: https://learnxinyminutes.com/smalltalk/index Shows how to implement conditional logic in Smalltalk using `ifTrue:`, `ifFalse:`, and nested conditional statements. It also demonstrates a 'switch' or 'case' like functionality using a Dictionary. ```smalltalk | x | x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else" "if then else" x > 10 ifTrue: [Transcript show: 'ifTrue'; cr] ifFalse: [Transcript show: 'ifFalse'; cr]. "if else then" x > 10 ifFalse: [Transcript show: 'ifFalse'; cr] ifTrue: [Transcript show: 'ifTrue'; cr]. Transcript show: (x > 10 ifTrue: ['ifTrue'] ifFalse: ['ifFalse']); cr. "nested if then else" Transcript show: (x > 10 ifTrue: [x > 5 ifTrue: ['A'] ifFalse: ['B']] ifFalse: ['C']); cr. "switch functionality" switch := Dictionary new. switch at: $A put: [Transcript show: 'Case A'; cr]. switch at: $B put: [Transcript show: 'Case B'; cr]. switch at: $C put: [Transcript show: 'Case C'; cr]. result := (switch at: $B) value. ``` -------------------------------- ### Smalltalk Symbol Operations Source: https://learnxinyminutes.com/smalltalk/index Demonstrates assignment, concatenation, emptiness check, size, character access, substring, searching, iteration, conditional checks, and conversion of symbols to other types in Smalltalk. ```smalltalk | b x y | x := #Hello. "symbol assignment" y := #Symbol, #Concatenation. "symbol concatenation (result is string)" b := x isEmpty. "test if symbol is empty" y := x size. "string size" y := x at: 2. "char at location" y := x copyFrom: 2 to: 4. "substring" y := x indexOf: $e ifAbsent: [0]. "first position of character within string" x do: [:a | Transcript show: a printString; cr]. "iterate over the string" b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" y := x select: [:a | a > $a]. "return all elements that meet condition" y := x asString. "convert symbol to string" y := x asText. "convert symbol to text" y := x asArray. "convert symbol to array" y := x asOrderedCollection. "convert symbol to ordered collection" y := x asSortedCollection. "convert symbol to sorted collection" y := x asBag. "convert symbol to bag collection" y := x asSet. "convert symbol to set collection" ``` -------------------------------- ### Smalltalk SortedCollection Iteration and Transformation Source: https://learnxinyminutes.com/smalltalk/index Details methods for iterating over elements and transforming the collection. This includes performing actions on each element, testing conditions for all elements, selecting elements based on a test, rejecting elements, and collecting transformed elements. ```Smalltalk x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" y := x select: [:a | a > 2]. "return collection of elements that pass test" y := x reject: [:a | a < 2]. "return collection of elements that fail test" y := x collect: [:a | a + a]. "transform each element for new collection" ``` -------------------------------- ### Smalltalk Character Manipulation and Operations Source: https://learnxinyminutes.com/smalltalk/index Demonstrates common operations on characters in Smalltalk, including assignment, case testing, letter/digit checks, conversion to numbers or strings, and character comparisons. ```smalltalk | x y b | x := $A. "character assignment" y := x isLowercase. "test if lower case" y := x isUppercase. "test if upper case" y := x isLetter. "test if letter" y := x isDigit. "test if digit" y := x isAlphaNumeric. "test if alphanumeric" y := x isSeparator. "test if separator char" y := x isVowel. "test if vowel" y := x digitValue. "convert to numeric digit value" y := x asLowercase. "convert to lower case" y := x asUppercase. "convert to upper case" y := x asciiValue. "convert to numeric ascii value" y := x asString. "convert to string" b := $A <= $B. "comparison" y := $A max: $B. ``` -------------------------------- ### Smalltalk String Operations Source: https://learnxinyminutes.com/smalltalk/index Demonstrates assignment, concatenation, emptiness check, size, character access, substring, searching, string allocation, element modification, iteration, conditional checks, and conversion of strings to other types in Smalltalk. ```smalltalk | b x y | x := 'This is a string'. "string assignment" x := 'String', 'Concatenation'. "string concatenation" b := x isEmpty. "test if string is empty" y := x size. "string size" y := x at: 2. "char at location" y := x copyFrom: 2 to: 4. "substring" y := x indexOf: $a ifAbsent: [0]. "first position of character within string" x := String new: 4. "allocate string object" x "set string elements" at: 1 put: $a; at: 2 put: $b; at: 3 put: $c; at: 4 put: $e. x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time" x do: [:a | Transcript show: a printString; cr]. "iterate over the string" b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" y := x select: [:a | a > $a]. "return all elements that meet condition" y := x asSymbol. "convert string to symbol" y := x asArray. "convert string to array" x := 'ABCD' asByteArray. "convert string to byte array" y := x asOrderedCollection. "convert string to ordered collection" y := x asSortedCollection. "convert string to sorted collection" y := x asBag. "convert string to bag collection" y := x asSet. "convert string to set collection" y := x shuffled. "randomly shuffle string" ``` -------------------------------- ### Smalltalk Class and Meta-Class Information Retrieval Source: https://learnxinyminutes.com/smalltalk/index This snippet demonstrates how to retrieve various properties of a Smalltalk class or meta-class, such as its name, category, comment, instance variables, selectors, and inheritance hierarchy. It covers both immediate and accumulated properties. ```Smalltalk | b x | x := String name. "class name" x := String category. "organization category" x := String comment. "class comment" x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc" x := String definition. "class definition" x := String instVarNames. "immediate instance variable names" x := String allInstVarNames. "accumulated instance variable names" x := String classVarNames. "immediate class variable names" x := String allClassVarNames. "accumulated class variable names" x := String sharedPools. "immediate dictionaries used as shared pools" x := String allSharedPools. "accumulated dictionaries used as shared pools" x := String selectors. "message selectors for class" x := String sourceCodeAt: #size. "source code for specified method" x := String allInstances. "collection of all instances of class" x := String superclass. "immediate superclass" x := String allSuperclasses. "accumulated superclasses" x := String withAllSuperclasses. "receiver class and accumulated superclasses" x := String subclasses. "immediate subclasses" x := String allSubclasses. "accumulated subclasses" x := String withAllSubclasses. "receiver class and accumulated subclasses" b := String instSize. "number of named instance variables" b := String isFixed. "true if no indexed instance variables" b := String isVariable. "true if has indexed instance variables" b := String isPointers. "true if index instance vars contain objects" b := String isBits. "true if index instance vars contain bytes/words" b := String isBytes. "true if index instance vars contain bytes" b := String isWords. "true if index instance vars contain words" Object withAllSubclasses size. "get total number of class entries" ```