Op 30-4-2020 om 10:31
schreef Ben Coman:
> collection := '8569 2478 0383 3437'.
> (collection reverse selectWithIndex: [:item :index |
(index % 2 == 0)
> ifTrue: [item *2]] ) inspect
I see a error and the non-even numbers are nill now.
but after some figgeling this seems to work :
Great that you worked it out for yourself !!!
"figgeling" is a very important part of programming.
collection := '8569247803833437' asArray.
checkNumber := (collection reverse withIndexCollect: [:item
:index |
(index % 2 == 0) ifTrue: [item asInteger *2] ifFalse: [item
asInteger]]
) sum inspect
^ checkNumber isDivisibleBy: 10
That looks like it would work, but the inspect is
redundant now you know how it works.
An important take away from this is that when you are
confused by what is happening,
you need to LOOK at each spot you data is transformed,
where "inspect" is your friend, particular running it from
the debugger.
--------------------------------
Now there is another path you might try, but first I want
to stress
that I didn't know this answer a minute ago - I only just
discovered it !!
So this answer is not based on something magic I knew
directly, but on my approach to guess, search and test
within the system.
I was considering how you were dealing with "every second
digit" and considered a general description of this was
"pairs".
I _wondered_ whether Pharo had any methods dealing with
"pairs" ?
Spotter is a good place to ask this question, so I...
Pressed <Shift-Enter>
Typed... pair #i
to see if there were any implementors containing the word
"pair" and discovered
SequenceableCollection>>#pairsCollect:
3. First time I've seen that method, I wonder how it
works?
The method comment gives a clue that the block takes two
arguments.
So lets try-the-simplest-possible-thing...
( '123456' pairsCollect: [ :a :b | a ] ) inspect
==> #($1 $3 $5)
So that looks useful.
Try experimenting with it yourself.
cheers -ben