For the past few weeks I have been working on converting an old script in Python to NIM. Despite little experience with NIM, I am very happy with the results, especially the performance. Ok, but there is something that I can't find a solution, even though it is simple, I did not found a way to sort a sequence.
Suppose I have a 2d array like this:
var myVal: seq[array[4,string]] = @[ ["10", "C", "10", "10"], ["11", "A", "11", "11"], ["7" , "B", "7", "7"] ]
A simple looping with echo will give me this:
["10", "C", "10", "10"] ["11", "A", "11", "11"] ["7", "B", "7", "7"]
My goal is to sort the 2nd column and get this: ["11", "A", "11", "11"] ["7", "B", "7", "7"] ["10", "C", "10", "10"]
In pure Python this could be something like: sorted(myVal, key=lambda x:x[1]) #where x[1] represents 2nd column.
Is there a function in NIM that can sort myArry by 2nd column?
I tried sort(myVal, system.cmp), but it didn't work... (at least not for me!)
thanks in advance.
Vanderlei
You're on the right track, sort takes a procedure which defines how to do the actual sorting. https://nim-lang.org/docs/algorithm.html#sort%2CopenArray%5BT%5D%2Cproc%28T%2CT%29 What you need to do is to pass a procedure which compares the second element of each of the arrays and return an integer. In this case it should be enough to use cmp(a[1], b[1]). By the way sort sorts the data inline (it doesn't return a sorted version), you can also use sorted which returns a sorted version, or you can use sortedIt to save a bit on typing: https://nim-lang.org/docs/algorithm.html#sortedByIt.t%2Cuntyped%2Cuntyped
By the way, this forum supports RST/Markdown styling so you should wrap your code in code block statements to make it easier to read.
Thanks for the quick feedback PMunch.
I will test your suggestions in the next few days. I hope to be successful with your tips.
** By the way, this forum supports RST/Markdown styling so you should wrap your code in code block statements to make it easier to read. **
OK, next time I will try to make my messages easier to read with the RST/Markdown.
Thanks again