1% MISSING7
2
3:- module(simplify).
4
5getbug :-
6	writeln('\nCheck that you are in "module(simplify).", then'),
7	writeln('to start the program type "simplify(1 + a + b + a, S).".\n').
8
9test(S) :-
10	simplify(1 + a + b + a, S).
11
12
13bug :-
14	nl,
15	explanation.
16
17explanation :-
18writeln(' \n \
19There is a clause missing which matches 2nd parameter = []. \n \
20 \n \
21GOAL:	 simplify(1 + a + b + a, S). \n \
22CORRECT: S = 2 * a + b + 1 \n \
23BUGGY:   no (more) solutions. \n \
24').
25
26
27% ============================================================================
28% procedure for the simplification of summations.
29
30simplify(Init,Sexpr) :-
31	simplify2(Init,Int,Vars),
32	construct(Int,Vars,Sexpr).
33
34simplify2(L+A,I,Var) :-
35	!,
36	simplify2(L,I1,V1),
37	treat(A,I1,V1,I,Var).
38simplify2(A,I,V) :- treat(A,0,[],I,V).
39
40treat(A,I,V,I1,V) :- 					% A is an integer
41	integer(A),!,
42	I1 is I+A.
43treat(A,I,V,I,V1) :-					% A is a symbol
44	incr(A,V,V1).
45
46					% fix: add incr(A,[],[A/1]) :-!.
47incr(A,[A/N|L],[A/N1|L]) :-
48	!,N1 is N+1.
49incr(A,[S|L],[S|L1]) :-
50	incr(A,L,L1).
51
52construct(I,[],I) :-!.
53construct(0,L,P) :-!,construct1(L,P).
54construct(I,L,P+I) :- !,construct1(L,P).
55construct1([S],P) :-!,pri(S,P).
56construct1([S|L],L1+P) :- pri(S,P),construct1(L,L1).
57
58pri(A/1,A) :-!.
59pri(A/N,N*A).
60