I was hoping to find a better way to solve a problem I've encountered in Haskell.
Given a list and a condition create a new list with only elements which satisfy the condition. Below is a solution I used. Is there a better alternative which doesn't involve maybes?
eg :: (Eq a, Num a) => (a -> Bool) -> [a] -> [a]
eg cond i = catMaybes (map (\x-> if cond x then Just x else Nothing) i)
CodePudding user response:
Your eg is equivalent to filter :: (a -> Bool) -> [a] -> [a]. Indeed, you can filter with:
filter (\x -> some_condition x) my_list
If some_condition is for example a simple a -> Bool function, this is equivalent to:
filter some_condition my_list
Neither your implementation of eg nor the one with filter require the Eq a and Num a type constraints by the way: one can simply use guards or pattern match on the outcome of cond x.
filter is implemented with explicit recursion [src]:
filter :: (a -> Bool) -> [a] -> [a] filter _pred [] = [] filter pred (x:xs) | pred x = x : filter pred xs | otherwise = filter pred xs
Here for an empty list it thus returns the empty list, and when the list is not empty, it will only prepend x if pred x is satisfied.
