2

This question has been asked quite a lot (for instance, here) but I could not understand why it's happening and how to fix it.

I want to make a list Z and count its elements. This is my code:

Z = [a,b,c,d,e].

listlength([],0).
listlength([Head|Tail],Count):-
    listlength(Tail,PartialCount),
    Count is PartialCount + 1 .

But I get the following error (and warnings):

ex3.pl:1:   Warning:    Singleton variables: [Z]
ex3.pl:1:   ERROR:  No permission to modify static procedure `(=)/2'
ex3.pl:5:   Warning:    Singleton variables: [Head]
ex3.pl:5:   Warning:    Singleton variables: [Head]

I do not understand how I can fix it, and I do not know how to define a list and test the listlength rule. I'm using SWI-Prolog 7.6.4 x64.

false
  • 10,264
  • 13
  • 101
  • 209
psyguy
  • 312
  • 3
  • 16

2 Answers2

2

You get the error.... how? doing what? I'm guessing, you are loading a file with the above definitions in it. Then each of them is interpreted as a predicate definition. In particular,

Z = [1,2,3].

is read as if it were

=(Z, [1,2,3]).

which is the same as

=(Z, [1,2,3]) :- true.

and that means you are redefining the built-in predicate =/2.

Instead, define

mypred([1,2,3]).

and use it in queries like

?- mypred(Z), write(Z).
Will Ness
  • 70,110
  • 9
  • 98
  • 181
0

At listLength.pl implement your facts:

listLength([],0).
listLength([_|Tail],Count):-            % Fixing Singleton variables: [Head] 
    listLength(Tail,PartialCount),      % Variable `Head` was not in use.
    Count is PartialCount + 1 .         % Use wildcard `_`

?- Z = [a,b,c,d,e], listLength(Z,5).    % For queries in files use `?-`
                                        % Fixing Singleton variables: [Z] and
                                        % No permission to modify static procedure `(=)/2'

After using consult('listLength.pl').

You can use listLength/2 which you implemented:

?- listLength([1,3,4,2],X).
X = 4.

?- listLength([a,b,c,d,e],X).
X = 5.

?- Z=[1,3,a,b,3], listLength(Z,X).
Z = [1, 3, a, b, 3],
X = 5.
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118