问题描述
限时送ChatGPT账号..通常的 append/3 是纯的,但它为模式 (-,+,+) 留下了一个选择点:
The usually append/3 is pure, but it leaves a choice point for mode (-,+,+):
?- append(X, [3], [1,2,3]).
X = [1, 2] ;
false.
在上面的结果中你是一个选择点可以看出,例如 SWI-Prolog 提供提示,然后;"提供虚假.我想出了这个解决方案来避免选择点:
That thee is a choice point in the above result is seen in that for example SWI-Prolog offers the prompt and then ";" delivers false. I came up with this solution to avoid the choice point:
append2(X, Y, Z) :-
reverse(Z, H),
reverse(Y, J),
append(J, K, H),
reverse(K, X).
这个新的 append2/3 不再留下选择点:
This new append2/3 doesn't leave a choice point anymore:
?- append2(X, [3], [1,2,3]).
X = [1, 2].
但是有比 reverse/2 cludge 更好的解决方案吗?请注意,有一个谓词 last/3 可用于该示例,仅从末尾删除一个元素.但是模式 (-,+,+) 应该适用于第二个参数中的任意长列表.
But are there better solutions than the reverse/2 cludge? Note, that there is a predicate last/3 which could be used for the example with only one element removed from the end. But the mode (-,+,+) should work for arbitrary long lists in the second argument.
推荐答案
你的 append2
不会为 (-, +, +) 模式留下选择点,而是为其他模式引入它们.我不知道是否可以在不使用 var/1
或其他东西检查操作模式的情况下编写它.
Your append2
doesn't leave choice point for (-, +, +) mode but introduces them for other modes. I do not know if it is possible to write it without checking the mode of operation using var/1
or something.
这是 mercury library 手册中的评论关于所讨论的模式.
Here is a comment from the mercury library manual regarding the mode in question.
% The following mode is semidet in the sense that it doesn't
% succeed more than once - but it does create a choice-point,
% which means it's inefficient and that the compiler can't deduce
% that it is semidet. Use remove_suffix instead.
% :- mode append(out, in, in) is semidet.
remove_suffix
谓词在 Mercury 中实现如下:
The remove_suffix
predicate is implemented in mercury as follows:
remove_suffix(List, Suffix, Prefix) :-
list.length(List, ListLength),
list.length(Suffix, SuffixLength),
PrefixLength = ListLength - SuffixLength,
list.split_list(PrefixLength, List, Prefix, Suffix).
这篇关于纯 append/3 模式 (-,+,+) 不会留下选择点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论