I need to write a predicate f(L,R) that succeeds if and only if L is a list containing all terms in R that are not lists.
For example:
f(L,[1,2,3,[4,5,6],[[7,8,9]],[]]).
Should give:
L = [1,2,3,4,5,6,7,8,9]
I wrote a predicate that gives the following result instead:
L = [1,2,3,4,5,6,7,8,9,[]]
Empty lists should not be present in the result. My predicate is the following:
f([],[]).
f(V,[H|T]):- H = [_|_] -> append(L,R,V),
f(L,H), f(R,T),!;
V = [H1|T1], H1=H, f(T1,T).
I have two doubts. First of all, the empty lists should not be present in the result. Also I don’t know why it does not work if I don’t put the cut (!). In fact, if I don’t put the cut it gives me the result as above, but if I ask for another result it loops forever. I really don’t understand why this should loops.
To remove the empty list, handle that case (discard it).
About the loop: I think the cause could be that you’re calling append(L,R,V) with all arguments not instantiated: move append after the recursive calls.
Finally, maybe you don’t use rightly the ‘if then else’ construct: I’ve indented using the usual SWI-Prolog source style, using indentation to highlight ‘sequential’ calls