package gve.calc.formula;

import java.util.Vector;
import java.util.Hashtable;

@version 4 nov 1999 @author Geert Vernaeve This evaluator is able to undo multiple redefinitions of the same variable.
public class MultiEvaluator implements Evaluator { private Vector identifiers,values; private Hashtable functions = new Hashtable(); public MultiEvaluator() { identifiers = new Vector(); values = new Vector(); } public Object clone() { MultiEvaluator result = new MultiEvaluator(); result.identifiers = (Vector)identifiers.clone(); result.values = (Vector)values.clone(); result.functions = (Hashtable)functions.clone(); return result; } public void defineVariable(String name,Part value) { identifiers.addElement(name); values.addElement(value); } public java.util.Enumeration variables() { return identifiers.elements(); }
Each undefVariable() annihilates exactly one defineVariable() call. So if you defined a variable multiple times, you have to call undefVariable() exactly as many times as you defineVariable()d it.
public void undefVariable(String name) { int i; for (i = values.size(); i-->0; ) if (name.equals(identifiers.elementAt(i))) { identifiers.removeElementAt(i); values.removeElementAt(i); return; } } /* Returns the value of a previously defined identifier (using * defineVariable()). */ public Part getValue(String identifier) { Double d; try { d = new Double(identifier); } catch (NumberFormatException exc) { for (int i = values.size(); i-->0; ) if (identifier.equals(identifiers.elementAt(i))) { Part result = (Part)values.elementAt(i); if (!(result instanceof Identifier)) return result; String str = ((Identifier)result).getString(); try { return new Real(new Double(str).doubleValue()); } catch (NumberFormatException ex) { return result; } } return null; } return new Real(d.doubleValue()); }
Change the value of an existing variable. If the variable doesn't exist, this call is equivalent to defineVariable().
public void setValue(String name,Part value) { for (int i = values.size(); i-->0; ) if (name.equals(identifiers.elementAt(i))) { // Modify values.setElementAt(value,i); return; } // Create defineVariable(name,value); } public void dump() { for (int i = values.size()-1; i>=0; i--) { System.out.println("---key"+identifiers.elementAt(i)); Object val = values.elementAt(i); if (val instanceof Part) ((Part)val).dump(1); else System.out.println(val); } } public Part call(String funcname,Part args) { Function f = (Function)functions.get(funcname); if (f == null) return null; return f.call(funcname,args,this); } public void setFunction(String funcname,Function f) { functions.put(funcname,f); } public boolean isFunction(String funcname) { return (functions.get(funcname) != null); } }