带序言的列表中最长的偶数序列
我想实现一个谓词 Even_sequence(X,Y,Z),其中 X 是给定列表,Y 是偶数序列最大长度的计数器,Z 是存储当前偶数子序列长度的计数器。例如,对于给定列表 2,4,6,3,5,2,2
我想返回 3
因为 2,4,6
> 是最长的序列。
这是我尝试过的代码,但我不知道如何使其工作(我是 Prolog 的初学者)。如果我运行 even_sequence([2,2,2,3,3],C, R)
我收到错误:参数未充分实例化 In: [1] Even_sequence([2,2|...],_1730,_1732)
even_sequence([],_,_).
even_sequence([H|T],GlobalMax,LocalMax):-
H mod 2 =:= 0,
LocalMax1 is LocalMax+1,
even_sequence(T,GlobalMax,LocalMax1).
even_sequence([H|T],GlobalMax,LocalMax):-
H mod 2 =\= 0,
GlobalMax1 is LocalMax,
LocalMax1 is LocalMax-LocalMax,
even_sequence(T,GlobalMax1,LocalMax1).
I want to implement a predicate even_sequence(X,Y,Z) where X is the given list, Y is a counter of the max length of even numbers sequence, and Z is the counter that stores the length of the current even number subsequence. For example for the given list 2,4,6,3,5,2,2
i want to return 3
because 2,4,6
is the longest sequence.
Here is the code that i tried and i don't know how to make it work(i am a total beginner in Prolog).If i run even_sequence([2,2,2,3,3],C,R)
i get the error: Arguments are not sufficiently instantiated In: [1] even_sequence([2,2|...],_1730,_1732)
even_sequence([],_,_).
even_sequence([H|T],GlobalMax,LocalMax):-
H mod 2 =:= 0,
LocalMax1 is LocalMax+1,
even_sequence(T,GlobalMax,LocalMax1).
even_sequence([H|T],GlobalMax,LocalMax):-
H mod 2 =\= 0,
GlobalMax1 is LocalMax,
LocalMax1 is LocalMax-LocalMax,
even_sequence(T,GlobalMax1,LocalMax1).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
swi-prolog 中的结果:
Result in swi-prolog: