Skip to content

Commit

Permalink
Add lazy variables
Browse files Browse the repository at this point in the history
  • Loading branch information
boxbeam committed Feb 2, 2022
1 parent 90e089e commit a7cd67f
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/redempt/crunch/functional/EvaluationEnvironment.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import redempt.crunch.data.CharTree;
import redempt.crunch.token.Constant;
import redempt.crunch.token.LazyVariable;
import redempt.crunch.token.Operator;
import redempt.crunch.token.Token;
import redempt.crunch.Variable;

import java.util.Locale;
import java.util.function.DoubleSupplier;
import java.util.function.ToDoubleFunction;

/**
Expand Down Expand Up @@ -57,6 +59,15 @@ public void addFunctions(Function... functions) {
}
}

/**
* Adds a lazily-evaluated variable that will not need to be passed with the variable values
* @param name The name of the lazy variable
* @param supply A function to supply the value of the variable when needed
*/
public void addLazyVariable(String name, DoubleSupplier supply) {
namedTokens.set(name, new LazyVariable(name, supply));
}

public void setVariableNames(String... names) {
for (int i = 0; i < names.length; i++) {
namedTokens.set(names[i], new Variable(null, i));
Expand Down
35 changes: 35 additions & 0 deletions src/redempt/crunch/token/LazyVariable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package redempt.crunch.token;

import java.util.function.DoubleSupplier;

public class LazyVariable implements Value {

private String name;
private DoubleSupplier supplier;

public LazyVariable(String name, DoubleSupplier supplier) {
this.name = name;
this.supplier = supplier;
}

@Override
public TokenType getType() {
return TokenType.LITERAL_VALUE;
}

@Override
public double getValue() {
return supplier.getAsDouble();
}

@Override
public Value getClone() {
return this;
}

@Override
public String toString() {
return name;
}

}
10 changes: 9 additions & 1 deletion test/redempt/crunch/test/CrunchTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,17 @@ public void implicitMultiplicationTest() {
}

@Test
public void rootingTest(){
public void rootingTest() {
assertEquals(2, Crunch.evaluateExpression("sqrt(4)"), "Square Rooting");
assertEquals(2, Crunch.evaluateExpression("cbrt(8)"), "Cube Rooting");
}

@Test
public void lazyVariableTest() {
EvaluationEnvironment env = new EvaluationEnvironment();
env.addLazyVariable("x", () -> 2);
env.addLazyVariable("y", () -> 7);
assertEquals(14, Crunch.compileExpression("xy", env).evaluate());
}

}

0 comments on commit a7cd67f

Please sign in to comment.