How to add to the end of the list in the prolog

I am trying to add one item to the end of the list in the prolog, but it continues to fail.

insertAtEnd(X,[ ],[X]). insertAtEnd(X,[H|T],[H|Z]) :- insertAtEnd(X,T,Z). letters([a,b,c]). 

I do not understand why this below does not work.

 insertAtEnd(d,letters(Stored),letters(Stored)). 

I am also trying to store this list in a variable stored everywhere, but I'm not sure if this is the right way.

+7
source share
2 answers

Prolog implements a relational computational model, and variables can only be created, not assigned. Try

 ?- letters(Stored), insertAtEnd(d, Stored, Updated), write(Updated). 
+3
source

you can use append and put your item as a second list

like this:

insertAtEnd (X, Y, Z): - add (Y, [X], Z).

+1
source

All Articles