排列到列表SWI-Prolog [英] Permute into a list SWI-Prolog

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

问题描述

您如何使用置换谓词将其输出到SWI序言中的列表中?

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)).

forall这是一个通用的内置函数,实现了一个故障驱动的循环,其简单性令人赞叹.我从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天全站免登陆