如何计算数字列表中的偶数和奇数 [英] How to count even and odd numbers in a list of numbers
问题描述
我想编写一个函数,告诉我列表中偶数和奇数的出现次数。例如,如果我的列表是[1,2,3,4,5],我希望它返回(2,3)。
这就是我目前的情况
counteven :: [整数] - >整数
counterteven [] = 0
counterteven(x:xs)
|(x`div` 2)== 0 = 1 + counterteven xs
| otherwise = counteven xs
countodd :: [Integer] - >整数
countodd [] = 0
countodd(x:xs)
|(x`div` 2)/ = 0 = 1 + countodd xs
|否则= countodd xs
oddsAndEvens :: [Integer] - > (整数,整数)
oddsAndEvens(x:xs)=((counteven(x:xs)),(countodd(x:xs)))
它在我的文本编辑器上运行,但是我得到了奇怪的结果。
有人可以帮我解决问题吗?
您有两个问题。
问题1: div
vs mod
。
div
将数字分开。 mod
取其余数。例如, div 6 2 = 3
和 mod 6 2 = 0
。
您错误地使用 div
。这应该是 mod
,所以例如你的第一个函数应该是:
counteven :: [Integer] - >整数
counterteven [] = 0
counterteven(x:xs)
| x`mod` 2 == 0 = 1 + counterteven xs - 注意:`mod`不是`div`!
|否则= counteven xs
我相信你可以修正 您的最终功能也有问题: 由于 I want to write a function that will tell me the number of even and odd number occurences within a list. For example, if my list was [1,2,3,4,5], I want it to return (2,3). This is what I have so far It does run on my text editor but I am getting strange results. You have two problems. You incorrectly use I'm sure you can fix Your final function has an issue too: The argument It should be: Since 这篇关于如何计算数字列表中的偶数和奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! countodd $
问题二:过度限制性模式匹配
oddsAndEvens :: [Integer] - > (整数,整数)
oddsAndEvens(x:xs)=(counteven(x:xs),countodd(x:xs))
(x:xs)
只有模式匹配非空列表,所以 oddsAndEvens []
会产生错误,因为您尚未定义其行为。
oddsAndEvens :: [Integer] - > (Integer,Integer)
oddsAndEvens xs =(counteven xs,countodd xs)
xs
匹配任何东西,函数现在可以用于空列和非空列表。counteven :: [Integer] -> Integer
counteven [] = 0
counteven (x:xs)
|(x `div` 2) == 0 = 1 + counteven xs
|otherwise = counteven xs
countodd :: [Integer] -> Integer
countodd [] = 0
countodd (x:xs)
|(x `div` 2) /= 0 = 1 + countodd xs
|otherwise = countodd xs
oddsAndEvens :: [Integer] -> (Integer,Integer)
oddsAndEvens (x:xs) = ((counteven(x:xs)),(countodd(x:xs)))
Can someone please help me what the problem might be?Problem 1:
div
vs mod
.div
divides numbers. mod
takes their remainder. For example, div 6 2 = 3
, and mod 6 2 = 0
.div
. That should be mod
, so for instance your first function should be: counteven :: [Integer] -> Integer
counteven [] = 0
counteven (x:xs)
| x `mod` 2 == 0 = 1 + counteven xs -- NOTE: `mod` not `div`!
| otherwise = counteven xs
countodd
on your own given this example.Problem two: over-restrictive pattern matching.
oddsAndEvens :: [Integer] -> (Integer, Integer)
oddsAndEvens (x:xs) = (counteven (x:xs), countodd (x:xs))
(x:xs)
only pattern matches on non-empty lists, so oddsAndEvens []
will produce an error, since you haven't defined its behaviour.oddsAndEvens :: [Integer] -> (Integer, Integer)
oddsAndEvens xs = (counteven xs, countodd xs)
xs
matches anything, the function will now work for empty and nonempty lists.