如何在prolog的谓词中传递列表 [英] how to pass a list in a predicate in prolog

查看:40
本文介绍了如何在prolog的谓词中传递列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个段落作为列表存储在一个变量中,然后调用该列表来计算特定单词在该段落中出现的次数.

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.

但是,当我这样做时:

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). 

列表中出现hello"的次数没有显示,而是收到警告:

The number of "hello" occurrences in the list doesn't show, instead I receive a warning:

singleton variable:[X]

推荐答案

prolog 文件中的行:

The line in a prolog file:

L = [hello,hello,hello].

序言的意思:

=(L, [hello,hello,hello]).

这意味着您正在尝试定义谓词,=/2.因此,您不仅会收到关于 L 的单例警告(因为 L 未在此谓词定义的其他任何地方使用),而且您还会看到关于尝试重新定义内置的 =/2 因为 prolog 已经定义了它.

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.

你可以做的是:

my_list([hello,hello,hello]).

然后,你可以这样做:

my_list(L), counthowmany(hello,L,N).

请注意,此案例有效:

L = [hello,hello,hello], counthowmany(hello,L,N).

之所以有效,是因为它没有尝试重新定义 =/2.它只是使用现有的内置谓词=/2.

It works because it's not attempting to re-define =/2. It is just using the existing built-in predicate =/2.

这篇关于如何在prolog的谓词中传递列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