Decorate-sort-undecorate idiom: Difference between revisions
Content added Content deleted
(→{{header|RPL}}: typo) |
(Created Nim solution.) |
||
Line 622: | Line 622: | ||
<pre>a is site Code Rosetta programming chrestomathy |
<pre>a is site Code Rosetta programming chrestomathy |
||
chrestomathy programming Rosetta Code site is a</pre> |
chrestomathy programming Rosetta Code site is a</pre> |
||
=={{header|Nim}}== |
|||
In Nim, there are several ways to sort a list either by creating an explicit temporary list or using a map-sort-map idiom. |
|||
The easiest way to sort a list of words by word length consists to use the “sortedByIt” template which eliminates the need to create a decorated list. But this is not what is required in this task. |
|||
Here is one way to sort the words by length using the decorate-sort-decorate idiom: |
|||
<syntaxhighlight lang="Nim">import std/[algorithm, sequtils] |
|||
let wordList = ["Rosetta", "Code", "is", "a", "programming", "chrestomathy", "site"] |
|||
echo wordList.mapIt((value: it, length: it.len)).sortedByIt(it.length).mapIt(it.value) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>@["a", "is", "Code", "site", "Rosetta", "programming", "chrestomathy"] |
|||
</pre> |
|||
Note that words with same length will appear in the original list order. If we want them to appear in |
|||
alphabetical order, we need to sort the list alphabetically first. As Nim sorting algorithm is stable, |
|||
the order of items with same key value (i.e. length in this example) is preserved when sorting. |
|||
Of course, it is also possible to define a comparison function to sort by length then alphabetically and use it when sorting. |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |