按列表的大小对结构列表进行排序

sort a list of structures by the size of a list

我需要按以下格式对结构列表进行排序:(A, B, [...]) 按列表的长度。

例如,如果我有:

[(A,B,[1,2,3,4]),(A,B,[1,2]),(A,B,[1,2,3,4,5]),(A,B,[1,2,3])]

排序后我想要这个:

[(A,B,[1,2]),(A,B,[1,2,3]),(A,B,[1,2,3,4]),(A,B,[1,2,3,4,5])]

我该怎么做?

将每个元素 El 映射到结构 N-El 并使用内置 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).

如果您的 Prolog 系统不提供 maplist/3,请参阅 this answer

最后一步可能是 "accelerated" 作者:

keyvalue_value(_-V, V).

..., maplist(keyvalue_value, KVsS, ElsS), ...

或者,使用library(lambda)不需要辅助定义:

list_lulasorted(Els, ElsS) :-
   maplist(\El^(N-El)^( El=(_,_,L), length(L, N) ), Els, KVs),
   keysort(KVs, KVsS),
   maplist(\(_-V)^V^true, KVsS, ElsS).

一些注意事项:(A, B, L) 不像在 Haskell 或 ML 中那样频繁。相反,使用 .(A, B, L)(A*B)-L 之类的结构,具体取决于 AB 的实际含义。