Clone wiki

symja_android_library / examples / Package

Package example

In the following example we define a Symja "package" with user-defined rules which will be loaded on startup.

The package was named "TestPackage" and defines a new public function "Test" and a private predicate function "checkparam". The package could be written in a separate text file like this:

Package(
  "TestPackage", 
  { 
    "Test" 
  },{
    checkparam(i_,n_):=FreeQ(n,i),
    Test(x_, y_):={x,y} /; checkparam(x,y)
  } 
)

you can read in this textfile with a Java FileReader:

FileReader reader = new FileReader("/path-to-file/testpackage.txt");

To simplify the example we use a StringReader in this Java snippet, which reads the package text from the TEST_PACKAGE string:

import java.io.StringReader;
import org.matheclipse.core.basic.Config;
import org.matheclipse.core.eval.EvalEngine;
import org.matheclipse.core.eval.EvalUtilities;
import org.matheclipse.core.expression.F;
import org.matheclipse.core.interfaces.IExpr;
import org.matheclipse.parser.client.SyntaxError;
import org.matheclipse.parser.client.math.MathException;

public class PackageExample {
	private static final String TEST_PACKAGE = "Package(\n"
	        // define the package name "TestPackage"
			+ "  \"TestPackage\", \n"
			// define the public available symbol Test
			+ "  { \"Test\" }, \n" + "{\n"
			// define checkparam as package private function
			+ "checkparam(i_,n_):=FreeQ(n,i),\n"
			// Test() function is public available
			+ "Test(x_, y_):={x,y} /; checkparam(x,y)\n" + "} )\n";

	public static void main(String[] args) {
		try {
			// don't distinguish between lower- and uppercase identifiers
			Config.PARSER_USE_LOWERCASE_SYMBOLS = true;
			EvalEngine engine = new EvalEngine(true);
			// Windows c:\temp\...
			StringReader reader = new StringReader(TEST_PACKAGE);
			F.initSymbols(reader, null);
			EvalUtilities util = new EvalUtilities(engine, false, true);

			// evaluate the string directly
			IExpr result = util.evaluate("Test(a,b)");
			// print: {a,b}
			System.out.println(result.toString());

			// evaluate the last result ($ans contains "last answer")
			result = util.evaluate("$ans+cos(x)^2");
			// print: {Cos(x)^2+a,Cos(x)^2+b}
			System.out.println(result.toString());

			result = util.evaluate("Test(a,f(a))");
			// print: test(a,f(a))
			System.out.println(result.toString());

			result = util.evaluate("Test(f(a),a)");
			// print: {f(a),a}
			System.out.println(result.toString());

			result = util.evaluate("checkparam(a,b)");
			// checkparam is package private
			// print: checkparam(a,b)
			System.out.println(result.toString());
		} 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();
		}
	}
}

GIT: package examples:

Updated