How do you make a rule that returns all elements besides the last in another list in Prolog using append? I've made the equivalent without append but I can't figure out the append solution
remlast([_],[]).
remlast([H1|T1],[H2|T2]):-
H2=H1,
remlast(T1,T2),
!.
I can get the last element from a list with append with this
mylastAppend(X,List):-
append(_,[X],List),!.
But I can't figure out how to use that in the above example
CodePudding user response:
Use:
list_front(List, Front) :-
append(Front, [_], List).
This will split the list in Front of the list and a one-element list from the back of List.
CodePudding user response:
Your "equivalent without append" is not optimal. This is better: https://stackoverflow.com/a/51291825/
Here is a variation which results in a difference list (which can then be used for e.g. an efficient append):
list_without_last_dl(Lst, LstWithout, LstWithoutTail) :-
Lst = [H|T],
list_without_last_dl_(T, H, LstWithout, LstWithoutTail).
list_without_last_dl_([], _H, W, W).
list_without_last_dl_([H|T], H2, [H2|W], WT) :-
list_without_last_dl_(T, H, W, WT).
Result in swi-prolog:
?- list_without_last_dl([a,b,c], W, WT).
W = [a,b|WT].