Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing every instance of the empty list from a list of list

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 :)

like image 455
user1353742 Avatar asked May 02 '12 13:05

user1353742


People also ask

How do you remove an empty list from a list?

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.

How do you remove every instance of an element in a 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.

Does list remove remove all occurrences?

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.


2 Answers

Filter is your friend.

filter (not . null) ...

alternatively, for those who like to filter manually,

[ x | x <- xs , not (null x) ]
like image 132
Don Stewart Avatar answered Dec 19 '22 23:12

Don Stewart


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.

like image 30
ДМИТРИЙ МАЛИКОВ Avatar answered Dec 19 '22 21:12

ДМИТРИЙ МАЛИКОВ