Sort the list of structures by list size
I need to sort a list of structures in this format: (A, B, [...])
by the length of the list.
For example, if I have:
[(A,B,[1,2,3,4]),(A,B,[1,2]),(A,B,[1,2,3,4,5]),(A,B,[1,2,3])]
After sorting, I want this:
[(A,B,[1,2]),(A,B,[1,2,3]),(A,B,[1,2,3,4]),(A,B,[1,2,3,4,5])]
How can i do this?
source to share
Match each element El
to a construct N-El
and use inline keysort/2
.
el_keyed(El,N-El) :-
El = (_,_,L),
length(L, N).
list_lulasorted(Els, ElsS) :-
maplist(el_keyed, Els, KVs),
keysort(KVs, KVsS),
maplist(el_keyed, ElsS, KVsS).
See this answer if your Prolog system does not provide maplist/3
.
The last step can be "sped up":
keyvalue_value(_-V, V). ..., maplist(keyvalue_value, KVsS, ElsS), ...
Alternatively, using library(lambda)
, no additional definition is needed:
list_lulasorted(Els, ElsS) :-
maplist(\El^(N-El)^( El=(_,_,L), length(L, N) ), Els, KVs),
keysort(KVs, KVsS),
maplist(\(_-V)^V^true, KVsS, ElsS).
Some notes: (A, B, L)
not as common as in Haskell or ML. Instead, use any type of structure .(A, B, L)
, or possibly (A*B)-L
, depending on what it means A
and B
.
source to share