Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to end of list in prolog

Tags:

prolog

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.

like image 911
MeowMeow Avatar asked Oct 31 '12 03:10

MeowMeow


People also ask

How do I add to a list in Prolog?

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

How do you end a function in Prolog?

If you want to exit SWI-Prolog, issue the command halt., or simply type CTRL-d at the SWI-Prolog prompt.

Where is the last element in Prolog?

You just want the last element of the list. Try this: lastElement([Head]) :- write(Head). lastElement([_|Tail]):- lastElement(Tail).

How do you find the tail of a list in Prolog?

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.


2 Answers

you can use append and put your item as second list

like this:

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

like image 181
kochav Avatar answered Sep 30 '22 00:09

kochav


Prolog implements a relational computation model, and variables can only be instantiated, not assigned. Try

?- letters(Stored),
   insertAtEnd(d, Stored, Updated),
   write(Updated).
like image 43
CapelliC Avatar answered Sep 30 '22 01:09

CapelliC