简体   繁体   中英

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

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. 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 :: (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.

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. 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:

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

we can remove the parameter xs with an η-reduction to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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