Just wrote a prolog program to flatten a list. Even though we had done the program in Lisp and Python it was a wonderful experience doing the same in Prolog. Spend about an hour for the program. Really excited at this point… The following is the program.
app([], Y, Y).
app([H|X], Y, [H|Z]) :- app(X, Y ,Z).
flat([], []).
flat([H|T],Y) :- flat(H,K), flat(T,L), app(K,L,Y), !.
flat(H, [H]) :- not(H = [K]).
I am using a gprolog interpreter. The ‘not’ function is not working in my system (any idea why?) and hence wrote my own not function.
my_not(X) :- X, !, fail.
my_not(_).
For those who dont know what flatten is:
a = [ 1, [ 2, 3 ], [ [ 4 ], 5 ], 6 ]
flat(a) = [1, 2, 3, 4, 5, 6]
I am sure that this is not the best solution. Let me know if you got a much better solutionor any other solution.
Because in gprolog the ‘not’ clause is represented by \+ for example to check if item is not a member of list, you should write \+member(item,list)
Thank you, Dawid.