I'm new to Haskell and am just trying to write a simple list comprehension to remove every instance of the empty list from a list of lists, i.e entering this..
> remove ["abfwfw", "wfgwg", "", "dfw"]
will result in this output...
> ["abfwfw", "wfgwg", "dfw"]
thanks in advance :)
Short answer: You can remove all empty lists from a list of lists by using the list comprehension statement [x for x in list if x] to filter the list.
Use the remove() Function to Remove All the Instances of an Element From a List in Python. The remove() function only removes the first occurrence of the element. If you want to remove all the occurrence of an element using the remove() function, you can use a loop either for loop or while loop.
The remove() Method Removes the First Occurrence of an Item in a List. A thing to keep in mind when using the remove() method is that it will search for and will remove only the first instance of an item.
Filter is your friend.
filter (not . null) ...
alternatively, for those who like to filter manually,
[ x | x <- xs , not (null x) ]
Filter
would probably help you.
> filter (not . null) ["abfwfw", "wfgwg", "", "dfw"]
["abfwfw","wfgwg","dfw"]
What we are doing here is checking every element of a list whether its length equal to null or not with a predicate function (not . null) :: [a] -> Bool
.
There is a nice explanation of what filters are and how they work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With