置换成列表 SWI-Prolog [英] Permute into a list SWI-Prolog

查看:19
本文介绍了置换成列表 SWI-Prolog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 permute 谓词输出到 SWI prolog 中的列表中?

How do you use the permute predicate to output into a list in SWI prolog?

permutation/2 谓词一次只返回一个结果.

The permutation/2 predicate only returns one result at a time.

推荐答案

如果你想要一个所有排列的列表,findall/3 是要走的路.如果要打印,可以使用 forall/2.无论哪种情况:

If you want a list of all permutations, findall/3 is the way to go. If you want to print, you can use forall/2. Either case:

case_a(In, L) :- findall(Perm, permutation(In, Perm), L).
case_b(In) :- forall(permutation(In, Perm), writeln(Perm)).

因为它是一个通用的内置函数,实现了一个失败驱动的循环,它的简单性令人惊叹.我报告了来自 SWI-Prolog 库的定义,我觉得很有趣.

forall it's a general purpose builtin, implementing a failure driven loop, amazing for its' simplicity. I report the definition from SWI-Prolog library, I think it's interesting.

%%  forall(+Condition, +Action)
%
%   True if Action if true for all variable bindings for which Condition
%   if true.

forall(Cond, Action) :-
    + (Cond, + Action).

如 false 所述,如果列表中有变量,则应注意 findall/3 WRT bagof/3 的不同行为:

As noted by false, if you have variables in your list, you should be aware of the different behaviour of findall/3 WRT bagof/3:

?- case_a([1,2,3],X).
X = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]].

?- case_a([A,B,C],X).
X = [[_G467, _G470, _G473], [_G455, _G458, _G461], [_G443, _G446, _G449], [_G431, _G434, _G437], [_G419, _G422, _G425], [_G407, _G410, _G413]].

请注意,第二个查询输出中的每个变量都是不同的:这可能是请求结果,也可能不是,取决于手头的问题.决定适当的行为 WRT 变量量化在变量是数据的受限问题类别中是强制性的,即元编程,我认为......

Note that each variable in in the second query output is different: that could be the request outcome, or not, depending on the problem at hand. Deciding the appropriate behaviour WRT the variable quantification is mandatory in the restricted class of problems where variables are data, i.e. metaprogramming, I think...

这篇关于置换成列表 SWI-Prolog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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