Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smalltalk array manipulaton

I am new in using smalltalk and i am trying to iterate an array inside an array and evaluate each array member if it is divisible by 4 if true it will return the byte array containing the element using select method Here's my code:

| anArray result |
anArray := #(#(1 2 3 3 4 6 7) #(6 7 6 9 9 4 7 6) #(11 12 13 14 15 14)).
anArray select: [ :each | 
     each do: [ :ea | 
         ea \\ 4 == 0 ifTrue: [ Transcript show: each printString ]
     ]
]

The problem is that it needs a boolean condition in the select method. Do you know other ways to use select method to return the said output?

Thanks!

like image 438
Jepthe Tan Avatar asked Sep 06 '26 05:09

Jepthe Tan


2 Answers

Welcome to Smalltalk! Your question is a bit ambiguous. Do you want to select each inner array where any element is divisible by 4? If so, try the following:

| anArray result |
anArray := #(#(1 2 3 3 4 6 7) #(6 7 6 9 9 4 7 6) #(11 12 13 14 15 14)).
anArray select: [ :eachArray | 
    eachArray anySatisfy: [ :eachElement | 
        eachElement \\ 4 == 0.
    ].
].

Or do you want to print each element from the inner array that is divisible by 4? If so, try the following:

| anArray result |
anArray := #(#(1 2 3 3 4 6 7) #(6 7 6 9 9 4 7 6) #(11 12 13 14 15 14)).
anArray do: [ :eachArray | 
    eachArray do: [ :eachElement |
        eachElement \\ 4 == 0 ifTrue: [
            Transcript cr; show: eachElement.
        ].
    ].
].
like image 162
James Foster Avatar answered Sep 07 '26 21:09

James Foster


(Read James Foster's answer first)

If you want to select and print:

anArray select: [:eachArray | 
  (eachArray anySatisfy: [:eachElement | eachElement \\ 4 == 0])
      ifTrue: [Transcript cr; show: eachArray];    "no need to #printString"
      yourself]

which forces the Boolean resulting from #anySatisfy: to be answered by the block.

like image 23
Leandro Caniglia Avatar answered Sep 07 '26 20:09

Leandro Caniglia