Re: Prolog Programming for AI, problem 7.1
- From: Stefan Mandl <stefan.mandl@xxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 25 Nov 2006 00:55:05 +0100
Hi Lash,
I created this solution, but as I don't have
the book, I have no idea whether or not it is ok
with respect to your terms.
The main idea is to turn the sum into a list and
to use msort() on that, which separates numbers and
symbols nicely.
regards,
Stefan
----
simplify(X,S) :- to_list(X,LX), msort(LX,SX), split(SX,Numbers,Atoms),
add_list(Numbers, NumericSum),
group(Atoms,[],Symbols),
sum_symbols(Symbols,[], SymbolicSum),
(SymbolicSum = 0, S=NumericSum;
NumericSum = 0, S=SymbolicSum;
S=SymbolicSum+(NumericSum)).
to_list(A,[A]) :- number(A); atom(A).
to_list(A+B,L) :- to_list(A,LA), to_list(B,LB), append(LA,LB,L).
split([A],[A],[]) :- number(A),!.
split([A],[],[A]) :- atom(A),!.
split([A|R],[A|MoreNumbers],Atoms) :- number(A), !, split(R,MoreNumbers,Atoms).
split(A,[],A) :- !.
add_list([],0).
add_list([H|T],S) :- add_list(T,TS), S is H+TS.
group([],[],[]) :- !.
group([],[G|X],[[L,G]]) :- length([G|X],L),!.
group([H|T],[],R) :- !,group(T,[H],R).
group([H|T],[H|X],R) :- !,group(T,[H,H|X],R).
group([H|T],[O|X],[[L,O]|Rg]) :- O\=H, !,length([O|X],L),group(T,[H],Rg).
sum_symbols([],[],0).
sum_symbols([],R,R).
sum_symbols([[N,S]|T], SsF, Result) :- (N=1,NF=S; NF=N*S),
(SsF=[], sum_symbols(T,NF,Result);
sum_symbols(T,(SsF)+NF,Result)).
.
- Prev by Date: Re: Prolog Programming for AI, problem 7.1
- Next by Date: Random domain function
- Previous by thread: Re: Prolog Programming for AI, problem 7.1
- Next by thread: Random domain function
- Index(es):