% Student exercise profile :- set_prolog_flag(occurs_check, error). % disallow cyclic terms :- set_prolog_stack(global, limit(8 000 000)). % limit term space (8Mb) :- set_prolog_stack(local, limit(2 000 000)). % limit environment space %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% algebraic expression simplification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %TASK: define single-step simplification rules (level 0) % for operators: + * - / ^ % - 0 and 1 % double % distributive % eval if both numbers simplify_0( 0*_, 0 ) :- !. simplify_0( 1*E, E ) :- !. simplify_0( E*E, E^2 ) :- !. simplify_0( A*B, C ) :- number(A), number(B), !, C is A*B. simplify_0( 0+E, E ) :- !. simplify_0( E+E, 2*E ) :- !. simplify_0( A+B, C ) :- number(A), number(B), !, C is A+B. simplify_0( 0-E, -1*E ) :- !. simplify_0( E-0, E ) :- !. simplify_0( E-E, 0 ) :- !. simplify_0( A-B, C ) :- number(A), number(B), !, C is A-B. simplify_0( _^0, 1 ) :- !. simplify_0( E^1, E ) :- !. simplify_0( A^B, C ) :- number(A), number(B), !, C is A**B. simplify_0( A*B + C*B, (A+C)*B ). simplify_0( E, E ). % TASK: define commutative rules for + and * (level 1) simplify_1(X*Y, Z) :- simplify_0(X*Y, Z), !. simplify_1(X*Y, Z) :- simplify_0(Y*X, Z). simplify_1(X+Y, Z) :- simplify_0(X+Y, Z), !. simplify_1(X+Y, Z) :- simplify_0(Y+X, Z). % catch-all rule at level 1 to call level 0 rules simplify_1(E, E1) :- simplify_0(E, E1). % TASK: define recursive simplification on expression structure (level 2) % on first argument simplify_2( E, E2 ) :- E =.. [ OP, A, B], simplify_2(A, A1), A \= A1, !, E1 =.. [ OP, A1, B], simplify_2(E1, E2). % on second argument simplify_2( E, E2 ) :- E =.. [ OP, A, B], simplify_2(B, B1), B \= B1, !, E1 =.. [ OP, A, B1], simplify_2(E1, E2). simplify_2(E, E1) :- simplify_1(E, E1), !. simplify_2(E, E). simplify(E, E1) :- simplify_2(E, E1). % on the whole /** Your example queries go here, e.g. ?- E = 0+(a*1)^0, simplify(E,S). */ %%% TASK: expand to other number types (float, complex) %%% TASK: simplify monomials, polynomials %%% TASK: expand to trigonometry, log, exp %%% TASK: expand to radicals %%% TASK: compute derivative (respect to an atom)