简体   繁体   中英

How to just get key only on GNU Smalltalk?

I am currently using sortedCollection that stores dictionary of character (key) and number of occurrence for that character (value). When iterating through sortedCollection, how do I access the key value only?

eg

[que last notNil] whileTrue: [
    stdout << 'current character is ' *key* << ' and occurs << *val* << ' times.' << nl.
]

Where que is the sortedCollection that sorts dictionary by value.

My goal is following: let's say que has: [$a:20, $e:100] where first letter is the key of dictionary and second number is the value of dictionary. My output should look something like this:

current character is a and occurs 20 times. current character is e and occurs 100 times.

I am not sure how to get a , or the key in dictionary since keys are arbitrary.

Assuming that que is a sorted collection and each element is an Association with the character as the key and the count as the value, as in your [$a:20, $e:100] example, you could do it like this:

que do: [:each | stdout << 'current character is ' << each key
                        << ' and occurs ' << each value << ' times.' << nl]

If que is a Dictionary, use que keysAndValuesDo: [:char :count | stdout << "..." char << "..." count << "..." nl] que keysAndValuesDo: [:char :count | stdout << "..." char << "..." count << "..." nl] .

Depending on your overall application, you could also use a Bag , which is an unordered collection of elements that can appear multiple times (as opposed to a Set, which contains each element only once).

characters := 'hello world' asBag.
characters asSet do: [:each |
    stdout << 'current character is ' << each
           << ' and occurs ' << (characters occurrencesOf: each) 
           << ' times.' << nl]

You could also have a look at the # sortedByCount method and see whether it suits your case. I cannot tell from the reference how exactly its returned collection is structured, so I will not provide you with guessed example code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM