listprologdcgdifference-lists

Prolog Insert the number in the list by the tail


How can I build a predicate in prolog that receives a number and a list, I must insert the number in the list by the tail

I tried inserting the number in the list by the head: insert(H,[P|Q],[H,P|Q]). and it works, but how can I do it by the tail?


Solution

  • Inserting at the tail can be done with a two-part recursive rule:

    English description is much longer than its Prolog equivalent:

    ins_tail([], N, [N]).
    ins_tail([H|T], N, [H|R]) :- ins_tail(T, N, R).
    

    Demo.