如何计算列表中的所有偶数 [英] How to count all even numbers in a list

查看:227
本文介绍了如何计算列表中的所有偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我如何计算在Prolog中的列表中的偶数。我是一个初学者,刚刚开始学习Prolog昨天。我知道列表中的元素是

Please help me with how to count even numbers in a list in Prolog. I am a beginner, just started learning Prolog yesterday. I know to count the elements in the list is

mylen([H|Lc],N) :- mylen(Lc,M),N is M+1.
mylen([],0).

我认为定义偶数在这种情况下可能有帮助,我想代码可能是:

And I think defining even number maybe helpful in this case, and I guess the code is maybe something like:

even(n):-
  N rem 2 =:= 0.

你能帮我把这两个部分放在一起,所以我的代码计数为偶数?我知道我还需要添加一个计数器,但我不知道如何在Prolog中这样做。

Can you help me with putting these two parts together, so my code counts even numbers? I know I also need to add a counter, but I have no idea of how to do this in Prolog.

非常感谢您的帮助!

推荐答案

目前,您有两条规则:

空列表中的元素数量为 0

(1) The number of elements in the empty list is 0

my_len([], 0).

(2)列表中的元素数 [H | Lc] 是 N 如果列表中的元素数量 Lc M 1

(2) The number of elements in the list [H|Lc] is N if the number of elements in the list Lc is M and N is M+1

my_len([H|Lc], N) :- my_len(Lc, M), N is M+1.

你已经装备了一个谓词,如果数字是偶数则为true,如果数字为偶数,则为false不是: N 甚至如果除以 N 2 是 0

You're already armed with a predicate which is true if a number is even, and false if it is not: N is even if the remainder of N when divided by 2 is 0:

even(N) :- N rem 2 =:= 0.

现在你可以把它拼凑在一起。空列表中偶数元素的数量仍为零。所以你保留规则(1)。你的规则(2)将需要改变,因为它需要检查列表的头是否是偶数。你可以用Prolog中的两个规则来处理这个问题,这两个规则负责处理两种不同的情况(列表头是偶数,或列表头是奇数):

Now you can piece it together. The number of even elements in an empty list is still zero. So you keep rule (1). Your rule (2) will need to change as it will need to check if the head of the list is even. You can do this with with two rules in Prolog which take care of the two different cases (the list head is even, or the list head is odd):

[H | Lc] 中的均匀元素数量为 N 如果 H 甚至 strong>元素 Lc M

(2a) The number of even elements in list [H|Lc] is N if H is even, and the number of even elements in list Lc is M, and N is M+1.

(2b) 列表 [H | Lc] 均匀元素的数量为 N 如果 H 甚至(或 H 元素的数量,列表 Lc 中的偶数元素的数量为 N 。 [请注意,如果 H 是奇数, N 。]

(2b) The number of even elements in list [H|Lc] is N if H is not even (or H is odd), and the number of even elements in list Lc is N. [Notice that N doesn't change if H is odd.]

我将这两个规则的呈现作为练习留在Prolog中。您可以使用Prolog否定函数 \ + 来测试数字是否不等于 \ + even(N)。或者您可以定义 odd(N): - N rem 2 =:= 1。用于此情况的谓词。

I'll leave the rendering of these two rules into Prolog as an exercise. You can use the Prolog negation functor, \+ to test if a number is not even, by \+ even(N). Or you can define an odd(N) :- N rem 2 =:= 1. predicate to use for that case.

这篇关于如何计算列表中的所有偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