Question

For the sake of usability, when I write the following code

{1,2,3,4,5,6,7,8,9,10}

I expect the Rascal console to print the same, yet in the output window I see:

{10,9,8,7,6,5,4,3,2,1}

This example is overly simple of course, and for this the ordering doesn't really hurt. However, in more complex examples I would expect the output to be sorted so that I can more easily verify if a certain element is included in the set.

Does the current ordering of the printed set have a meaning?

Was it helpful?

Solution

From the Rascal Tutor:

A set is an unordered sequence of values and has the following properties:

  • All elements have the same static type.
  • The order of the elements does not matter.
  • A set contains an element only once. In other words, duplicate elements are eliminated and no matter how many times an element is added to a set, it will occur in it only once.

And the wikipedia page on Sets:

In computer science, a set is an abstract data structure that can store certain values, without any particular order, and no repeated values.

So the behaviour you observe is as expected, there is no order inside a set, the order displayed is due to the implementation (a java HashSet). Sorting before printing, or during construction will have negative performance overhead, and might give a user the incorrect impression that there is an order.

In regards to the first suggestion, using the same sequence as supplied, that would require a less efficient data structure, and would again hurt performance in the off-change we have to print a set.

OTHER TIPS

And of course, you can always do:

import List;
import Set;
sort(toList({4,2,1,3}))

if you really want the output sorted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top