Evaluator

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

pl/prolog/pllib/evaluator.txt · ostatnio zmienione: 2017/07/17 08:08 (edycja zewnętrzna)
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0