如何使用PROLOG计算奇数和偶数
问题是:
当我们输入 mem([1,2,3,4,5]) 时。
我们将得到如下输出:
odd=3
Even=2
我的编码是这样的,但无法运行。可以帮我检查一下我的错误在哪里吗?
内存(X,[X | L])。
mem(X,[元素|L]):- 内存([X,L])。
计数([],L,L)。
计数([X | H],L1,L2):- 写(偶数), X%2=0,nl, 写(奇数), X%2>=1,nl, 计数([H],[X|L1],L2)。
感谢您的帮助。
question is:
when we key in mem([1,2,3,4,5]).
we will get the output as bellow:
odd=3
even=2
my coding is like that but cannot run. can help me check where is my mistake??
mem(X,[X|L]).
mem(X,[element|L]):-
mem([X,L]).
count([],L,L).
count([X|H],L1,L2):-
write(even),
X%2=0,nl,
write(odd),
X%2>=1,nl,
count([H],[X|L1],L2).
thanks for your helping.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您编写的过程执行两种不同的操作,并且实际上并不属于一起。
mem/2
等同于通常内置的member/2
,只不过您的定义包含错误:在第二个子句中element
是一个原子变量,因此它不会匹配列表中的其他元素。通常的定义是请注意,此定义不仅会测试术语是否是列表的元素,而且甚至可以用于生成列表。
您到底想在
count/3
中做什么:将列表拆分为两个列表,一个包含奇数,另一个包含偶数;或者计算奇数和偶数元素的数量?可以通过以下方式完成拆分:请注意,
=/= /2
和=:= / 2
强制将参数计算为算术表达式,而= /2
试图统一其论点。可以用类似的方式计算奇数和偶数的数量,并留给读者作为练习。 :-)
The procedures you have written do two different things and don't actually belong together.
mem/2
is equivalent to the usually builtinmember/2
except that your definition contains an error: in the second clauseelement
is an atom instead of a variable so it will not match other elements of the list. The usual definition isNote that this definition will not only test if a term is an element of a list but can even be use to generate a list.
What exactly are you trying to do in
count/3
: split the list into two lists, one containing odd and the other containing even; or count the number of odd and even elements? The splitting could be done with something like:Note that
=/= /2
and=:= / 2
force evaluation of arguments as arithmetic expressions while= /2
attempts to unify its arguments.Counting the number of odds and evens can be done in a similar fashion, and is left as an exercise for the reader. :-)