【问题标题】:How do I implement in Prolog the predicate list_for_set如何在 Prolog 中实现谓词 list_for_set
【发布时间】:2020-04-21 17:08:27
【问题描述】:

如何在 Prolog 中实现谓词 list_for_set(Xs, Cs) 其中 Cs 是一个列表,其中包含与 Xs 相同的元素,按其首次出现的顺序排列,但其出现次数仅为 1。例如,查询

? - list_for_set([1, a, 3.3, a, 1.4], Cs).

它只发生在 Cs = [1, a, 3,4] 上。咨询

? - list_for_set ([1, a, 3,3, a, 1,4], [a, 1,3,4])

必须失败。

前面语句的Cs列表将被称为集合列表,即每个元素只出现一次的列表。

【问题讨论】:

  • 来吧,OP,这并不难。

标签: prolog


【解决方案1】:

好的,这其中涉及到一些诡计。

foofilter([],_,_-T) :- T=[]. % close difflist

foofilter([L|Ls],Seen,H-T) :-
   member(L,Seen),
   !,
   foofilter(Ls,Seen,H-T).

foofilter([L|Ls],Seen,H-T) :-
   \+member(L,Seen),
   !,
   T=[L|NewT],
   foofilter(Ls,[L|Seen],H-NewT).
:-begin_tests(filter).

data([1, a, 3, 3, a, 1, 4]).

test(one) :- data(L),
             DiffList=[[]|T]-T,  % Assume [] is never in L
             foofilter(L,[],DiffList),
             DiffList=[_|Result]-_,
             format("~q ==> ~q\n",[L,Result]),
             Result = [1,a,3,4].

:-end_tests(filter).

rt :- run_tests(filter).

运行测试:

?- rt.
% PL-Unit: filter [1,a,3,3,a,1,4] ==> [1,a,3,4]
. done
% test passed
true.

有人可能会想出一个单行。

【讨论】:

  • 你能提醒我差异列表是如何工作的吗?
  • @Enigmativity 试试我的解释器:github.com/dtonhofer/prolog_notes/tree/master/difflists
  • @Enigmativity 但虚拟元素[] 让我很恼火。必须可以不用。
  • @Enigmativity 好的,它可以在没有虚拟条目的情况下工作,我必须在上面的链接中更新我的图像。
猜你喜欢
  • 2013-04-06
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多