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 and flattens it.
?- flatten([a,[b,c],[[d],[],[e]]],Xs).
Xs = [a,b,c,d,e]. % expected result
The function takes out the inner structures of the list.
This is what I have so far:
flatten2([],[]).
flatten2([Atom|ListTail],[Atom|RetList]) :-
atom(Atom), flatten2(ListTail,RetList).
flatten2([List|ListTail],RetList) :-
flatten2(List,RetList).
Now, this works when I call:
?- flatten2([a,[b,c],[[d],[],[e]]], R).
R = [a,b,c,d,e]. % works as expected!
But when I call to see if a list that I input is already flattened, is returns false instead of true:
?- flatten2([a,[b,c],[[d],[],[e]]], [a,b,c,d,e]).
false. % BAD result!
Why does it work on one hand, but not the other? I feel like I'm missing something very simple.
?- flatten([X], Ls).yield? You may think that it "obviously" should yieldLs = [X]. However, you then have the following problem:?- flatten([X], Ls), Ls = [X], X = [a].succeeds, but if we simply exchange the goals by commutativity of conjunction, we get:?- Ls = [X], X = [a], flatten([X], Ls)., or more compactly,?- flatten([[a]], [[a]])., which of course must fail because[[a]]is not a flat list. So, which is it? Fail or succeed? This shows that this is really not a nice relation at all. - matappend/2. It limits this relation to a more meaningful and often also more practically useful version. - mat