File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22
33import redempt .crunch .data .CharTree ;
44import redempt .crunch .token .Constant ;
5+ import redempt .crunch .token .LazyVariable ;
56import redempt .crunch .token .Operator ;
67import redempt .crunch .token .Token ;
78import redempt .crunch .Variable ;
89
910import java .util .Locale ;
11+ import java .util .function .DoubleSupplier ;
1012import 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 ));
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments