Reputation: 163
I have to write a code that that returns all numbers in the input list within the range given by the first two arguments.
I tried to set the head of the list as the lowest input.
inRange :: Int -> Int -> [Int] -> [Int]
inRange lo hi xs = (x == lo : xs == hi)
I expect having a result such as
inRange 5 10 [1..15] == [5,6,7,8,9,10]
, but since I cannot write the code the modular is not loading.
Upvotes: 3
Views: 294
Reputation: 16224
With pattern matching you can do this like:
inRange :: Int -> Int -> [Int] -> [Int]
inRange _ _ [] = []
inRange lo hi (x:xs)
| lo > hi = []
| lo <= x && x <= hi = x : (inRange lo hi xs)
| x > hi = []
| otherwise = inRange lo hi xs
Upvotes: 0
Reputation: 476493
We can filter :: (a -> Bool) -> [a] -> [a]
the list, such that it only retains values x
for which lo <= x && x <= hi
holds:
inRange :: Ord a => a -> a -> [a] -> [a]
inRange lo hi = filter (\x -> lo <= x && x <= hi)
We can optimize this for the case where lo > hi
, since then, no element can satisfy the condition, and hence we can return an empty list.
inRange :: Ord a => a -> a -> [a] -> [a]
inRange lo hi
| lo > hi = []
| otherwise = filter (\x -> lo <= x && x <= hi)
Upvotes: 4
Reputation: 67467
with list comprehensions
> inRange lo hi xs = [ x | x <- xs, x>=lo && x<=hi ]
> inRange 5 10 [1..15]
[5,6,7,8,9,10]
Upvotes: 1