List of methods if their implementation has at least two occurences of a word 'assert' in Smalltalk - smalltalk

I wanted to get the list of methods of a class if their implementation has at least two occurrences of a word 'assert' in Smalltalk.
Can somebody help me with this? Thanks in advance!

I'm not sure about the details of gnu-Smalltalk, but in Pharo, you can do something like this:
YourClass methods select: [ :method |
method sourceCode matchesRegex: '.*assert.*assert.*'. ]
Here I use a trivial regex to see if I can match two "assert" words in the source code.
However, with Smalltalk, it's easy to do more precise searches. Image, you want to see if a method sends at least two assert: messages. You can find such methods this way:
YourClass methods select: [ :method |
| numAsserts |
numAsserts := method ast allChildren count: [ :node |
node isMessage and: [ node selector = #assert: ] ].
numAsserts >= 2
]
In the example above, for each method, we simply count the number of AST nodes that are message sends, and have the assert: selector. Then we check if the number of these nodes is greater or equal to 2.

Related

Print a SortedCollection to screen using keysAndValueDo (smalltalk)

Hello i'm learning and am new to smalltalk and I'm trying to print my SortedCollection to screen trying to use keysAndValueDo but im not sure how its done, if anyone could give me a general example that would be great
Part 1 - Displaying to the screen
The most straight forward way to print to the screen in a GUI-based Smalltalk is to use the message:
Transcript show: 'some text'
(The Transcript is a system object that displays into a scrollable window).
To make sure there is a newline before each line of display text, we send the message cr to the Transcript
Transcript cr.
Transcript show: 'some text'.
A shorthand method, that saves us re-typing Transcript over and over, is to send Transcript a series of messages one after another. This is called a message cascade. Each time we end a message in ; it means send to the same receiver as the last message was sent to.
We can then shorten this again, as Smalltalk pays no attention to newlines in expressions.
The final display message cascade becomes:
Transcript cr; show: 'some text'.
Part 2: Enumerating aSortedCollection using keysAndValuesDo:
This keyword message is SequencableCollectionand its method header is:
keysAndValuesDo: aBlock
"Enumerate the receiver with all the keys (aka indices) and values."
(It works the same way in Dolphin, and in Squeak and its derivatives, Pharo and Cuis).
The keyword message keysAndValuesDo: takes a block argument.
A block is an anonymous object, with one method. Its method is defined between a matched pair of square brackets - a [ ... ] pair.
In this case, we need a local variable in the block for the key of each element of the collection, and another local variable for the value of each element.
We can call them anything we like, and in this case, it is the order that they appear in that is important. keysAndValuesDo: will put the element's key into the first local variable in the block, and will put the element's value into the second local variable in the block.
Local variables in a block are declared at the start of the block, and each variable name is identified by prefixing it with :. The local variable declarations are ended with a |.
The block then looks like
[:local1 :local2 |
"do something for each element, with the key in local1 and the value in local2"
]
I prefer meaningful local variable names, so I'll use eachKey and eachValue.
Part 3: Putting it all together
To enumerate through mySortedCollection
"Declare the mySortedCollection variable"
|mySortedCollection|
"Initialise the collection"
mySortedCollection := SortedCollection new.
"add in some data to the collection"
mySortedCollection add: ('First') ;
add: ('Second') ;
add: ('Third').
"Enumerate through the collection, displaying to the Transcript window"
mySortedCollection keysAndValuesDo:
[:eachKey :eachValue |
Transcript cr; show: eachKey; show: ' '; show: eachValue
] .
Paste the code into a Workspace (known as a Playground in Pharo, from version 4.0 onwards). Select the text. Once selected, right-click (on a two or three button mouse) and select "Do it" from the menu. Or use Ctrl-d as a keyboard shortcut. (The exact chording key may vary on your platform)
Final notes
In a SortedCollection or an OrderedCollection, the key is the index. The value is what is stored at element[index].
In a Dictionary, the key of the element is the key, and the value of the element is the value.
SortedCollections are sorted in order of the element values, according to the definition of the collections sort block. In the absence of a custom sort block, they will be added in ascending order. 'First', 'Second' and 'Third' are, coincidentally, in alphabetical order. It happens to work out nicely in this example.
The following example works with Pharo Smalltalk, other Smalltalk implementation might work similar.
First, look at existing print methods as examples. In case of SortedCollection, you find them in the printing protocol of its superclass Collection.
You will find that the printing of elements is defined in printElementsOn:. So you could overwrite this method in SortedCollection.
Here is a printElementsOn: method that will use keysAndValuesDo:, as you were asking for:
printElementsOn: aStream
aStream nextPut: $(.
self keysAndValuesDo: [:key :value |
aStream
nextPut: $(;
print: key;
nextPut: $:;
space;
print: value;
nextPut: $)].
aStream nextPut: $)
Now a collection that before printed:
"a SortedCollection(1 2 3 3 5 10)"
will print:
"a SortedCollection((1: 1)(2: 2)(3: 3)(4: 3)(5: 5)(6: 10))"

check if 2 linked list have the same elements regardless of order

Is there any way to check if 2 linked lists have the same elements regardless of order.
edit question:
I have fixed the code and given some more details:
this is the method that compares 2 lists
compare: object2
^ ((mylist asBag) = ((objetc2 getList) asBag)).
the method belongs to the class myClass that has a field : myLList. myList is a linkedList of type element.
I have compiled it in the workspace:
a: = element new id:1.
b:= element new id:2.
c:=element new id:3.
d: = element new id:1.
e:= element new id:2.
f:=element new id:3.
elements1 := myClass new.
elements addFirst:a.
elements addFirst:b.
elements addFirst:c.
elements2 := myClass new.
elements addFirst:d.
elements addFirst:e.
elements addFirst:f.
Transcript show: (elements1 compare:elements2).
so I am getting false.. seems like it checks for equality by reference rather than equality by value..
So I think the correct question to ask would be: how can I compare 2 Bags by value? I have tried the '=='..but it also returned false.
EDIT:
The question changed too much - I think it deserves a new question for itself.
The whole problem here is that (element new id: 1) = (element new id: 1) is giving you false. Unless it's particular class (or superclasses) redefine it, the = message is resolved comparing by identity (==) by default. That's why your code only works with a collection being compared with itself.
Test it with, for example, lists of numbers (which have the = method redefined to reflect what humans understand by numeric equality), and it will work.
You should redefine your element's class' = (and hashCode) methods for this to work.
Smalltalk handles everything by reference: all there exist is an object, which know (reference) other objects.
It would be wrong to say that two lists are equivalent if they are in different order, as the order is part of what a list means. A list without an order is what we call a bag.
The asBag message (as all of the other as<anotherCollectionType> messages) return a new collection of the named type with all the elements of the receiver. So, #(1 2 3 2) is an Array of four elements, and #(1 2 3 2) asBag is a bag containing those four elements. As it's a Bag, it doesn't have any particular order.
When you do bagA := Bag new. you are creating a new Bag instance, and reference it with bagA variable. But then you do bagA := myList asBag, so you lose the reference to the previous bag - the first assignment doesn't do anything useful in your code, as you don't use that bag.
Saying aBool ifTrue: [^true] ifFalse: [^false] has exactly the same meaning as saying ^aBool - so we prefer just to say that. And, as you only create those two new bags to compare them, you could simplify your whole method like this:
compareTo: anotherList
^ myList asBag = anotherList asBag
Read it out loud: this object (whatever it is) compares to another list if it's list without considering order is the same than the other list without order.
The name compareTo: is kind of weird for returning a boolean (containsSameElements: would be more descriptive), but you get the point much faster with this code.
Just to be precise about your questions:
1) It doesn't work because you're comparing bag1 and bag2, but just defined bagA and bagB.
2) It's not efficient to create those two extra bags just because, and to send the senseless ifTrue: message, but other way it's OK. You may implement a better way to compare the lists, but it's way better to rely on the implementation of asBag and the Bag's = message being performant.
3) I think you could see the asBag source code, but, yes, you can assume it to be something like:
Collection>>asBag
|instance|
instance := Bag new.
instance addAll: self.
^instance
And, of course, the addAll: method could be:
Collection>>addAll: anotherCollection
anotherCollection do: [ :element | self add: element ]
So, yes - it creates a new Bag with all the receiver's elements.
mgarciaisaia's answer was good... maybe too good! This may sound harsh, but I want you to succeed if you're serious about learning, so I reiterate my suggestion from another question that you pick up a good Smalltalk fundamentals textbook immediately. Depending on indulgent do-gooders to rework your nonsensical snippets into workable code is a very inefficient way to learn to program ;)
EDIT: The question has changed dramatically. The following spoke to the original three-part question, so I paraphrased the original questions inline.
Q: What is the problem? A: The problem is lack of fundamental Smalltalk understanding.
Q: Is converting to bags an efficient way to make the comparison? A: Although it's probably not efficient, don't worry about that now. In general, and especially at the beginning when you don't have a good intuition about it, avoid premature optimization - "make it work", and then only "make it fast" if justified by real-world profiling.
Q: How does #asBag work? A: The implementation of #asBag is available in the same living world as your own code. The best way to learn is to view the implementation directly (perhaps by "browsing implementors" if you aren't sure where it's defined") and answer your own question!! If you can't understand that implementation, see #1.

