I am trying to add one item to the end of a list in prolog, but it keeps on failing.
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 attempting to store this list in the variable Stored throughout, but I am not sure if the above is correct way to proceed.
You can't modify lists in Prolog, but you can create a list with an unspecified length: main :- A = [1,2,3,4|_]. Then, you can insert an element using nth0/3 in SWI-Prolog: :- initialization(main).
If you want to exit SWI-Prolog, issue the command halt., or simply type CTRL-d at the SWI-Prolog prompt.
You just want the last element of the list. Try this: lastElement([Head]) :- write(Head). lastElement([_|Tail]):- lastElement(Tail).
In Prolog list elements are enclosed by brackets and separated by commas. Another way to represent a list is to use the head/tail notation [H|T]. Here the head of the list, H, is separated from the tail of the list, T, by a vertical bar. The tail of a list is the original list with its first element removed.
you can use append and put your item as second list
like this:
insertAtEnd(X,Y,Z) :- append(Y,[X],Z).
Prolog implements a relational computation model, and variables can only be instantiated, not assigned. Try
?- letters(Stored),
insertAtEnd(d, Stored, Updated),
write(Updated).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With