====== Evaluator ====== {{tag>math arithmetic}} ===== Description ===== Evaluator which traverses the structure of the evaluated term, where variables are represented by Prolog atoms like a, b or c, so they do not correspond to Prolog variables. **Source**: Guide to Prolog Programming (on-line tutorial) ===== Download ===== Program source code: {{evaluator.pl}} ===== Listing ===== eval(A+B,CV):-eval(A,AV),eval(B,BV),CV is AV+BV. eval(A-B,CV):-eval(A,AV),eval(B,BV),CV is AV-BV. eval(A*B,CV):-eval(A,AV),eval(B,BV),CV is AV*BV. eval(Num,Num):-number(Num). eval_v(A+B,CV,Vars):-eval_v(A,AV,Vars),eval_v(B,BV,Vars),CV is AV+BV. eval_v(A-B,CV,Vars):-eval_v(A,AV,Vars),eval_v(B,BV,Vars),CV is AV-BV. eval_v(A*B,CV,Vars):-eval_v(A,AV,Vars),eval_v(B,BV,Vars),CV is AV*BV. eval_v(Num,Num,Vars):-number(Num). eval_v(Var,Value,Vars):-atom(Var),member(Var/Value,Vars). % Try ?-eval_v(2*a+b,Val,[a/1,b/5]) to test the above program. ===== Comments =====