I am trying to modify my list from [a, (a s b), ( a s b s c), a] to [[a], [a, b], [a,b,c], [a]]
I tried sth like that:
:- op(300, xfy, s).
lol([], List).
lol([X|T], List) :-
X \=(A s B),
lol(T, [[X]|List]).
lol([X s P|T], List) :-
lol([P|T], [[X]|List]).
but this makes:
lol([], [[a], [b], [c], [d], [e]|_G4165]
Your base case is not correct as it leaves the tail of the constructed list unbound. It should be:
lol([], []).
The recursive cases can also be fixed as:
lol([X| Xs], [[X]| Tail]) :-
X \= s(_, _),
lol(Xs, Tail).
lol([X s P| Xs], [[X| Ps]| Tail]) :-
lol([P| Xs], [Ps| Tail]).
With these changes we get:
?- lol([a, (a s b), ( a s b s c), a], List).
List = [[a], [a, b], [a, b, c], [a]] .
To avoid spurious choice points you can either add a cut in the first recursive case:
lol([X| Xs], [[X]| Tail]) :-
X \= s(_, _),
!,
lol(Xs, Tail).
Or combine the two recursive cases using an if-then-else control construct (left as an exercise).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments