【问题标题】:Prolog - Append some elements form a list to another oneProlog - 将列表中的一些元素附加到另一个元素
【发布时间】:2016-07-07 18:16:58
【问题描述】:

我需要像这样将列表中的一些元素附加到另一个列表中:

find_same(pt(1,1),pt(2,2),6,[slope(6,pt(3,3)),slope(6,pt(4,4)),slope(7,pt(3,2)),slope(9,pt(5,5))],NL).

结果

NL=[pt(1,1),pt(2,2),pt(3,3),pt(4,4)]

我尝试过使用 append,但我遇到了一些问题,代码如下:

find_same(_,_,_,[],_):-!.
find_same(pt(X,Y),pt(Xa,Ya),R,Slopes,Nl):-X\=a,
    append(Nla,[pt(X,Y),pt(Xa,Ya)],Nl),
    find_same(pt(a,a),pt(b,b),R,Slopes,Nla).
find_same(pt(X,Y),pt(Xa,Ya),R,[slope(R,pt(Xs,Ys))|Ss],Nl):-X=a,
     append(Nla,[pt(Xs,Ys)],Nl),
     find_same(pt(X,Y),pt(Xa,Ya),R,Ss,Nla).
find_same(_,_,R1,[slope(R2,_)|_],_):-R1\=R2,!.

因为返回给我很多列表。

然后我尝试使用其他代码:

find_same2(_,_,_,[],_):-!.
find_same2(pt(X,Y),pt(Xa,Ya),R,Slopes,_):-X\=a,
           find_same2(pt(a,a),pt(b,b),R,Slopes,[pt(X,Y),pt(Xa,Ya)]).
find_same2(pt(X,Y),pt(Xa,Ya),R,[slope(R,pt(Xd,Yd))|Ss],[pt(Xd,Yd)|Nl]):-
           X=a,!,
           find_same2(pt(X,Y),pt(Xa,Ya),R,Ss,Nl).
find_same2(_,_,R1,[slope(R2,_)|_],_):-R1\=R2.

但它只返回 false。

我该如何解决这个问题?谢谢

【问题讨论】:

    标签: prolog


    【解决方案1】:

    因为您不关心点的具体组成部分是什么,所以您可以将每个点视为单个变量。因此,不要以 pt(X, Y) 为例,而是将其视为 P

    所以你要找到共同点:

    find_common(P1, P2, N, SlopeList, Result)
    

    如果您可以从SlopeList 创建符合您条件的元素子列表,那么您可以通过添加两个现有点来形成Result。如果调用该子列表CommonPoints,那么您的Result 将只是[P1, P2 | CommonPoints]

    现在你只需要弄清楚如何确定CommonPoints。您可以使用member/2 来执行此操作。考虑:

    member(slope(N, P), SlopeList)
    

    这对于SlopeList 中具有元素slope(N, P) 的每个元素都会成功。要将它们收集在一起,您可以使用findall/3

    findall(P, member(slope(N, P), SlopeList), CommonPoints).
    

    这些都是您解决问题所需的全部内容。你只需要把它们放在一起。

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2015-02-05
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多