如何在Prolog中声明列表



我浏览了SO上关于如何声明列表的各种答案,但不断收到错误消息。我正在读一本书中关于列表的部分,但仍然没有一个关于如何正确声明列表的例子。我正在为我的班级做一个项目。我有一组随机的问题,但当用户回答一个问题时,该问题就不能重复(问题是随机的(。

我已经完成了这一部分,但我想创建一个列表,这样当有人问我问题时,我想把问题编号添加到我的列表中。我试过各种方法,但还是做不到!

test(N):- list(P), member(N, P).
list = [].
start :-
write('Answer the questions correctly'), nl,
X is 0,
push(X,list,[X|list]),
test(X).

这个片段只是为了制作列表代码。据我所知,我想将X,在本例中为0,推到列表的顶部。由于我的列表被宣布为空,我想它会起作用。我得到这个错误:

No permission to modify static procedure `(=)/2'

我试着理解这意味着什么,但因为每个人的代码不同,所以有很多不同的答案,我不知所措。这是我第一次在Prolog中编程。

无权修改静态过程``(=(/2'

在Prolog中,您不会像使用那样通过声明列表来构建列表

list = [].

Prolog值以小写字母开头,变量以大写字母开头。这在编程语言中并不常见,但可以很容易地创建新变量,不必声明它们,只需在需要变量的地方使用大写字母即可。

Prolog不使用赋值或具有方法。Prolog使用语法统一并具有谓词。因此,当您将[]视为传递的参数时,也就是说,列表要么是构造的,要么是与变量统一的。

你可能想要这样的

begin :-
% In the next statement I am doing what you would consider 
% constructing a list.
ask([]).    
ask(List) :-
write('Answer the questions correctly'), nl,
get_answer(A),
% Here the answer in A is added to the head of the list using
% the list operator that combines a head with a tail, `|`.
% This is how your idea of a push is done with a list.
test([A|List]).
% When this is called from 
% get_answer(A), A will be unified with 0. 
get_answer(0).
% The next predicate `test` with two clauses does what your were trying to do with
% `member(N,P)`. It uses recursion which needs one clause to recursively process
% a list and one clause, the base case, to handle an empty list.
% When the list is empty, do nothing.
test([]). 
test([H|T]) :-
% H is the head of the list
% do something with head of list by adding more code here.
% T is the tail of the list.
% Recursively call test with the tail of the list
% to process the remainder of the list.
test(T).      

最新更新