Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove sub-lists in prolog?

Can someone help me, please? I need to solve this problem in prolog and I don't know how...

"Given a list of integer numbers. Remove all sub-lists formed from decreases elements."

like image 727
user3671805 Avatar asked Jan 10 '23 08:01

user3671805


1 Answers

We can improve this answer by using tchoose/3 instead of tfilter/3 and maplist/3, removing descending sublists in two steps---not three:

  1. separate decreasing and non-decreasing parts (using splitlistIfAdj/3 and (#=<)/3)

    ?- splitlistIfAdj(#=<,[ 1 , 2 , 3 , 4,3,2,1 , 2 , 3 , 4,3,2,1 , 2 ],Xs1).
    Xs1 =                 [[1],[2],[3],[4,3,2,1],[2],[3],[4,3,2,1],[2]].
  2. filter singleton lists and map to items (using tchoose/3, Prolog lambdas, and (=)/3)

    ?- tchoose(\[H|T]^H^(T=[]),[[1],[2],[3],[4,3,2,1],[2],[3],[4,3,2,1],[2]],Xs).
    Xs =                       [ 1 , 2 , 3 ,           2 , 3 ,           2 ].

Let's put it together!

:- use_module(library(clpfd)).
:- use_module(library(lambda)).

descending_removed(Xs0,Xs) :-
   splitlistIfAdj(#=<,Xs0,Xs1),
   tchoose(\[H|T]^H^(T=[]),Xs1,Xs).

Same queries, same results:

?- descending_removed([1,2,3,4,3,2,1,2,3,4,3,2,1,2],Xs).
Xs = [1,2,3,2,3,2].

?- descending_removed([4,3,2,1,0],Xs).
Xs = [].

?- descending_removed([1,2,3,4],Xs).
Xs = [1,2,3,4].

?- descending_removed([1,2,3,  4,3,3,2,2,1],Xs).
Xs = [1,2,3].

?- descending_removed([1,2,3,4,4,3,3,2,2,1],Xs).
Xs = [1,2,3,4].
like image 191
repeat Avatar answered Jan 15 '23 18:01

repeat