How to add to end of list in prolog

19,902

Solution 1

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

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

Solution 2

you can use append and put your item as second list

like this:

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

Share:
19,902
MeowMeow
Author by

MeowMeow

Updated on July 01, 2022

Comments

  • MeowMeow
    MeowMeow almost 2 years

    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.