I want to write a procedure simplify (E, E1) which is able to simplify expressions.
I have only one operation +, and symbolic and numeric operands. Examples of this procedure:
simplify(a + 1 + b + 5, E) ------> E = a + b + 6
simplify(1 + b + 9 + a + 5 + c, E) ------> E = b + a + c + 15
All the characters we shift to the beginning. Then we calculate the sum of numerical operands and appends it to the end of the expression.
How to write a procedure?
Well, this is obviously a homework question, but here's an SWI Prolog program anyway:
:- op(500, xfy, user:(+)).
simplify(Expr, Simplified) :-
split(Expr, Syms0, Nums0),
sumlist(Nums0, Nums),
append(Syms0, [Nums], Syms),
unparse(Syms, Simplified).
split(X+Y, [X|Syms], Nums) :- atom(X), split(Y, Syms, Nums).
split(X+Y, Syms, [X|Nums]) :- integer(X), split(Y, Syms, Nums).
split(X, [X], []) :- atom(X).
split(X, [], [X]) :- integer(X).
unparse([X], X).
unparse([X|Xs], X+Y) :- unparse(Xs, Y).
:- simplify(a+1+b+5, a+b+6).
:- simplify(1+b+9+a+5+c, b+a+c+15).