Prolog:试图使奇数甚至列表的特定要素
我想知道列表中存在多少个偶数和奇数,直到用户输入的特定索引。
以下代码正常工作,但仅给出偶数或奇数元素。有人可以帮助我获得所需的输出吗? 提前致谢。
:- use_module(library(clpfd)).
oddlength(L):-
L9 is L+2,
L6 is L9/2,
write('List has '),
write(L6),
write(' Odd Element').
evenlength(L):-
L6 is L/2,
write('List has '),
write(L6),
write(' Even Element').
split(Index,List,Left,Right) :-
length(Left,Index), % Actually CREATES a list of fresh variables if "Left" is unbound
append(Left,Right,List). % Demand that Left + Right = List.
write(List).
create(L1):-read(Elem),create(Elem,L1).
create(-1,[]):-!. create(Elem,[Elem|T]):-read(Nextel),create(Nextel,T).
chklst([H|T]):-
length(T,L),
L>=0 ->
(
L1 is L+1,
L2 is mod(L1,2),
L2=:=0 ->
evenlength(L1)
;
oddlength(L)
).
go:- write('Creating a list'),nl, write('Enter -1 to stop'),nl, create(L), nl, write('Enter index'),read(ID),split(ID,L,X1,X2),nl, chklst(X1).
I want to know how many even and odd numbers are present in the list up to a specific index entered by the user.
The following code is working but only gives either even or odd elements. Can someone help me getting the desired output?
Thanks in advance.
:- use_module(library(clpfd)).
oddlength(L):-
L9 is L+2,
L6 is L9/2,
write('List has '),
write(L6),
write(' Odd Element').
evenlength(L):-
L6 is L/2,
write('List has '),
write(L6),
write(' Even Element').
split(Index,List,Left,Right) :-
length(Left,Index), % Actually CREATES a list of fresh variables if "Left" is unbound
append(Left,Right,List). % Demand that Left + Right = List.
write(List).
create(L1):-read(Elem),create(Elem,L1).
create(-1,[]):-!. create(Elem,[Elem|T]):-read(Nextel),create(Nextel,T).
chklst([H|T]):-
length(T,L),
L>=0 ->
(
L1 is L+1,
L2 is mod(L1,2),
L2=:=0 ->
evenlength(L1)
;
oddlength(L)
).
go:- write('Creating a list'),nl, write('Enter -1 to stop'),nl, create(L), nl, write('Enter index'),read(ID),split(ID,L,X1,X2),nl, chklst(X1).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎。 。 。复杂的。
首先,您需要的是测试整数是否奇怪甚至是:
一旦有了即可穿越列表的简单问题。
如果您想要的只是计数:
That seems . . . complicated.
First thing you need is a predicate to test whether an integer is odd or even:
Once you have that it's a simple matter of traversing the list.
If all you want are counts: