% % Extended safeIs example presented 26 February 1996. % % Also includes code to handle logical expressions. % % Allows expressions of the form: % % X safeIs Y safeIs 1+2+a. % % % Define operators so that remainder of file can be read. % :-op(700, xfy, safeIs). :-op(400, yfx, and). :-op(500, yfx, or). % % Basic procedure. % member([H|_],H). member([_|T],H):-member(T,H). % % Categorize operators. % % Binary operators that can be evaluated by "is". binOp(X,builtIn,both_numeric):- member(['+','-','*','/'],X). % Binary operators handled by eval clauses. binOp(X,eval,one_logical):- member([and,or],X). % Assignment operator. binOp(safeIs,eval,right_unbound). % % Check precondition. % precondition(both_numeric,Val1,Val2):- number(Val1), number(Val2). precondition(one_logical,Val1,Val2):- ( truthValue(Val1) ; truthValue(Val2) ). precondition(right_unbound,Val1,Val2):- var(Val1). % % Define truth values. % truthValue(true). truthValue(false). % % safeIs clauses. % safeIs(Value,Value):-( atomic(Value) ; var(Value) ). safeIs(Value,Expr):- Expr =.. [Operator,Op1,Op2], binOp(Operator,Type,Precond), safeIs(Val1,Op1), safeIs(Val2,Op2), Expr2 =.. [Operator,Val1,Val2], ( precondition(Precond,Val1,Val2), ( Type = builtIn, Value is Expr2 ; Type = eval, eval(Value,Expr2) ) ; Value=Expr2 ),!. % % Evaluation clauses. % eval(Value,Value safeIs Value):-!. eval(true, true and true ). eval(false, V1 and V2 ):- ( V1 = false ; V2 = false ). eval(false, false or false ). eval(true, V1 or V2 ):- ( V1 = true ; V2 = true ). % This comment intentionally left blank.