Prolog programming…

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.

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.

This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Prolog programming…

  1. Dawid says:

    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)

  2. Vivek says:

    Thank you, Dawid. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

nine + 1 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>