I'm working on a function for a homework problem that counts the number of values in a list for which the values are greater than v1
and less than v2
. I've put something together that works but only in a specific case. When I try something else I get the error of
*** Exception: Non-exhaustive patterns in function countInRange
This function is supposed to call on getInRange
. getInRange
just returns values from a list that are greater than v1
and less than v2
. Here is what it looks like.
rangeHelper v1 v2 x | x > v1 && x < v2 = True
| otherwise = False
getInRange :: Ord a => a -> a -> [a] -> [a]
getInRange v1 v2 iL = filter(rangeHelper v1 v2) iL
count iL = sum (map (const 1) iL)
countInRange :: Ord a => a -> a -> [[a]] -> Int
countInRange v1 v2 [iL] = count ((getInRange v1 v2) iL)
If I were to call
countInRange 3 10 [[4,5,6]] -- works, prints 3
countInRange 3 10 [[1,2], [4,5,6]] -- error: non exhaustive patterns
Your countInRange
function only expects a list that contains one list. When you write countInRange v1 v2 [iL]
you only define it to match pattern when your list contains single element called iL
. You can also use count = length
You can fix this issue by defining it like this:
countInRange v1 v2 xs = sum (map (length.filter (rangeHelper v1 v2)) xs)
-- or
countInRange v1 v2 = sum.map (length.filter (rangeHelper v1 v2))