I'm learning Smalltalk programming as I think its way ahead as an OOP programming tool. I would appreciate feedback regarding my coding of the following problem. I have a sequence of letters representing bases in a DNA and want to change the T to a U in the string. I have done this in two ways. The first uses the copyReplaceAll:with:
message to the string object which changes every occurrence of 'T' to a 'U':
string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
string copyReplaceAll: 'T' with: 'U'.
My second method uses iteration and boolean conditions to test whether a 'T' is identified. I learned that I have to copy the string to an Array object, then iterate over that object and copy the elements to an empty array. Ideally I would like the original string object to be mutable. Am I going at this the wrong way? Here's my code:
string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
strCopy := string asArray.
empty := Array new: strCopy size.
cntr := 1.
strCopy do: [:char |
(char = $T) ifTrue: [empty at:cntr put: $U ]
ifFalse: [empty at:cntr put: char].
cntr := cntr + 1
].
-
1\$\begingroup\$ This would have been a good question for the [smalltalk] and [pharo] tags of Stack Overflow. Next time consider asking there too. \$\endgroup\$Leandro Caniglia– Leandro Caniglia2017年07月29日 12:07:42 +00:00Commented Jul 29, 2017 at 12:07
1 Answer 1
Since Smalltalk is super interactive also try browsing through the methods of e.g. ByteString
and other classes and the different ways to search for methods and their implementors:
Browsing the ByteString class methods
You can actually run do:
and at:put:
on it directly, but there's also doWithIndex:
for example, which looks like it will make your second bit even simpler:
string := 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'.
string doWithIndex: [ :char :i | (char = $T) ifTrue: [ string at: i put: $U ] ].
Now, in terms of readability, the first one is of course much easier to understand. It's to the point and obvious even for readers with no knowledge of Smalltalk. The second one and the example I posted aren't (or are less so at least) - they use more complex syntax and several new concepts.
If you restrict yourself to just String
I think your second approach is fine though.
-
1\$\begingroup\$ Thank you Ferada for taking the time to help me with this. I can see that the doWithIndex: message makes the code neater without the need for a counter. \$\endgroup\$awyr_agored– awyr_agored2017年07月28日 23:25:37 +00:00Commented Jul 28, 2017 at 23:25
-
3\$\begingroup\$ @awyr_agored Be aware that the expression
string doWithIndex: [...]
suggested by @ferada will modify yourstring
, whereas your version left the originalstring
unchanged and worked on acopy
. \$\endgroup\$Leandro Caniglia– Leandro Caniglia2017年07月29日 12:10:28 +00:00Commented Jul 29, 2017 at 12:10