0
votes

Hi I have to solve a problem in Prolog, that sounds like this: deletes all the sublists of a list that are increasing. For example the list [1,[2],[3,4],6] becomes [1,6]. So far I have tried this but it's not working. Any help please ?

    domains
 el=integer
 list=el*
 element=integer;list
 lista=element*

goal
elim([1,[2],[3],4)],L),
write(L).

predicates 
 elim(lista,lista)
 is_increasing(lista)
 is_list(lista)

clauses
is_increasing([A,B|T]) :- 
    B>A,
    is_increasing([B|T]).
is_list([_|_]).
is_list([]).
elim([],[]).
elim([E|Es],[E|Ts]) :-
    is_list(E),
    is_increasing(E),
    elim(Es, Ts).  
1
You might want to mention which Prolog interpreter you're using (PDC Visual Prolog?). For starters, it looks like elements must be of the form i(_) or l(_), but your elements are just integers and lists of integers. The way the code is written, it would expect a list like, [i(1), l([i(2)]), l([i(3)]), i(4)] or something like that. But then it would attempt to match a sublist, like l([i(2)]) against [...] which won't match.lurker
I'm using Turbo Prologjojuk

1 Answers

0
votes

attempt to modularize your code: first write an is_increasing/1. Since it appears that a list of 1 element is increasing, you can do as simply as

is_increasing([A,B|T]) :- B > A, is_increasing([B|T]).
is_increasing([_]).

then you can use it to discard elements while copying. Beware to check that an element is a list before calling. Here is a possible definition

is_list([_|_]).
is_list([]).

edit

there is a bad declaration, as advised by mbratch

element=i(integer);l(list) 

should be

element=integer;list

Also, you forgot is_increasing([_])., and anyway you're not using at all is_list or is_increasing.

The rule eliminating sublists of course should read

elim([E|Es], Ts) :- is_list(E), is_increasing(E), elim(Es, Ts).

just add the base case and a copy. i.e. elim is a 3 clauses predicate...

edit apart the rule above, you need only a base case

elim([],[]).

and a copy

elim([E|Es],[E|Ts]) :- elim(Es, Ts).

just try to understand why the order of rules is also important in Prolog...