[英]Prolog: take a list of two elements, return true if and only if the first element is same as second
I'm a newbie prolog programmer, and for an assignment, I have to have a basic program that succeeds if and only if list X is a list of two elements, with the first as the same as the second. 我是一名新手Prolog程序员,对于一项作业,我必须拥有一个基本程序,该程序必须且仅当list X是两个元素的列表且第一个元素与第二个元素相同时才能成功。
From my view of prolog, programs seem to be pretty small, so I typed this in: 从我的序言的角度来看,程序似乎很小,所以我输入了以下内容:
firstPair(x,x).
When I run it under swipl, I get this as output: 当我在swipl下运行它时,我将其作为输出:
Syntax error: Operator expected
Is there something more that needs to be done? 还有什么需要做的吗? I thought that if I executed this with say, firstPair(1,2).
我以为如果我用firstPair(1,2)执行此操作。 this would be all it would need to know that it is false.
这就是知道它为假所需要的全部。
First, lowercase x
is not a variable, it's an atom . 首先,小写的
x
不是变量,它是一个atom 。 Make x
uppercase to fix the problem: 使
x
大写可解决此问题:
firstPair(X,X).
Second, you do not type this into the interpreter. 其次,您不要在解释器中键入此内容。 Rather, you write it into a file
firstPair.pl
, and then read that file into Prolog. 而是将其写入文件
firstPair.pl
,然后将该文件读取到Prolog中。
At the command prompt, type this: 在命令提示符下,键入:
['firstPair.pl'].
Press enter. 按回车。 Now you can use your
firstPair/2
rule. 现在,您可以使用
firstPair/2
规则。
Finally, since the assignment talks about lists, I think the instructor wanted you to write firstPair/1
, not firstPair/2
: 最后,由于作业讨论的是列表,所以我认为讲师希望您编写
firstPair/1
,而不是firstPair/2
:
firstPair([X,X]).
Your program/fact 您的程序/事实
firstPair(X,X).
will succeed if the two arguments given it can be unified , whether they are lists, atoms, variables, etc. To meet your specification, a 如果给定的两个参数可以统一 (无论它们是列表,原子,变量等),则将成功。为了满足您的规范,
program that succeeds if and only if list X is a list of two elements, with the first as the same as the second.
且仅当list X是两个元素的列表且第一个元素与第二个元素相同时,程序才会成功。
You need something like this: 您需要这样的东西:
list_of_two_elements( [X,X] ).
This will succeed if passed a single term that is (or can be unified with) a list of two elements that are, or can be made through unification, identical. 如果传递的单个术语是(或可以与之统一)两个元素的列表,或者可以通过统一使两个元素相同,那么这将成功。 For instance, all of the following will succeed:
例如,以下所有都会成功:
list_of_two_elements( X ).
on success, the variable X
will be unified with a list of two elements containing the same unbound variable, something like [V1,V1]
. 成功后,变量
X
将与包含相同未绑定变量的两个元素的列表统一,例如[V1,V1]
。
list_of_two_elements( [1,1] ).
list_of-two_elements( [1,X] ).
(on success, X
here will have been unified with the integer 1
.) (成功后,此处的
X
将与整数1
统一。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.