反转列表时出现 prolog 空列表错误
首先,我对 Prolog 很陌生,只是想了解最基本的知识。
我必须工作一个连接两个列表的简单函数和一个反转列表的函数。
这个实现:
cconcat([], L, L).
cconcat([H1|T1], L2, [H1|T2]) :- cconcat(T1, L2, T2).
revv([], []).
revv(R, [H|T]) :- revv(R1, T), cconcat(R1,[H],R).
效果很好,但是这个
cconcat([], L, L).
cconcat([H1|T1], L2, [H1|T2]) :- cconcat(T1, L2, T2).
revv(R, []) :- R is [].
revv(R, [H|T]) :- revv(R1, T), cconcat(R1,[H],R).
给了我这个错误:类型错误:预期为“evaluable”,找到了“[]”
。
这是为什么?它们不是等价的吗?
First of all I'm very new to Prolog and just trying to understand the very basics.
I have to work a simple function that concatenes two lists and a function that reverses a list.
This implementation:
cconcat([], L, L).
cconcat([H1|T1], L2, [H1|T2]) :- cconcat(T1, L2, T2).
revv([], []).
revv(R, [H|T]) :- revv(R1, T), cconcat(R1,[H],R).
works well, but this one
cconcat([], L, L).
cconcat([H1|T1], L2, [H1|T2]) :- cconcat(T1, L2, T2).
revv(R, []) :- R is [].
revv(R, [H|T]) :- revv(R1, T), cconcat(R1,[H],R).
gives me this error : Type error: `evaluable' expected, found `[]'
.
Why is that? Aren't they equivalent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与此重写相同:
is() 是为这种用途而设计的:
is() 想要一些它可以评估的数学;这就是错误消息的含义,它不知道如何评估空列表。 R = [] 可以在那里工作,但你的第一个版本更好。
is the same as this rewrite:
is() was made for this kind of use:
is() wants some math it can evaluate; that's what the error message means, it doesn't know how to evaluate an empty list. R = [] will work there, but your first version is better.
对于串联,有 3 种特殊情况:
以及 2 个非空列表的一般情况,我们从左侧列表复制元素并向下递归(直到我们陷入终止递归的特殊情况):
将所有这些放在一起,您会得到:
反转列表更容易。在这里,我们使用一个辅助谓词
reverse_list/3
,它带有一个维护状态的额外参数:For concatenation, you have 3 special cases:
And the general case of 2 non-empty lists, for which we copy elements from the left list and recurse down (until we collapse into a special case that terminates the recursion):
Putting it all together you get:
Reversing a list is easier. Here, we use a helper predicate,
reverse_list/3
that carries an extra argument that maintains state: