I want to store a paragram as a list in a variable and then call that list for counting how many times a particular word appears in that paragraph.
However, when I do this:
L = [hello,hello,hello].
counthowmany(_, [], 0) :- !.
counthowmany(X, [X|Q], N) :- !, counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [_|Q], N) :- counthowmany(X, Q, N).
... and compile buffer, and then ask this:
counthowmany(hello,L,N).
The number of "hello" occurrences in the list doesn't show, instead I receive a warning:
singleton variable:[X]
The line in a prolog file:
L = [hello,hello,hello].
Means to prolog:
=(L, [hello,hello,hello]).
Which means you're attempting to define a predicate, =/2
. So not only will you get a singleton warning about L
(since L
isn't used anywhere else in this predicate definition), but you'll also see an error about an attempt to re-define the built-in =/2
since prolog already has it defined.
What you can do instead is:
my_list([hello,hello,hello]).
Then later on, you can do:
my_list(L), counthowmany(hello,L,N).
Note that this case works:
L = [hello,hello,hello], counthowmany(hello,L,N).
It works because it's not attempting to re-define =/2
. It is just using the existing built-in predicate =/2
.
You do
?- X = [hello,how,are,you,hello,hello], counthowmany(hello, X, N).
X = [hello, how, are, you, hello, hello],
N = 3.
First you first bind X ans then you ask for this specific X.
Example 2.
?- counthowmany(hello, X, N).
X = [],
N = 0.