Wiki

Clone wiki

symja_android_library / examples / StepListener

Evaluation steps listener example

Include the symja-YYYY-MM-DD.jar and the log4j-1.2.11.jar libraries in your classpath and start coding using parsed input strings or the internal object hierarchy.

Here is an example where a StepListener is use to log the partial steps to evaluate an expression:

Example:

import org.matheclipse.core.eval.EvalEngine;
import org.matheclipse.core.eval.ExprEvaluator;
import org.matheclipse.core.interfaces.AbstractEvalStepListener;
import org.matheclipse.core.interfaces.IExpr;
import org.matheclipse.parser.client.SyntaxError;
import org.matheclipse.parser.client.math.MathException;

public class StepListenerExample {
	private static class StepListener extends AbstractEvalStepListener {
		/**
		 * Listens to the evaluation step in the evaluation engine.
		 */
		@Override
		public void add(IExpr inputExpr, IExpr resultExpr, int recursionDepth, long iterationCounter, String hint) {
			System.out.println("Depth " + recursionDepth + " Iteration " + iterationCounter + ": " + inputExpr.toString() + " ==> "
					+ resultExpr.toString());
		}
	}

	public static void main(String[] args) {
		try {
			ExprEvaluator util = new ExprEvaluator( );
			EvalEngine engine = util.getEvalEngine();
			engine.setStepListener(new StepListener());
			IExpr result = util.evaluate("D(Sin(x),x)");
			System.out.println("Result: " + result.toString());
			// disable trace mode if the step listener isn't necessary anymore
			engine.setTraceMode(false);
		} catch (SyntaxError e) {
			// catch Symja parser errors here
			System.out.println(e.getMessage());
		} catch (MathException me) {
			// catch Symja math errors here
			System.out.println(me.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Updated