smalltalk returning string from block in VisualWorks

I want to return the value, that was passed int to the block. If it's a number, everything works great, but If I put in a String or boolean value, I get a "Message not understand".
q := [ :a | a].
Transcript show: ((q value:'123') value) printString.
I thought everything is treated the same, so I'm confused. But I guess I'm just missing something.
edit: it seem to work under Pharo...
The message "value" isn't implemented for Object in VisualWorks. Some applications add it in but it's not in the base class library. In some versions of VisualWorks it slipped into the base class library and was later taken out.
If you write your code like this it will work:
q := [ :a | a].
Transcript show: (q value:'123') printString.
Remove the send of #value. It is not necessary for your example as you described it. #value: is sent to the Block, which returns the argument, as you wanted. You then send #value to the argument, which works in Pharo because it returns self and is essentially a non-op.
This fixes your error because, as I suspected and David verified, VisualWorks Strings DNU #value.
n.b. As Bob said, the key missing info in your question is "Which object DNU which message?" In general, the more specific you are about your errors, the better the answers can be.
Works fine for me.
| q |
q := [ :a | a].
Transcript show: ((q value: true) value) printString.
| q |
q := [ :a | a].
Transcript show: ((q value: 123) value) printString.
If you have a DNU exception you will be able to see which object is receiving the message that is not understood. Post that information.

