Prolog只选择第一个解决方案

时间:2016-07-07 08:45:22

标签: prolog

我有这个代码返回了很多解决方案,但我只需要第一个列表,我认为我必须使用一些剪切,但我是Prolog的新手,我找不到我必须把它放在哪里。

list_s(_,[],_) :-
    !.
list_s(P,[P|Ps],ListS) :-
    list_slope(P,Ps,ListS).
list_s(pt(X,Y),[pt(A,B)|Ps],ListS) :-
    angle(pt(X,Y),pt(A,B),R),
    new_s(R,pt(A,B),Ns),
    append(Nls,[Ns],ListS),
    !,
    list_s(pt(X,Y),Ps,Nls).

我试图将它放在append/3之后,但这不起作用。 我该如何解决这个问题?

编辑:我认为问题在于追加可能我需要改变或改进这个功能。

实施例

1 ?- list_slope(pt(2,2),[pt(1,1),pt(2,9),pt(3,8),pt(4,7)],L).

L = [slope(0.3805063771123649, pt(4, 7)), slope(0.16514867741462683, pt(3, 8)), slope(0.0, pt(2, 9)), slope(0.7853981633974483, pt(1, 1))] ;

L = [_G2260, slope(0.3805063771123649, pt(4, 7)), slope(0.16514867741462683, pt(3, 8)), slope(0.0, pt(2, 9)), slope(0.7853981633974483, pt(1, 1))] ;
L = [_G2260, _G2266, slope(0.3805063771123649, pt(4, 7)), slope(0.16514867741462683, pt(3, 8)), slope(0.0, pt(2, 9)), slope(0.7853981633974483, pt(1, 1))] ;

L = [_G2260, _G2266, _G2272, slope(0.3805063771123649, pt(4, 7)), slope(0.16514867741462683, pt(3, 8)), slope(0.0, pt(2, 9)), slope(0.7853981633974483, pt(1, 1))]

2 个答案:

答案 0 :(得分:1)

如果你只想要Prolog谓词的第一个结果,你可以简单地做

digest()

答案 1 :(得分:1)

不是使用剪切或丢弃(显然是错误的)解决方案,而是最好重写代码以避免首先出现不需要的选择点。例如,假设始终使用绑定的前两个参数调用谓词:

list_slope(Point, Points, Slopes) :-
    % change argument order to exploit
    % first-argument indexing
    list_slope_(Points, Point, Slopes).

list_slope_([], _, []).
list_slope_([pt(A,B)| Points], pt(X,Y), [Slope| Slopes]) :-
    angle(pt(X,Y), pt(A,B), Angle),
    new_slope(Angle, pt(A,B), Slope),
    list_slope_(Points, pt(X,Y), Slopes).

但是,与原始代码相比,这将以相反的顺序给出斜率。如果需要相反的顺序,您可以使用累加器轻松获得它:

list_slope(Point, Points, Slopes) :-
    % change argument order to exploit
    % first-argument indexing
    list_slope_(Points, Point, [], Slopes).

list_slope_([], _, Slopes, Slopes).
list_slope_([pt(A,B)| Points], pt(X,Y), Acc, Slopes) :-
    angle(pt(X,Y), pt(A,B), Angle),
    new_slope(Angle, pt(A,B), Slope),
    list_slope_(Points, pt(X,Y), [Slope| Acc], Slopes).
相关问题