简体   繁体   中英

Prolog: Checking lengths of lists inside a list

I'm totally new in Prolog and I have problems handling a list that contains other lists. I have some lists like this: [([5],23),([1],23),([2],43),([4],29),([3],14),([5,1,4,3],47)] and I am trying to take the (sub)list with the biggest length and put it first at the list

in this example I want the result to be like this: ([5,1,4,3],47),([5],23),([1],23),([2],43),([4],29),([3],14)]

(don't care whether it will be removed or not from it's starting place).

Thanks to all who will try to help

Presuming that you want to use the built-in sort routine (I'm using SWI-Prolog as example here), then the following would work:

calcLen((List,K),(N,List,K)):- length(List,N).
delLen((_,List,K),(List,K)).

sortlen(List,Sorted):- 
  maplist(calcLen,List,List1), 
  sort(0,@>=,List1, List2),
  maplist(delLen,List2,Sorted).

The two predicates calcLen and delLen insert and remove a length calculation at the front of the pairs in the list -- making them triples. The maplist predicate applies calcLen (and later delLen ) to a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM