how to pass a list in a predicate in prolog

≡放荡痞女 提交于 2019-12-20 05:23:12

问题


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]

回答1:


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.




回答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.


来源:https://stackoverflow.com/questions/21971270/how-to-pass-a-list-in-a-predicate-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!