listprologdcg

Get elements from list of lists


is it possible to get all elements from list of lists in Prolog?

Something like: We have getElements([[[a,b,[c]],d,e],f,g,[h,[i,j]]],S) and the result is: S = [a,b,c,d,e,f,g,h,i,j] ...

Thanks for help.


Solution

  • In SWI-Prolog (and maybe others), you can use flatten/2:

    ?- flatten([[[a,b,[c]],d,e],f,g,[h,[i,j]]], S).
    S = [a, b, c, d, e, f, g, h, i|...].
    

    Note that the SWI-Prolog manual page for flatten/2 includes the following statement:

    Ending up needing flatten/3 often indicates, like append/3 for appending two lists, a bad design.

    However, the page doesn't say whether there is another native predicate to replace it.

    I'm sure a better answer will be supplied.