looking for answers to exercises in Squeak book Ch 2.

Bob Arning arning at charm.net
Thu Apr 26 20:17:31 UTC 2001


Hi Tom,

On Thu, 26 Apr 2001 15:45:15 -0400 txporter at mindspring.com wrote:
>At the end of chapter 2, there are some exercises, specifically No. 3:
>Write a piece of workspace code [...] to do the following:
>(a) Replace all vowels in the string 'Squeak' with dashes.
>(b) Compute the average of a set of integers in an array.
>
>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.
>
>aString := 'squeak'.
>aCount := 1.
>aString do: [:element | element isVowel ifTrue:
>	[aString at: aCount put: $-]. "Could aString be self?"
>	aCount := aCount +1].

	'squeak' collect: [ :ch | ch isVowel ifTrue: [$-] ifFalse: [ch]]

>anArray := #(12 14 16 18 20).
>aSum := 0.
>aCount := 0.
>anArray do: [:num | aSum := aSum + num.
>	aCount := aCount +1].
>anAverage := aSum / aCount.

Well, the simplest way would be
	
	#(12 14 16 18 20) average

If you weren't aware that #average existed, you might try

	| anArray |
	anArray _ #(12 14 16 18 20).
	anArray sum / anArray size

If #sum weren't available, you could do

	| anArray |
	anArray _ #(12 14 16 18 20).
	(anArray inject: 0 into: [ :sum :each | sum + each]) / anArray size

>Sorry for such a trivial start, but I really want to grok the OO way to do this.

No problem.

Cheers,
Bob





More information about the Squeak-dev mailing list