Re: Prolog Programming for AI, problem 7.1
- From: "Greg Buchholz" <sleepingsquirrel@xxxxxxxxx>
- Date: 22 Aug 2006 09:54:00 -0700
Lash Rambo wrote:
I'm soldiering through "Prolog Programming for Artifical Intelligence" by
Bratko, but have run into a nasty exercise. It's 7.1, and reads:
Write a procedure 'simplify' to symbolically simplify summation
expressions with numbers and symbols (lower-case letters). Let the
procedure rearrange the expressions so that all the symbols precede
numbers. These are examples of its use:
?- simplify(1 + 1 + a, E).
E = a + 2
?- simplify(1 + a + 4 + 2 + b + c, E).
E = a + b + c + 7
?- simplify(3 + x + x, E).
E = 2*x + 3
The imperative solution sprung immediately to mind. You'd just read
through the expression, use a hash to map each symbol to its number of
occurrences, and tally the constants. At the end, stitch the contents of
the hash together with the tally. That's maybe 5 lines of Perl code.
% What about something like...
update(Key,[], [(Key, 1)]).
update(Key,[(Key, Value)|Dict], [(Key, Inc)|Dict]) :- Inc is Value + 1.
update(Key,[(Key1,Value)|Dict], [(Key1,Value)|Rest]) :-
Key \= Key1,
update(Key, Dict, Rest).
simp(X, (Sum, Vars), (New, Vars)) :- integer(X), New is Sum+X.
simp(X, (Sum, Vars), (Sum, NewVars)) :- atom(X),
update(X,Vars,NewVars).
simp(X+Y, SumAndVars, NewSumAndVars) :-
simp(X, SumAndVars , Tmp),
simp(Y,Tmp,NewSumAndVars).
pretty((Sum, []), Sum).
pretty((Sum, [(Var, Occurs)|Rest]), Occurs * Var + Tmp) :-
pretty((Sum,Rest), Tmp).
simplify(Exp,Out) :- simp(Exp,(0,[]), Ugly), pretty(Ugly,Out).
.
- References:
- Prolog Programming for AI, problem 7.1
- From: Lash Rambo
- Prolog Programming for AI, problem 7.1
- Prev by Date: Re: Prolog Programming for AI, problem 7.1
- Next by Date: Re: Prolog Programming for AI, problem 7.1
- Previous by thread: Re: Prolog Programming for AI, problem 7.1
- Next by thread: Re: Prolog Programming for AI, problem 7.1
- Index(es):
Relevant Pages
|