looking for answers to exercises in Squeak book Ch 2.
Randal L. Schwartz
merlyn at stonehenge.com
Thu Apr 26 20:09:51 UTC 2001
>>>>> "txporter" == txporter <txporter at mindspring.com> writes:
txporter> As a new Squeaker, I am slowly making my way through Mark's book on Squeak.
txporter> At the end of chapter 2, there are some exercises, specifically No. 3:
txporter> Write a piece of workspace code [...] to do the following:
txporter> (a) Replace all vowels in the string 'Squeak' with dashes.
txporter> (b) Compute the average of a set of integers in an array.
txporter> I did this like so, but think it is more like "procedural-language speak' and not Smalltalk. Anyone have any more elegant solutions? I particularly do not like the use of the aCount variable.
txporter> aString := 'squeak'.
txporter> aCount := 1.
txporter> aString do: [:element | element isVowel ifTrue:
txporter> [aString at: aCount put: $-]. "Could aString be self?"
txporter> aCount := aCount +1].
This one took me about five minutes. I was looking for a way to
convert an array of Character to a String... had to stumble across
#withAll: ...
String withAll:
('Squeak' asArray collect: [:ch | ch isVowel ifTrue: [$-] ifFalse: [ch]])
Mark, is there a simpler way you had in mind?
txporter> anArray := #(12 14 16 18 20).
txporter> aSum := 0.
txporter> aCount := 0.
txporter> anArray do: [:num | aSum := aSum + num.
txporter> aCount := aCount +1].
txporter> anAverage := aSum / aCount.
You're gonna shoot me when you see how easy this is:
anArray := #(12 14 16 18 20).
theAverage := (anArray sum) / (anArray size)
Learn to use the method finder. Helps tremendously.
--
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!
More information about the Squeak-dev
mailing list
|