Home > Enterprise >  Returning number of occurences with condition from list in Haskell
Returning number of occurences with condition from list in Haskell

Time:10-18

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 doestn work.I cant figure out how would i do it. Thanks for help.

CodePudding user response:

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 = length (filter (<3) xs)

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

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