Skip to content

Commit a7cd67f

Browse files
committed
Add lazy variables
1 parent 90e089e commit a7cd67f

3 files changed

Lines changed: 55 additions & 1 deletion

File tree

src/redempt/crunch/functional/EvaluationEnvironment.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22

33
import redempt.crunch.data.CharTree;
44
import redempt.crunch.token.Constant;
5+
import redempt.crunch.token.LazyVariable;
56
import redempt.crunch.token.Operator;
67
import redempt.crunch.token.Token;
78
import redempt.crunch.Variable;
89

910
import java.util.Locale;
11+
import java.util.function.DoubleSupplier;
1012
import java.util.function.ToDoubleFunction;
1113

1214
/**
@@ -57,6 +59,15 @@ public void addFunctions(Function... functions) {
5759
}
5860
}
5961

62+
/**
63+
* Adds a lazily-evaluated variable that will not need to be passed with the variable values
64+
* @param name The name of the lazy variable
65+
* @param supply A function to supply the value of the variable when needed
66+
*/
67+
public void addLazyVariable(String name, DoubleSupplier supply) {
68+
namedTokens.set(name, new LazyVariable(name, supply));
69+
}
70+
6071
public void setVariableNames(String... names) {
6172
for (int i = 0; i < names.length; i++) {
6273
namedTokens.set(names[i], new Variable(null, i));
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package redempt.crunch.token;
2+
3+
import java.util.function.DoubleSupplier;
4+
5+
public class LazyVariable implements Value {
6+
7+
private String name;
8+
private DoubleSupplier supplier;
9+
10+
public LazyVariable(String name, DoubleSupplier supplier) {
11+
this.name = name;
12+
this.supplier = supplier;
13+
}
14+
15+
@Override
16+
public TokenType getType() {
17+
return TokenType.LITERAL_VALUE;
18+
}
19+
20+
@Override
21+
public double getValue() {
22+
return supplier.getAsDouble();
23+
}
24+
25+
@Override
26+
public Value getClone() {
27+
return this;
28+
}
29+
30+
@Override
31+
public String toString() {
32+
return name;
33+
}
34+
35+
}

test/redempt/crunch/test/CrunchTest.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,9 +102,17 @@ public void implicitMultiplicationTest() {
102102
}
103103

104104
@Test
105-
public void rootingTest(){
105+
public void rootingTest() {
106106
assertEquals(2, Crunch.evaluateExpression("sqrt(4)"), "Square Rooting");
107107
assertEquals(2, Crunch.evaluateExpression("cbrt(8)"), "Cube Rooting");
108108
}
109109

110+
@Test
111+
public void lazyVariableTest() {
112+
EvaluationEnvironment env = new EvaluationEnvironment();
113+
env.addLazyVariable("x", () -> 2);
114+
env.addLazyVariable("y", () -> 7);
115+
assertEquals(14, Crunch.compileExpression("xy", env).evaluate());
116+
}
117+
110118
}

0 commit comments

Comments
 (0)