Defining lists in prolog scripts

31,152

Solution 1

In Prolog we speak of logical variables, to mean identity between literals.

That is, a program it's a set of rules that collectively state what's true about our literals, and that literals are uninterpreted. We write rules using variables to describe relations about individuals, and while trying to prove if our query can become true, Prolog binds variables as rules dictate.

A list it's just syntax sugar for a binary relation between a term (the head) and (note the recursion here) a list. Usually, when we speak of a database, we use facts (rules without a body, always true) that binds atomic literals.

So that tutorial probably expresses the task in different words than you report, or it's somewhat misleading. You could anyway store lists in your database as such:

mylist([a,b,c]).

and write your program like:

myprog(X) :- mylist(L), member(X, L).

Then you can query your program like:

?- myprog(X).

and Prolog, trying to prove myprog/1, attempt to prove mylist/1 and member/2... To prove mylist(L) the variable L get bound to [a,b,c].

HTH

Solution 2

When you write

X = [a, b, c].

It's read as

=(X, [a, b, c]).

which is read as a definition of a fact concerning the =/2 predicate. A fact where any free variable would be equal to [a, b, c]. That is, you redefine =/2. That's obviously not what you intend!

You have to remember in Prolog that variables are scoped only locally, inside a predicate. What would work is:

main :-
    X = [a, b, c],
    % do stuff with X.

Solution 3

I use swipl under linux, to define a list in prolog.

mylist([element1,element2,elementn]).

Then you can query your program:

?- mylist(A).

Solution 4

no, you cannot do it like this. what are you basically writing is:

=(X,[a,b,x]).

and as the error says you cannot redefine =/2

what you could do is:

x([a,b,c]).

and when you want to use X:

...
x(X),
foo(X)
...

Solution 5

If Y = [a,b,c], after the function makeList(Y,F) function call, F = [a,b,c]

makeList(Y,F) :-
append(Y,[],X),
F = X.

e.g)

?- makeList([a,b,c],X).
X = [a,b,c].
Share:
31,152
Admin
Author by

Admin

Updated on April 29, 2020

Comments

  • Admin
    Admin about 4 years

    I am new to prolog programming and have been told in a tutorial to define a list of structures (in a script) so that I can query it as a database. However I find it impossible to define this list as a variable in a script. When I define a list such as

    X=[a,b,c].
    

    I just receive an error saying

    No permission to modify static_procedure `(=)/2'
    

    Does prolog not support defining variables such as this? I am using SWI-Prolog under linux.