[英]List of list, the no of lists with maximum 1 even number
I'm new in Haskell and I tried this using recursion我是 Haskell 的新手,我尝试使用递归
f :: [[Integer]] -> Integer
f [] = 0
f [x] = 1
f ((x : xs) : xss)
| even x = 1 + f (xs : xss)
| otherwise = f (xs : xss)
but doesn't work and I think its totally wrong.但不起作用,我认为它完全错误。 How can I make this using recursion, list comprehension and map, filter functions?
如何使用递归、列表理解和 map 过滤函数来实现这一点? For exemple, f[[2,3,4], [1,0], [1,3,5,7]] = 2
例如,f[[2,3,4], [1,0], [1,3,5,7]] = 2
If I get the tile right you want to count all inner-lists with at-most 1 even number in them.如果我得到正确的瓷砖,你想计算所有内部列表,其中最多有 1 个偶数。
So let's split this - first count all even numbers in a list:所以让我们拆分一下 - 首先计算列表中的所有偶数:
evenNumberCount :: [Integer] -> Int
evenNumberCount ls = length (filter even ls)
having this we can do a test if a list has at most one:有了这个,我们可以做一个测试,如果一个列表最多有一个:
atMostOneEvenNumber :: [Integer] -> Bool
atMostOneEvenNumber ls = evenNumberCount ls <= 1
I guess at this point it's easy enough to plug together the answer:我想在这一点上很容易将答案组合在一起:
f :: [[Integer]] -> Int
f ls = length (filter atMostOneEvenNumber ls)
your example:你的例子:
> f[[2,3,4], [1,0], [1,3,5,7]]
2
Note: this has the wrong signature (because length:: [a] -> Int
) - if you want Integer
either add fromIntegral
to the right side or switch to genericLength
and adapt the signatures注意:这有错误的签名(因为
length:: [a] -> Int
) - 如果你想要Integer
要么将fromIntegral
添加到右侧或切换到genericLength
并调整签名
(Note to Haskellers reading: I'm aware that length:: Foldable t => ta -> Int
don't think this helps here;) ) (Haskellers 阅读注意:我知道
length:: Foldable t => ta -> Int
认为这在这里没有帮助;))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.