Wiki

Clone wiki

mikulas / mexpr / custom-function

Custom Java Function

New functions can be added as user wishes. Each function is defined in separate java class and must implement Supplier<Double> interface.

Class must have the @FunctionalSupplier annotation and the name and description property of the annotation must be populated.

Class may have multiple constructors with any number of parameters but all must be of type Supplier<Double>. Parser will use these constructors with the right parameters.

Function must be on classpath and will be automatically instancied which it can be checked by Registrar.getInstance().getFuncClassInfos()

See class SinSupplier.

import java.util.function.Supplier;
import cz.jmare.mexpr.arit.FunctionalSupplier;

@FunctionalSupplier(name = "sin", description = "Returns the trigonometric sine of an angle. Syntax: sin(x)")
public class SinSupplier implements Supplier<Double> {
    private Supplier<Double> supplier;

    public SinSupplier(Supplier<Double> supplier) {
        this.supplier = supplier;
    }

    @Override
    public Double get() {
        return Math.sin(supplier.get());
    }
}

Or see class LogSupplier which has multiple parameters variants:

@FunctionalSupplier(name = "log", description = "Returns the natural logarithm (base e) or logarithm with custom base of a double value. Syntax: log(x) or log(x, base)")
public class LogSupplier implements Supplier<Double> {
    private Supplier<Double> supplier;

    private Supplier<Double> base;

    public LogSupplier(Supplier<Double> supplier) {
        this.supplier = supplier;
    }

    public LogSupplier(Supplier<Double> supplier, Supplier<Double> base) {
        this.supplier = supplier;
        this.base = base;
    }

    @Override
    public Double get() {
        if (base != null) {
            return Math.log(supplier.get()) / Math.log(base.get());
        }
        return (double) Math.log(supplier.get());
    }
}

Updated