package it.cavallium.warppi.math.rules.dsl.patterns;

import it.cavallium.warppi.math.Function;
import it.cavallium.warppi.math.MathContext;
import it.cavallium.warppi.math.rules.dsl.Pattern;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * Matches and generates any function as a named sub-function.
 */
public class SubFunctionPattern implements Pattern {
	private final String name;

	public SubFunctionPattern(final String name) {
		this.name = name;
	}

	@Override
	public boolean match(final Function function, final Map<String, Function> subFunctions) {
		final Function existingSubFunction = subFunctions.putIfAbsent(name, function);
		return existingSubFunction == null || existingSubFunction.equals(function);
	}

	@Override
	public Function replace(final MathContext mathContext, final Map<String, Function> subFunctions) {
		return subFunctions.get(name);
	}

	@Override
	public Stream<SubFunctionPattern> getSubFunctions() {
		return Stream.of(this);
	}

	@Override
	public boolean equals(final Object o) {
		if (!(o instanceof SubFunctionPattern)) {
			return false;
		}
		final SubFunctionPattern other = (SubFunctionPattern) o;
		return name.equals(other.name);
	}

	@Override
	public int hashCode() {
		return Objects.hash(name);
	}
}

@@ -334,16 +334,462 @@
 nction.%0A
+ * %3Cp%3E%0A * For a %3Ccode%3EFunction%3C/code%3E to match a %3Ccode%3EPattern%3C/code%3E, all %3Ccode%3ESubFunctionPattern%3C/code%3Es with the same name%0A * must capture equal sub-functions (according to the %3Ccode%3Eequals%3C/code%3E method).%0A * For example, the %3Ccode%3Ex + x%3C/code%3E %3Ccode%3EPattern%3C/code%3E matches %3Ccode%3E2 + 2%3C/code%3E and %3Ccode%3E2 + 2.0%3C/code%3E,%0A * but not %3Ccode%3E2 + 3%3C/code%3E, while the %3Ccode%3Ex + y%3C/code%3E %3Ccode%3EPattern%3C/code%3E matches all three %3Ccode%3EFunction%3C/code%3Es.%0A
  */%0Apubl

Improve SubFunctionPattern documentation