--- Begin Message ---
Op 30-4-2020 om 10:57 schreef Ben Coman:


On Thu, 30 Apr 2020 at 16:46, Roelof Wobben via Pharo-users <pharo-users@lists.pharo.org> wrote:
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



I will do and till  now I did not find a way to update the second one with it and keep the first one.
It seems I will loose the first number and then I cannot use it to calculate the sum.

Roelof


--- End Message ---

Reply via email to