Re: Prolog Programming for AI, problem 7.1




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).

.



Relevant Pages

  • Re: Calculating Time Sheet
    ... formatting them that will return a numeric data type rather than a string ... so you can then use the values in arithmetical expressions: ... If so you can't sum the values of course you'd have to add the values ... these daily totals, or alas convert them so they can be totalled. ...
    (microsoft.public.access.gettingstarted)
  • Re: Sum of calculated fields
    ... leading you astray. ... >unnessasary parts of the expressions, cleaned up, and now it definately works ... >Marshall Barton wrote: ... >>that Sum is doing in there. ...
    (microsoft.public.access.formscoding)
  • Re: Sum of calculated fields
    ... expressions I used so that it may make better sense, ... This database is used to calculate normal working hours and overtime hours, ... I have managed to get the sum() of Total hours to display in the report ...
    (microsoft.public.access.formscoding)
  • Re: Ultimate debunking of Cantors Theory
    ... >>> expressions like ... >> Where do I find that expression in a set theory book? ... The partial sums can be determined, but the sum cannot be determined at ... only value with which you can extend the domain. ...
    (sci.math)