简体   繁体   English

Prolog递归列表比较

[英]Prolog Recursive List Comparison

I just started Prolog and for practice I'm trying to compare two lists and see if the first list is greater than the second list by one element. 我刚刚启动Prolog,为了进行练习,我尝试比较两个列表,看看第一个列表是否比第二个列表大一个元素。 So far I got the base case to work, but for any list with more than one element it loops infinitely. 到目前为止,我已经有了基本情况,但是对于任何包含多个元素的列表,它都会无限循环。 Could anyone explain why this is happening? 谁能解释为什么会这样? Any information is appreciated. 任何信息表示赞赏。

Code

one_longer([H],[]).
one_longer([H|T],[H2|T2]) :- one_longer([T],[T2]).

The clause should be: 该子句应为:

one_longer([H|T],[H2|T2]) :- one_longer(T,T2).

As one_longer([T],[T2]) forms a new lists with only one element which results in the observed loop as when the rule is applied again results in continually asking one_longer([[]],[[]]) where as one_longer(T,T2) applies one_longer to the remainders of the two lists. one_longer([T],[T2])形成一个只有一个元素的新列表时,这会导致观察到的循环,因为再次应用该规则会导致不断询问one_longer([[]],[[]])在哪里one_longer(T,T2)one_longer应用于两个列表的其余部分。

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

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