I did some practice exercise on a problem at Rosetta Code. This code is likely heavier than it needs to be:
Given a list of values and a set of integer indices into that value list, the task is to sort
the values at the given indices, but preserving the values at indices outside the set of those
to be sorted.Make your example work with the following list of values and set of indices: ``
values: [7, 6, 5, 4, 3, 2, 1, 0] indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6]
Rosettacode is a bit disshelved in that it needs a better filing principle than a wiki, online code-exercising test harnesses and a code-markup-and-commenting system. Some people also write “coding golf” exercises which misses the point.
Anyway, the above has made me notice that one might want to consider the following additions to library(list)
:
vectorial_nth0(IndexList,List,Elements)
The integer indexes listed in IndexList
(not necessarily ordered or disjoint) indicate which elements from List
to unify with elements from Elements
, in order of appearance of the pairs of elements from IndexList
and Elements
. IndexList
and Elements
must be of the same length.
For example:
vectorial_nth0([1,0,1,3,2],List,[A,B,C,D,E])
performs:
nth_0(1,List,A),
nth_0(0,List,B),
nth_0(1,List,C),
nth_0(3,List,D),
nth_0(2,List,E).
Heroic programming could enlargen semantics to accept nonground elements in IndexList
.
Similarly:
vectorial_replace(IndexList,Elements,ListIn,ListOut)
The integer indexes listed in IndexList
(necessarily disjoint but necessarily ordered) indicate which elements from ListIn
to replace by element from Elements
(which could be fresh variables), in order of appearance of the pairs of elements from IndexList
and Elements
, giving ListOut
. IndexList
and Elements
must be of the same length.
One could then write things like this solution in R
values=c(7,6,5,4,3,2,1,0)
indices=c(7,2,8)
values[sort(indices)]=sort(values[indices])
print(values)
7 0 5 4 3 2 1 6
Similar to D, Groovy, (maybe APL, I can’t read it), Perl & Raku. The various LISPs still are weirdly verbose and opaque.