Currently I'm implementing an algorithm to return the Farey Series of order n by calling my function with FareySeries(n). This works quite well,for example calling
L = FareySeries(4)
returns
List([0, 1, 1/2, 1/3, 1/4, 2/3, 3/4])
but I need the list to be sorted. Reading the documentation, I thought
listsort(L)
would do the job, but it seems this only works for Integers and Floats (I tested this manually). Is there some built-in function(or parameter) for sorting a list containing mixed integers and fractions or do I have to sort it manually? I don't need code to sort for myself, I just want to use, what has already been implemented; sticking to the basics of coding here.
Easiest workaround is to use vecsort
. In general I would recommend always using vectors over lists except when incrementally building up a list. After constructing a list, it is cleaner to return it from a function as a vector.
L = List([0, 1, 1/2, 1/3, 1/4, 2/3, 3/4]);
listsort(L);
L
gives: List([0, 1, 1/2, 1/3, 1/4, 2/3, 3/4])
(incorrect)
L = List([0, 1, 1/2, 1/3, 1/4, 2/3, 3/4]);
vecsort(L)
gives: List([0, 1/4, 1/3, 1/2, 2/3, 3/4, 1])
(correct)
Note that vecsort
does not modify the original list, so if you want to update the list then you need to assign the output of vecsort
back to the variable.
However, I would recommend using vectors.
L = Vec(List([0, 1, 1/2, 1/3, 1/4, 2/3, 3/4]));
vecsort(L)
gives: [0, 1/4, 1/3, 1/2, 2/3, 3/4, 1]
(note the absence of List
).
The underlying reason for this is that vecsort
uses lex
, but listsort
uses cmp
. I am not sure why cmp
is so badly behaved - could be a bug, but more likely broken by design.
It seems that listsort
sorts in the same order as used by sets and is optimized for performance rather than user expectation. If you wish to use setsearch
on your list then you need to have it ordered as for sets. There is also a function vecsearch
that uses lex
as a comparison function.
It is perhaps also worth mentioning that both vecsort
and vecsearch
take as an optional argument a user supplied comparison function.