在Prolog中查找列表的长度 [英] Finding Length of List in Prolog
问题描述
我正在运行Prolog并尝试编写一个返回列表长度的小函数:
I'm running Prolog and trying to write a small function returning the length of a list:
len([],0).
len([XS], Y) :-
len([X|XS], M),
Y is M+1.
我的逻辑是,递归调用应包括列表的尾部(XS),并将1增加到先前的长度(Y为M + 1.)
My logic is that the recursive call should include the tail of the list (XS) and increase 1 to the previous length (Y is M+1.)
这总是返回false.
This always returns false.
有什么想法吗?
推荐答案
以下是调试和测试Prolog谓词的通用方法:
Here is a general methodology for debugging and testing Prolog predicates:
考虑一下:在Prolog中,您不需要组成一些测试数据.您甚至根本不需要了解谓词:只需输入自由变量即可!那总是专业的举动!
Think of it: In Prolog you do not need to make up some test data. You don't even need to understand a predicate at all: Just hand in free variables! That is always a professional move!
因此,就您而言,
?- len(L,N).
L = [],
N = 0 ;
*LOOPS**
您的定义并不像您声称的那么糟糕:至少对于空白列表而言,它是正确的.
Your definition is not that bad as you claim: At least, it is true for the empty list.
现在,也许看看您可能收到的编译器警告:
Now, maybe look at the compiler warnings you probably received:
Warning: user://1:11:
Singleton variables: [X]
接下来,按照箭头:-
的方向(即从右到左)读取递归规则:
Next read the recursive rule in the direction of the arrow :-
that is, right-to-left:
提供的len([X|Xs], M)
是真实的,而Y is M+1
是真实的,只要所有这些都是真实的,我们就可以得出结论
Provided len([X|Xs], M)
is true and Y is M+1
is true, provided all that is true, we can conclude that
len([XS], Y)
也是如此.因此,您总是得出关于长度为1([Xs]
)的列表的结论.
len([XS], Y)
is true as well. So you are always concluding something about a list of length 1 ([Xs]
).
您需要将其重新配置为len([X|Xs], M) :- len(Xs, N), Y is M+1
.
You need to reformulate this to len([X|Xs], M) :- len(Xs, N), Y is M+1
.
这是另一种策略:
通过消除目标,我们可以推广程序 1 .这是我最喜欢的方式.通过添加谓词(*)/1
像这样:
By removing goals, we can generalize a program1. Here is my favorite way to do it. By adding a predicate (*)/1
like so:
:- op(950,fy, *).
*_.
现在,让我们从程序中删除所有目标:
Now, let's remove all goals from your program:
len([],0).
len([XS], Y) :-
* len([X|XS], M),
* Y is M+1.
我们现在所拥有的是概括.再次,我们将看看最普遍的查询的答案:
What we have now is a generalization. Once again, we will look at the answers of the most general query:
?- len(L, N).
L = [],
N = 0 ;
L = [_].
什么? len/2
仅适用于长度为0和1的列表.这意味着,即使len([1,2], N)
也会失败!因此,现在我们可以确定:必须修复程序可见剩余部分中的某些内容.实际上,[XS]
仅描述了长度为1的列表.因此,必须将其删除...
What? len/2
is only true for lists of length 0 and 1. That means, even len([1,2], N)
fails! So now we know for sure: something in the visible remaining part of the program has to be fixed. In fact, [XS]
just describes lists of length 1. So this has to be removed...
精美打印:
1某些限制适用.本质上,您的程序必须是纯粹的单调程序.
这篇关于在Prolog中查找列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!