Search code examples
listprologappend

Get every element besides the last from a list in Prolog using append


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


Solution

  • 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.