纯 append/3 模式 (

编程入门 行业动态 更新时间:2024-10-21 22:58:51
本文介绍了纯 append/3 模式 (-,+,+) 不会留下选择点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-17 20:01:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/921561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   append

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!