简单的序言程序.得到错误:>/2:参数没有被充分实例化 [英] Simple prolog program. Getting error: >/2: Arguments are not sufficiently instantiated

查看:83
本文介绍了简单的序言程序.得到错误:>/2:参数没有被充分实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个Prolog谓词posAt(List1,P,List2),该谓词用于测试List1List2的位置P处的元素是否相等:

I made a Prolog predicate posAt(List1,P,List2) that tests whether the element at position P of List1 and List2 are equal:

posAt([X|Z], 1, [Y|W]) :-
   X = Y.
posAt([Z|X], K, [W|Y]) :-
   K > 1,
   Kr is K - 1,
   posAt(X, Kr, Y).

测试时:

?- posAt([1,2,3], X, [a,2,b]).

我希望输出为X = 2,但是却出现了以下错误:

I expected an output of X = 2 but instead I got the following error:

ERROR: >/2: Arguments are not sufficiently instantiated

为什么会出现此错误?

推荐答案

Prolog谓词是参数与语句之间的关系

A Prolog predicate is a relation between arguments, and your statement

List1和List2的位置P上的元素相等

the element at position P of List1 and List2 are equal

显然是一个可能有多种解决方案的例子.

is clearly an example where multiple solutions are possible.

?- posAt([1,2,3],X,[1,5,3,7]).
X = 1.

因此,鲨鱼"的答案虽然可以清楚地解释为什么会出现技术错误,但需要进行一些小的修正:

So the answer from sharky, while clearly explains why the technical error arises, requires a small correction:

posAt([X0|_], Pos, Pos, [X1|_]) :-
    X0 == X1.

现在它可以正常工作了.

Now it works as expected.

?- posAt([1,2,3],X,[1,5,3,7]).
X = 1 ;
X = 3 ;
false.

为列表处理编写简单的谓词是一种非常有价值的学徒实践,也是有效学习该语言的主要方法.如果您也想研究可用的库谓词,那么以下是使用库中的nth1/3的版本(

Writing simple predicates for list processing it's a very valuable apprenticeship practice, and the main way to effectively learn the language. If you are incline also to study the available library predicates, here is a version using nth1/3 from library(lists)

posAt(L0, P, L1) :-
   nth1(P, L0, E),
   nth1(P, L1, E).

这将输出:

?- posAt([1,2,3],X,[1,5,3,7]).
X = 1 ;
X = 3.

尝试理解为什么在这种情况下SWI-Prolog顶级"解释器能够推断解决方案的确定性"可能会很有趣.

Could be interesting to attempt understanding why in this case SWI-Prolog 'top level' interpreter is able to infer the determinacy of the solution.

这篇关于简单的序言程序.得到错误:>/2:参数没有被充分实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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