Re: Prolog Programming for AI, problem 7.1



On Sun, 20 Aug 2006 04:03:48 +0000, Lash Rambo wrote:

So, is there a simple, clever solution to this problem in Prolog? I'm
thinking a dozen lines, max. No CFGs, no term decomposition (beyond
stuff like X+Y), no wacky 3rd party libraries, etc.

How about this one:

simplify(ExprIn,ExprOut) :-
plus2list(ExprIn,ListIn),
sublist(integer,ListIn,Ints),
sumlist(Ints,I),
sublist(atom,ListIn,AllAtoms),
sort(AllAtoms,Atoms),
findall(Term,( member(A,Atoms),
findall(a,member(A,ListIn),AllAs),
length(AllAs,N),
(N == 1 -> Term = A ; Term = N*A)),
L),
(I == 0 -> plus2list(ExprOut,L) ; plus2list(ExprOut,[I|L])).

plus2list((A+B),[B|R]) :- plus2list(A,R).
plus2list(A,[A]) :- A \= (_+_).


Too long ? Too wacky ?

Cheers

Bart Demoen
.