I need to display the number of elements whose successor is greater in a list. For example, in the list [3,7,2,1,9] my function should return 2 because 7 is greater than 3 and 9 is greater than 1.
In order to do that,I was thinking to use the filter function:
greaterElems :: Ord a => [a] -> Int
greaterElems [] = 0
greaterElems [x] = 0
greaterElems (x:xs) = length (filter (< head xs) (x:xs))
However, this does not work as expected: it seems that Haskell always considers the second element of the list, as if "head xs" is calculated only once, but this does not seem normal to me since Haskell is lazy.
What am I missing and how could I fix my code in order to achieve my goal?
You can make use of zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
where we pass the list, and its tail. Indeed:
sucGreater :: Ord a => [a] -> [Bool]
sucGreater x = zipWith (<) x (tail x)
or as @RobinZigmond says, we can omit tail, and use drop
:
sucGreater :: Ord a => [a] -> [Bool]
sucGreater x = zipWith (<) x (drop 1 x)
For the given sample list, this gives us:
Prelude> sucGreater [3,7,2,1,9]
[True,False,False,True]
I leave it as an exercise to the count the number of True
s in that list.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments