简体   繁体   English

从 Haskell 中的列表返回有条件的出现次数

[英]Returning number of occurences with condition from list in Haskell

I want to filter number from list by condition that they have to be less than 3 and then how many elements like this were in starting list我想从列表中过滤数字,条件是它们必须小于 3,然后在起始列表中有多少这样的元素

filterLove :: (Num a, Ord a) => [a] -> Int
filterLove [42, 66, 15, 2] ~>* 1

I tried this filterLove filter (< 3) a = length a but it doesn't work.我试过这个filterLove filter (< 3) a = length a但它不起作用。 I can't figure out how would i do it.我不知道我该怎么做。 Thanks for help.感谢帮助。

filterLove is a function that maps a list of items so that means you define it as: filterLove是一个映射项目列表的函数,这意味着您可以将其定义为:

filterLove :: (Num a, Ord a) => [a] -> Int
filterLove xs = …

where xs is the list of numbers, and the part is an expression that should have Int as type.其中xs是数字列表,而部分是一个类型应该为Int的表达式。

We thus create a new list with only the elements of xs that are smaller than three with filter (<3) xs where filter :: (a -> Bool) -> [a] -> [a] takes a predicate and a list and produces a list with all the elements that satisfy the predicate.因此,我们使用filter (<3) xs创建一个仅包含小于 3 的xs元素的新列表,其中filter :: (a -> Bool) -> [a] -> [a]接受一个谓词和一个列表并生成一个包含满足谓词的所有元素的列表。 Then we can determine the length of that list with length (filter (<3) xs) where length :: [a] -> Int will determine the length of the list:然后我们可以使用length (filter (<3) xs)确定该列表的长度,其中length :: [a] -> Int将确定列表的长度:

filterLove :: (Num a, Ord a) => [a] -> Int
filterLove xs = length (filter (<3) xs)

we can remove the parameter xs with an η-reduction to:我们可以通过η-reduction删除参数xs为:

filterLove :: (Num a, Ord a) => [a] -> Int
filterLove = length . filter (<3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM