简体   繁体   English

从Prolog中的递归谓词输出最终列表

[英]Outputting final list from recursive predicate in Prolog

I wrote a program, that finds the longest coprime subsequence in a Prolog list (it is not yet perfect): 我写了一个程序,找到Prolog列表中最长的互质子序列(它还不完美):

longest_lcs([A, B | Tail],X) :- gcd(A,B,1),lcs([B | Tail],X,A,1).
longest_lcs([A, B | Tail],X) :- lcs([B | Tail],X,A,0).

lcs([],G,_,_) :- rev(G,G1),write(G1).

lcs([A, B | Tail],G,Q,_) :- gcd(B,Q,1), gcd(A,B,1), lcs([B | Tail], [Q | G], A, 1),!.
lcs([A, B | Tail],G,Q,_) :- gcd(B,Q,1);gcd(A,B,1), lcs([B | Tail], [Q | G], A, 0).

lcs([A, B | Tail],G,_,0) :- gcd(A,B,1), lcs([B | Tail], G, A, 1).
lcs([A, B | Tail],G,_,1) :- lcs([B | Tail], G, A, 1).
lcs([A, B | Tail],G,_,0) :- lcs([B | Tail], G, A, 0).

lcs([A],G,Q,_) :- gcd(Q,A,1),lcs([], [A, Q | G], _, _).    

Currently I output the subsequence with the write predicate, but I need it to run the following way: 目前我用write谓词输出子序列,但我需要它以下面的方式运行:

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

?- longest_lcs([2,4,8,16],X).
X = []

What modifications do I need to make, so this works? 我需要做哪些修改,这样有效吗?

Why do you want to use write/1? 你为什么要使用write / 1? Focus on a clear declarative description of what you want, and the toplevel will do the writing for you. 专注于对你想要的明确的陈述性描述,并且顶层将为你写作。 A possible formulation for a longest coprime subsequence is: It is a coprime subsequence, and no other coprime subsequnce is longer. 最长的互质子序列的可能公式是:它是一个互质子序列,没有其他互质子序列更长。 The code could look similar to this: 代码看起来与此类似:

list_lcpsubseq(Ls, Subseq) :-
    list_subseq(Ls, Subseq),
    coprimes(Subseq),
    length(Subseq, L),
    \+ ( list_subseq(Ls, Others), coprimes(Others), length(Others, O), O > L ).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM