Search code examples
prolog

Delete empty lists from lists of lists in Prolog


For instance, I have a list:

[ [], [], [], [1], [2,2], [3] ]

How can I delete empty elements from this list?


Solution

  • We can make a predicate that succeeds for empty lists:

    empty([]).
    

    Then we can make use of exclude/3 [swi-doc] to filter out elements for which the predicate succeeds:

    exclude(empty, [[], [], [], [1], [2,2], [3]], L).
    

    This thus gives us:

    ?- exclude(empty, [[], [], [], [1], [2,2], [3]], L).
    L = [[1], [2, 2], [3]].