Defining lists in a prolog script

I am new to prolog programming and talked in a tutorial on how 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, for example

X=[a,b,c]. 

I just get an error

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

Does the prolog not support the definition of variables like this? I am using SWI-Prolog under linux.

+8
source share
5 answers

In Prolog, we talk about logical variables to mean identity between literals.

That is, a program is a set of rules that together establish what is true of our literals and that literals are not interpreted. We write rules, using variables to describe relationships about people, and trying to prove whether our request can become true, Prolog binds the variables according to the rules.

A list is just syntactic sugar for the binary relationship between the term (chapter) and (note the recursion here) list. Usually, when we talk about a database, we use facts (rules without a body, always true) that atomic literals relate.

So this tutorial probably expresses the task in other words than you are reporting, or it is somewhat misleading. In any case, you can store lists in your database as such:

 mylist([a,b,c]). 

and write your program as:

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

Then you can request your program as:

 ?- myprog(X). 

and Prolog, trying to prove myprog / 1, tries to prove mylist / 1 and member / 2 ... To prove mylist (L), the variable L is associated with [a, b, c].

NTN

+17
source

When you write

 X = [a, b, c]. 

It reads like

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

which reads as the definition of a fact with respect to the predicate =/2 . The fact that any free variable will be equal to [a, b, c] . That is, you redefine =/2 . This is clearly not what you intend!

You should remember in Prolog that variables are limited only locally, inside a predicate. What will work:

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

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

 mylist([element1,element2,elementn]). 

Then you can request your program:

 ?- mylist(A). 
+1
source

no, you cannot do it like that. what you basically write:

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

and as the error says, you cannot override = / 2

what can you do:

 x([a,b,c]). 

and when you want to use X:

 ... x(X), foo(X) ... 
0
source

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

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

eg)

 ?- makeList([a,b,c],X). X = [a,b,c]. 
0
source

Source: https://habr.com/ru/post/912838/


All Articles