How to write additional methods in Smalltalk Collections which work only for Numeric Inputs?

I want to add a method "average" to array class.
But average doesn't make any sense if input array contains characters/strings/objects.
So I need to check if array contains only integers/floats.
Smalltalk says datatype check [checking if variable belongs to a particular datatype like int string array etc... or not] is a bad way of programming.
So what is best way to implement this?
The specification is somewhat incomplete. You'd need to specify what behavior the collection should show when you use it with non-numeric input.
There are a huge number of possibly desirable behaviors. Smalltalk supports most of them, except for the static typing solution (throw a compile-time error when you add a non-numeric thing to a numeric collection).
If you want to catch non-numeric objects as late as possible, you might just do nothing - objects without arithmetic methods will signal their own exceptions when you try arithmetic on them.
If you want to catch non-numeric elements early, implement a collection class which ensures that only numeric objects can be added (probably by signaling an exception when you add a non-numeric object is added).
You might also want to implement "forgiving" methods for sum or average that treat non-numeric objects as either zero-valued or non-existing (does not make a difference for #sum, but for #average you would only count the numeric objects).
In pharo at least there is
Collection >> average
^ self sum / self size
In Collections-arithmetic category. When you work with with a statically typed languages you are being hit by the language when you add non-number values to the collection. In dynamically typed languages you the same happens when you try to calculate average of inappropriate elements e.i. you try to send +, - or / to an object that does not understand it.
Don't think where you put data, think what are you doing with it.
It's reasonable to check type if you want to do different things, e.g.:
(obj isKindOf: Number) ifTrue: [:num| num doItForNum].
(obj isKindOf: Array ) ifTrue: [:arr| arr doItForArr].
But in this case you want to move the logic of type checking into the object-side.
So in the end it will be just:
obj doIt.
and then you'll have also something like:
Number >> doIt
"do something for number"
Array >> doIt
"do something for array"
(brite example of this is printOn: method)
I would have thought the Smalltalk answer would be to implement it for numbers, then be mindful not to send a collection of pets #sum or #average. Of course, if there later becomes a useful implementation for a pet to add itself to another pet or even an answer to #average, then that would be up to the implementer of Pet or PetCollection.
I did a similar thing when I implemented trivial algebra into my image. It allowed me to mix numbers, strings, and symbols in simple math equations. 2 * #x result in 2x. x + y resulted in x + y. It's a fun way to experiment with currencies by imagining algebra happening in your wallet. Into my walled I deposit (5 x #USD) + (15 * #CAN) for 5USD + 15CAN. Given an object that converts between currencies I can then answer what the total is in either CAN or USD.
We actually used it for supply-chain software for solving simple weights and measures. If a purchase order says it will pay XUSD/1TON of something, but the supplier sends foot-lbs of that same thing, then to verify the shipment value we need a conversion between ton and foot-lbs. Letting the library reduce the equation we're able to produce a result without molesting the input data, or without having to come up with new objects representing tons and foot-pounds or anything else.
I had high ambitions for the library (it was pretty simple) but alas, 2008 erased the whole thing...
"I want to add a method "average" to array class. But average doesn't make any sense if input array contains characters/strings/objects. So I need to check if array contains only integers/floats."
There are many ways to accomplish the averaging of the summation of numbers in an Array while filtering out non-numeric objects.
First I'd make it a more generic method by lifting it up to the Collection class so it can find more cases of reuse. Second I'd have it be generic for numbers rather than just floats and integers, oh it'll work for those but also for fractions. The result will be a float average if there are numbers in the collection array list.
(1) When adding objects to the array test them to ensure they are numbers and only add them if they are numbers. This is my preferred solution.
(2) Use the Collection #select: instance method to filter out the non-numbers leaving only the numbers in a separate collection. This makes life easy at the cost of a new collection (which is fine unless you're concerned with large lists and memory issues). This is highly effective, easy to do and a common solution for filtering collections before performing some operation on them. Open up a Smalltalk and find all the senders of #select: to see other examples.
| list numberList sum average |
list := { 100. 50. 'string'. Object new. 1. 90. 2/3. 88. -74. 'yup' }.
numberList := list select: [ :each | each isNumber ].
sum := numberList sum.
average := sum / (numberList size) asFloat.
Executing the above code with "print it" will produce the following for the example array list:
36.523809523809526
However if the list of numbers is of size zero, empty in other words then you'll get a divide by zero exception with the above code. Also this version isn't on the Collection class as an instance method.
(3) Write an instance method for the Collection class to do your work of averaging for you. This solution doesn't use the select since that creates intermediate collections and if your list is very large that's a lot of extra garbage to collect. This version merely loops over the existing collection tallying the results. Simple, effective. It also addresses the case where there are no numbers to tally in which case it returns the nil object rather than a numeric average.
Collection method: #computeAverage
"Compute the average of all the numbers in the collection. If no numbers are present return the nil object to indicate so, otherwise return the average as a floating point number."
| sum count average |
sum := 0.
count := 0.
self do: [ :each |
each isNumber ifTrue: [
count := count +1.
sum := sum + each.
]
].
count > 0 ifTrue: [
^average := sum / count asFloat
] ifFalse: [
^nil
]
Note the variable "average" is just used to show the math, it's not actually needed.
You then use the above method as follows:
| list averageOrNil |
list := { 100. 50. 'string'. Object new. 1. 90. 2/3. 88. -74. 'yup' }.
averageOrNil := list computeAverage.
averageOrNil ifNotNil: [ "got the average" ] ifNil: [ "there were no numbers in the list"
Or you can use it like so:
{
100. 50. 'string'. Object new. 1. 90. 2/3. 88. -74. 'yup'
} computeAverage
ifNotNil: [:average |
Transcript show: 'Average of list is: ', average printString
]
ifNil: [Transcript show: 'No numbers to average' ].
Of course if you know for sure that there are numbers in the list then you won't ever get the exceptional case of the nil object and you won't need to use an if message to branch accordingly.
Data Type/Class Checking At Runtime
As for the issue you raise, "Smalltalk says datatype check [checking if variable belongs to a particular datatype like int string array etc... or not] is a bad way of programming", there are ways to do things that are better than others.
For example, while one can use #isKindOf: Number to ask each element if it's not the best way to determine the "type" or "class" at runtime since it locks it in via predetermined type or class as a parameter to the #isKindOf: message.
It's way better to use an "is" "class" method such as #isNumber so that any class that is a number replies true and all other objects that are not numeric returns false.
A main point of style in Smalltalk when it comes to ascertaining the types or classes of things is that it's best to use message sending with a message that the various types/classes comprehend but behave differently rather than using explicit type/class checking if at all possible.
The method #isNumber is an instance method on the Number class in Pharo Smalltalk and it returns true while on the Object instance version it returns false.
Using polymorphic message sends in this away enables more flexibility and eliminates code that is often too procedural or too specific. Of course it's best to avoid doing this but reality sets in in various applications and you have to do the best that you can.
This is not the kind of thing you do in Smalltalk. You could take suggestions from the above comments and "make it work" but the idea is misguided (from a Smalltalk point of view).
The "Smalltalk" thing to do would be to make a class that could perform all such operations for you --computing the average, mean, mode, etc. The class could then do the proper checking for numerical inputs, and you could write how it would respond to bad input. The class would use a plain old array, or list or something. The name of the class would make it clear what it's usage would be for. The class could then be part of your deployment and could be exported/imported to different images as needed.
Make a new collection class; perhaps a subclass of Array, or perhaps of OrderedCollection, depending on what collection related behaviour you want.
In the new class' at:put: and/or add: methods test the new item for #isNumber and return an error if it fails.
Now you have a collection you can guarantee will have just numeric objects and nils. Implement your required functions in the knowledge that you won't need to deal with trying to add a Sealion to a Kumquat. Take care with details though; for example if you create a WonderNumericArray of size 10 and insert two values into it, when you average the array do you want to sum the two items and divide by two or by ten?

How do I perform a text search of a Squeak 3.7 image?

I have an image that runs on the 3.7 version of Squeak - I'd like to do a text search for strings and fragments of strings, over all classes, categories and selectors in the image. Is there a built in tool I can use for doing this sort of thing?
"method source containing it" (mentioned by Alexandre Jasmin) will include class comments, strings, selectors, and method source.
If the string might be contained in a method protocol name, I think you'd have to check programmatically. Something like:
Smalltalk allClasses select: [ :c |
c organization categories anySatisfy: [: cat |
'*substring*' match: cat ] ].
Select the text that you want to search for (generally from a browser or workspace).
Shift-Yellow Click on the text to show up a context menu.
That menu will contains among other things some advanced search options for the selected text string:
selectors containing it
method strings with it
method source with it
class names containing it
class comments with it
change sets with it