I\'ve only been working with Prolog for a couple days. I understand some things but this is really confusing me.
I\'m suppose to write a function that takes a list
I didn't find a solution using findall
, so I'll add it. (it will work if the list is ground)
First, we define how to test for a list:
list(X) :- var(X), !, fail.
list([]).
list([_|_]).
and the transitive closure of member
, we call it member*
:
'member*'(X, Y) :- member(X, Y).
'member*'(X, Y) :- member(Z, Y), 'member*'(X, Z).
The flattened list is all the solution of member*
which are not lists:
flatten(X, Y) :- findall(Z, ('member*'(Z, X), \+ list(Z)), Y).
Example:
?- flatten([[4],[[5,6],[7,[8],[9,[10,11]]]]],Y).
Y = [4, 5, 6, 7, 8, 9, 10, 11].