Unary - Binary message

Richard A. O'Keefe ok at atlas.otago.ac.nz
Fri Oct 26 02:38:03 UTC 2001

```"Gary McGovern" <garywork at lineone.net> wrote:
What I wanted was to overcome
count := count + 1
in iterations, (something I'm tired of already even as a beginner) and just
use
count ++

Are you writing

i := 1.
[i <= n] whileTrue: [
do something with i.
i := i + 1].

or are you writing

1 to: n do: [:i|
do something with i].

I use the iteration methods (such as #to:do:) as much as I can, and as
a result, very very seldom have occasion to add 1 to anything.

If you can get your hands on a copy of Kent Beck's
"Smalltalk Best Practice Patterns" you may get some useful ideas.

For example, suppose you had a pair of numeric arrays p, q and you
wanted to compute their dot product, and you either didn't know there
was a #dot: selector already in Squeak, or you DID know that for some
reason it is restricted to FloatArray.  Then you could write

dot := (1 to: p) inject: 0 into: [:sum :i| sum + ((p at: i) * (q at: i))].

or
dot := 0.
1 to: p size do: [:i | dot := dot + ((p at: i) * (q at: i))].

or
dot := 0.
p with: q do: [:x :y| dot := dot + (x * y)].

Or you might say, "we have #with:do: and #inject:into:, why is there
no #with:inject:into:?", and go and add

with: otherCollection inject: thisValue into: ternaryBlock
"Combines Collection>>inject:into
and SequenceableCollection>>with:do"
|nextValue|
nextValue := thisValue.
1 to: self size do: [:index|
nextValue := ternaryBlock
value: nextValue
value: (self at: index)
value: (otherCollection at: index)].
^nextValue

and then you could write

dot := p with: q inject: 0 into: [:sum :x :y| sum + (x*y)]

with never a count := count + 1 in sight.

```