Reputation: 109
I'm trying to remove a number (if exists) from sublists, using Higher Order Functions.
removeAux :: Int -> [[Int]] -> (Int -> [Int] -> Bool) -> [[Int]]
removeAux num (l:ls) f
| f num l = delete num l -- ERROR in this line
|otherwise = removeAux num ls f
removeFromSublists :: Int -> [[Int]] -> [[Int]]
removeFromSublists _ [[]] = [[]]
removeFromSublists num ls = removeAux num ls (elem)
And it's suppose to work like this:
> l = [[0,1,2],[2,3]]
> removeFromSublists 1 l
[[0,2],[2,3]]
> removeFromSublists 0 l $ removeFromSubLists 1 l
[[2],[2,3]]
> removeFromSublists 2 l
[[0,1],[3]]
But I have two problems that I don't know how to solve. First it will not delete all the occurrences of the number and it should? And I can't understand why the code doesn't work? I keep geting the error:
Can someone help me please?
Upvotes: 2
Views: 114
Reputation: 1059
It could help to take a type-driven approach here. As in, you want to remove all occurrences of some element from a list of list of elements.
This is, "given an a
and a list of list of a's
([[a]]
) return a list of list of a
's ([[a]]
):
removeAll :: Eq a => a -> [[a]] -> [[a]]
removeAll v (list:listOfLists) = ???
We're removing all v
from each list
in the list (list:listOfLists)
. Another way of saying this is "for each list
in our listOfLists
filter out v
".
So, we want to perform the same action (filter) for-each value in a list. In Haskell, this translates to mapping the filter action over every list
in the listOfLists
.
removeAll :: Eq a => a -> [[a]] -> [[a]]
removeAll v xs = map (filter (/= v)) xs
Upvotes: 2