Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array elements in Smalltalk

I am trying to sort the contents of the Array by alphabetical order by evaluating its first and third elements. I tried to use the 2nd and 3rd element in the array to evaluate and sort the array. But still I wasn't able to get the desired result.

Here's the content of the collection

#(#('Philippines' 'Davao' 'Durian')
#('Philippines' 'Cebu' 'Mango')
#('Philippines' 'Zambales' 'Lanzones)
#('Thailand' 'Bangkok'  'Durian')
#('Thailand' 'Phuket' 'Mango')
#('Vietnam' 'Ho chi min' 'Banana')
#('Vietnam' 'Hanoi' 'Mango'))

Here's what I did:

newArray := arrValues asArray.

newContent := newArray asSortedCollection: [ :ea :each | (ea at: 2) < (each at: 3) and: [ (ea at: 3) < (each at: 3)  ] ].

Here's my output:

#(#('Vietnam' 'Ho chi min' 'Banana')
#('Thailand' 'Bangkok'  'Durian')
#('Philippines' 'Davao' 'Durian')
#('Vietnam' 'Hanoi' 'Mango'))
#('Thailand' 'Phuket' 'Mango')
#('Philippines' 'Zambales' 'Lanzones)
#('Philippines' 'Cebu' 'Mango')

The output should be:

#(#('Vietnam' 'Ho chi min' 'Banana')
#('Thailand' 'Bangkok'  'Durian')
#('Philippines' 'Davao' 'Durian')
#('Philippines' 'Cebu' 'Mango')
#('Vietnam' 'Hanoi' 'Mango'))
#('Thailand' 'Phuket' 'Mango')
#('Philippines' 'Zambales' 'Lanzones)
like image 521
Jepthe Tan Avatar asked Feb 12 '26 21:02

Jepthe Tan


1 Answers

In Squeak and Pharo Smalltalk, you can write something like:

^arrValues sorted: #third ascending , #second ascending

or in Visualworks

^arrValues sorted:
     [:subArray | subArray at: 3] ascending ,
     [:subArray | subArray at: 2] ascending

We may thank Travis Griggs for introducing those nice SortFunction which give these good looking functional styles

He published this in his Objology blog http://objology.blogspot.com/2012/05/tag-memoizedfunctions.html and probably in earlier posts

like image 149
aka.nice Avatar answered Feb 15 '26 13:02

aka.nice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!