uCalc SDK Interactive Examples
Basic round-trip from an item back to its parent instance.
ID: 680
See: uCalc = [uCalc]
using uCalcSoftware;
var uc = new uCalc();
var myInstance = new uCalc();
// Define a variable and get its Item object
var v = myInstance.DefineVariable("v = 10");
// Use the item to get back to its parent uCalc instance
var parentInstance = v.uCalc;
// Perform another evaluation in the same context
Console.WriteLine(parentInstance.EvalStr("v + 5"));
15 using uCalcSoftware; var uc = new uCalc(); var myInstance = new uCalc(); // Define a variable and get its Item object var v = myInstance.DefineVariable("v = 10"); // Use the item to get back to its parent uCalc instance var parentInstance = v.uCalc; // Perform another evaluation in the same context Console.WriteLine(parentInstance.EvalStr("v + 5"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uCalc myInstance;
// Define a variable and get its Item object
auto v = myInstance.DefineVariable("v = 10");
// Use the item to get back to its parent uCalc instance
auto parentInstance = v.uCalc();
// Perform another evaluation in the same context
cout << parentInstance.EvalStr("v + 5") << endl;
}
15 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uCalc myInstance; // Define a variable and get its Item object auto v = myInstance.DefineVariable("v = 10"); // Use the item to get back to its parent uCalc instance auto parentInstance = v.uCalc(); // Perform another evaluation in the same context cout << parentInstance.EvalStr("v + 5") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim myInstance As New uCalc()
'// Define a variable and get its Item object
Dim v = myInstance.DefineVariable("v = 10")
'// Use the item to get back to its parent uCalc instance
Dim parentInstance = v.uCalc
'// Perform another evaluation in the same context
Console.WriteLine(parentInstance.EvalStr("v + 5"))
End Sub
End Module
15 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim myInstance As New uCalc() '// Define a variable and get its Item object Dim v = myInstance.DefineVariable("v = 10") '// Use the item to get back to its parent uCalc instance Dim parentInstance = v.uCalc '// Perform another evaluation in the same context Console.WriteLine(parentInstance.EvalStr("v + 5")) End Sub End Module
Binding a uCalc array to a host array
ID: 1466
See: DefineVariable
using uCalcSoftware;
var uc = new uCalc();
double[] myHostArray = new double[] { 5, 10, 15, 20 };
// Pin the array
var myHostArrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostArray, System.Runtime.InteropServices.GCHandleType.Pinned);
// Bind the uCalc variable to the pinned memory address
uc.DefineVariable("MyArray[]", myHostArrayHandle.AddrOfPinnedObject());
// The uCalc array values come from the host array
Console.WriteLine(uc.Eval("MyArray[0]"));
Console.WriteLine(uc.Eval("MyArray[1]"));
Console.WriteLine(uc.Eval("MyArray[2]"));
Console.WriteLine(uc.Eval("MyArray[3]"));
Console.WriteLine("");
// Changing the uCalc array updates the pinned array
uc.Eval("MyArray[0] = 10; MyArray[1] = 20; MyArray[2] = 30; MyArray[3] = 40; ");
// The changes the uCalc array are reflected in the host array
Console.WriteLine(myHostArray[0]);
Console.WriteLine(myHostArray[1]);
Console.WriteLine(myHostArray[2]);
Console.WriteLine(myHostArray[3]);
Console.WriteLine("");
// One more round trip
myHostArray[0] = 10;
myHostArray[1] = 11;
myHostArray[2] = 12;
myHostArray[3] = 13;
Console.WriteLine(uc.Eval("MyArray[0]"));
Console.WriteLine(uc.Eval("MyArray[1]"));
Console.WriteLine(uc.Eval("MyArray[2]"));
Console.WriteLine(uc.Eval("MyArray[3]"));
// Don't forget to free the handle when you are completely done with the parser instance
myHostArrayHandle.Free();
5
10
15
20
10
20
30
40
10
11
12
13 using uCalcSoftware; var uc = new uCalc(); double[] myHostArray = new double[] { 5, 10, 15, 20 }; // Pin the array var myHostArrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostArray, System.Runtime.InteropServices.GCHandleType.Pinned); // Bind the uCalc variable to the pinned memory address uc.DefineVariable("MyArray[]", myHostArrayHandle.AddrOfPinnedObject()); // The uCalc array values come from the host array Console.WriteLine(uc.Eval("MyArray[0]")); Console.WriteLine(uc.Eval("MyArray[1]")); Console.WriteLine(uc.Eval("MyArray[2]")); Console.WriteLine(uc.Eval("MyArray[3]")); Console.WriteLine(""); // Changing the uCalc array updates the pinned array uc.Eval("MyArray[0] = 10; MyArray[1] = 20; MyArray[2] = 30; MyArray[3] = 40; "); // The changes the uCalc array are reflected in the host array Console.WriteLine(myHostArray[0]); Console.WriteLine(myHostArray[1]); Console.WriteLine(myHostArray[2]); Console.WriteLine(myHostArray[3]); Console.WriteLine(""); // One more round trip myHostArray[0] = 10; myHostArray[1] = 11; myHostArray[2] = 12; myHostArray[3] = 13; Console.WriteLine(uc.Eval("MyArray[0]")); Console.WriteLine(uc.Eval("MyArray[1]")); Console.WriteLine(uc.Eval("MyArray[2]")); Console.WriteLine(uc.Eval("MyArray[3]")); // Don't forget to free the handle when you are completely done with the parser instance myHostArrayHandle.Free();
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
double myHostArray[] = { 5, 10, 15, 20 };
uc.DefineVariable("MyArray[]", &myHostArray);
// The uCalc array values come from the host array
cout << uc.Eval("MyArray[0]") << endl;
cout << uc.Eval("MyArray[1]") << endl;
cout << uc.Eval("MyArray[2]") << endl;
cout << uc.Eval("MyArray[3]") << endl;
cout << "" << endl;
// Changing the uCalc array updates the pinned array
uc.Eval("MyArray[0] = 10; MyArray[1] = 20; MyArray[2] = 30; MyArray[3] = 40; ");
// The changes the uCalc array are reflected in the host array
cout << myHostArray[0] << endl;
cout << myHostArray[1] << endl;
cout << myHostArray[2] << endl;
cout << myHostArray[3] << endl;
cout << "" << endl;
// One more round trip
myHostArray[0] = 10;
myHostArray[1] = 11;
myHostArray[2] = 12;
myHostArray[3] = 13;
cout << uc.Eval("MyArray[0]") << endl;
cout << uc.Eval("MyArray[1]") << endl;
cout << uc.Eval("MyArray[2]") << endl;
cout << uc.Eval("MyArray[3]") << endl;
}
5
10
15
20
10
20
30
40
10
11
12
13 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; double myHostArray[] = { 5, 10, 15, 20 }; uc.DefineVariable("MyArray[]", &myHostArray); // The uCalc array values come from the host array cout << uc.Eval("MyArray[0]") << endl; cout << uc.Eval("MyArray[1]") << endl; cout << uc.Eval("MyArray[2]") << endl; cout << uc.Eval("MyArray[3]") << endl; cout << "" << endl; // Changing the uCalc array updates the pinned array uc.Eval("MyArray[0] = 10; MyArray[1] = 20; MyArray[2] = 30; MyArray[3] = 40; "); // The changes the uCalc array are reflected in the host array cout << myHostArray[0] << endl; cout << myHostArray[1] << endl; cout << myHostArray[2] << endl; cout << myHostArray[3] << endl; cout << "" << endl; // One more round trip myHostArray[0] = 10; myHostArray[1] = 11; myHostArray[2] = 12; myHostArray[3] = 13; cout << uc.Eval("MyArray[0]") << endl; cout << uc.Eval("MyArray[1]") << endl; cout << uc.Eval("MyArray[2]") << endl; cout << uc.Eval("MyArray[3]") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim myHostArray() As Double = { 5, 10, 15, 20 }
'// Pin the array
Dim myHostArrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostArray, System.Runtime.InteropServices.GCHandleType.Pinned)
'// Bind the uCalc variable to the pinned memory address
uc.DefineVariable("MyArray[]", myHostArrayHandle.AddrOfPinnedObject())
'// The uCalc array values come from the host array
Console.WriteLine(uc.Eval("MyArray[0]"))
Console.WriteLine(uc.Eval("MyArray[1]"))
Console.WriteLine(uc.Eval("MyArray[2]"))
Console.WriteLine(uc.Eval("MyArray[3]"))
Console.WriteLine("")
'// Changing the uCalc array updates the pinned array
uc.Eval("MyArray[0] = 10; MyArray[1] = 20; MyArray[2] = 30; MyArray[3] = 40; ")
'// The changes the uCalc array are reflected in the host array
Console.WriteLine(myHostArray(0))
Console.WriteLine(myHostArray(1))
Console.WriteLine(myHostArray(2))
Console.WriteLine(myHostArray(3))
Console.WriteLine("")
'// One more round trip
myHostArray(0) = 10
myHostArray(1) = 11
myHostArray(2) = 12
myHostArray(3) = 13
Console.WriteLine(uc.Eval("MyArray[0]"))
Console.WriteLine(uc.Eval("MyArray[1]"))
Console.WriteLine(uc.Eval("MyArray[2]"))
Console.WriteLine(uc.Eval("MyArray[3]"))
'// Don't forget to free the handle when you are completely done with the parser instance
myHostArrayHandle.Free()
End Sub
End Module
5
10
15
20
10
20
30
40
10
11
12
13 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim myHostArray() As Double = { 5, 10, 15, 20 } '// Pin the array Dim myHostArrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostArray, System.Runtime.InteropServices.GCHandleType.Pinned) '// Bind the uCalc variable to the pinned memory address uc.DefineVariable("MyArray[]", myHostArrayHandle.AddrOfPinnedObject()) '// The uCalc array values come from the host array Console.WriteLine(uc.Eval("MyArray[0]")) Console.WriteLine(uc.Eval("MyArray[1]")) Console.WriteLine(uc.Eval("MyArray[2]")) Console.WriteLine(uc.Eval("MyArray[3]")) Console.WriteLine("") '// Changing the uCalc array updates the pinned array uc.Eval("MyArray[0] = 10; MyArray[1] = 20; MyArray[2] = 30; MyArray[3] = 40; ") '// The changes the uCalc array are reflected in the host array Console.WriteLine(myHostArray(0)) Console.WriteLine(myHostArray(1)) Console.WriteLine(myHostArray(2)) Console.WriteLine(myHostArray(3)) Console.WriteLine("") '// One more round trip myHostArray(0) = 10 myHostArray(1) = 11 myHostArray(2) = 12 myHostArray(3) = 13 Console.WriteLine(uc.Eval("MyArray[0]")) Console.WriteLine(uc.Eval("MyArray[1]")) Console.WriteLine(uc.Eval("MyArray[2]")) Console.WriteLine(uc.Eval("MyArray[3]")) '// Don't forget to free the handle when you are completely done with the parser instance myHostArrayHandle.Free() End Sub End Module
Binding a uCalc variable to a host variable in your C++ code
ID: 1465
See: DefineVariable
using uCalcSoftware;
var uc = new uCalc();
// This example is mainly meant for C++ where it works with ordinary scalar variables
// See the other example where we work with a uCalc array
// 1. Use an array so the data lives on the heap as a reference type
// Boxing is used for scalar variables; a boxed copy of the scalar disconnected from the uCalc
// variable would prevent the example from working as expected.
// You technically can get around this with the C# "unsafe" directive, but it's not recommended
double[] myHostVar = new double[] { 1234.5 };
// 2. Pin the array
var myHostVarHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostVar, System.Runtime.InteropServices.GCHandleType.Pinned);
// 3. Bind the uCalc variable to the pinned memory address
uc.DefineVariable("myVar", myHostVarHandle.AddrOfPinnedObject());
Console.WriteLine(uc.Eval("myVar")); // Output: 1234.5
// Changing the uCalc variable updates the pinned array
uc.Eval("myVar = 456");
// The change is reflected in the C# array
Console.WriteLine(myHostVar[0]); // Output: 456
// Changing the C# array updates uCalc
myHostVar[0] = 9876;
Console.WriteLine(uc.Eval("myVar")); // Output: 9876
// Fast Parse & Evaluate loop
var expr = uc.Parse("myVar * 10");
for (myHostVar[0] = 1; myHostVar[0] <= 5; myHostVar[0]++) {
Console.WriteLine(expr.Evaluate());
}
// Don't forget to free the handle when you are completely done with the parser instance
myHostVarHandle.Free();
1234.5
456
9876
10
20
30
40
50 using uCalcSoftware; var uc = new uCalc(); // This example is mainly meant for C++ where it works with ordinary scalar variables // See the other example where we work with a uCalc array // 1. Use an array so the data lives on the heap as a reference type // Boxing is used for scalar variables; a boxed copy of the scalar disconnected from the uCalc // variable would prevent the example from working as expected. // You technically can get around this with the C# "unsafe" directive, but it's not recommended double[] myHostVar = new double[] { 1234.5 }; // 2. Pin the array var myHostVarHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostVar, System.Runtime.InteropServices.GCHandleType.Pinned); // 3. Bind the uCalc variable to the pinned memory address uc.DefineVariable("myVar", myHostVarHandle.AddrOfPinnedObject()); Console.WriteLine(uc.Eval("myVar")); // Output: 1234.5 // Changing the uCalc variable updates the pinned array uc.Eval("myVar = 456"); // The change is reflected in the C# array Console.WriteLine(myHostVar[0]); // Output: 456 // Changing the C# array updates uCalc myHostVar[0] = 9876; Console.WriteLine(uc.Eval("myVar")); // Output: 9876 // Fast Parse & Evaluate loop var expr = uc.Parse("myVar * 10"); for (myHostVar[0] = 1; myHostVar[0] <= 5; myHostVar[0]++) { Console.WriteLine(expr.Evaluate()); } // Don't forget to free the handle when you are completely done with the parser instance myHostVarHandle.Free();
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
double myHostVar = 1234.5;
// Bind your C++ host variable to the uCalc variable like this:
uc.DefineVariable("myVar", &myHostVar);
cout << uc.Eval("myVar") << endl; // The value of the uCalc variable reflects that of the host variable
uc.Eval("myVar = 456"); // Changing the uCalc variable updates the host variable since they're linked
cout << myHostVar << endl; // The change is reflected in the C++ host variable
myHostVar = 9876; // The uCalc variable will reflect this host variable change
cout << uc.Eval("myVar") << endl;
auto expr = uc.Parse("myVar * 10");
for (myHostVar = 1; myHostVar <= 5; myHostVar++) {
cout << expr.Evaluate() << endl;
}
}
1234.5
456
9876
10
20
30
40
50 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; double myHostVar = 1234.5; // Bind your C++ host variable to the uCalc variable like this: uc.DefineVariable("myVar", &myHostVar); cout << uc.Eval("myVar") << endl; // The value of the uCalc variable reflects that of the host variable uc.Eval("myVar = 456"); // Changing the uCalc variable updates the host variable since they're linked cout << myHostVar << endl; // The change is reflected in the C++ host variable myHostVar = 9876; // The uCalc variable will reflect this host variable change cout << uc.Eval("myVar") << endl; auto expr = uc.Parse("myVar * 10"); for (myHostVar = 1; myHostVar <= 5; myHostVar++) { cout << expr.Evaluate() << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// This example is mainly meant for C++ where it works with ordinary scalar variables
'// See the other example where we work with a uCalc array
'// 1. Use an array so the data lives on the heap as a reference type
'// Boxing is used for scalar variables; a boxed copy of the scalar disconnected from the uCalc
'// variable would prevent the example from working as expected.
'// You technically can get around this with the C# "unsafe" directive, but it's not recommended
Dim myHostVar() As Double = { 1234.5 }
'// 2. Pin the array
Dim myHostVarHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostVar, System.Runtime.InteropServices.GCHandleType.Pinned)
'// 3. Bind the uCalc variable to the pinned memory address
uc.DefineVariable("myVar", myHostVarHandle.AddrOfPinnedObject())
Console.WriteLine(uc.Eval("myVar")) '// Output: 1234.5
'// Changing the uCalc variable updates the pinned array
uc.Eval("myVar = 456")
'// The change is reflected in the C# array
Console.WriteLine(myHostVar(0)) '// Output: 456
'// Changing the C# array updates uCalc
myHostVar(0) = 9876
Console.WriteLine(uc.Eval("myVar")) '// Output: 9876
'// Fast Parse & Evaluate loop
Dim expr = uc.Parse("myVar * 10")
For myHostVar(0) = 1 To 5
Console.WriteLine(expr.Evaluate())
Next
'// Don't forget to free the handle when you are completely done with the parser instance
myHostVarHandle.Free()
End Sub
End Module
1234.5
456
9876
10
20
30
40
50 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// This example is mainly meant for C++ where it works with ordinary scalar variables '// See the other example where we work with a uCalc array '// 1. Use an array so the data lives on the heap as a reference type '// Boxing is used for scalar variables; a boxed copy of the scalar disconnected from the uCalc '// variable would prevent the example from working as expected. '// You technically can get around this with the C# "unsafe" directive, but it's not recommended Dim myHostVar() As Double = { 1234.5 } '// 2. Pin the array Dim myHostVarHandle = System.Runtime.InteropServices.GCHandle.Alloc(myHostVar, System.Runtime.InteropServices.GCHandleType.Pinned) '// 3. Bind the uCalc variable to the pinned memory address uc.DefineVariable("myVar", myHostVarHandle.AddrOfPinnedObject()) Console.WriteLine(uc.Eval("myVar")) '// Output: 1234.5 '// Changing the uCalc variable updates the pinned array uc.Eval("myVar = 456") '// The change is reflected in the C# array Console.WriteLine(myHostVar(0)) '// Output: 456 '// Changing the C# array updates uCalc myHostVar(0) = 9876 Console.WriteLine(uc.Eval("myVar")) '// Output: 9876 '// Fast Parse & Evaluate loop Dim expr = uc.Parse("myVar * 10") For myHostVar(0) = 1 To 5 Console.WriteLine(expr.Evaluate()) Next '// Don't forget to free the handle when you are completely done with the parser instance myHostVarHandle.Free() End Sub End Module
BracketSensitive
ID: 121
using uCalcSoftware;
var uc = new uCalc();
var t = uc.NewTransformer();
var Pattern = t.Pattern("< {etc} >");
t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >");
// Note the difference in the final match
Pattern.BracketSensitive = true; // true is the default
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}");
Console.WriteLine("----------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");
Pattern.BracketSensitive = false;
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}");
Console.WriteLine("-----------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");
t.Str("( a b ( c ) d e )");
// Here parentheses are captured as regular tokens, not bracket pairs
var Pattern2a = t.Pattern("( {etc} (");
var Pattern2b = t.Pattern(") {etc} )");
Console.WriteLine("Brackets used as part of pattern");
Console.WriteLine("--------------------------------");
Pattern2a.BracketSensitive = true;
Pattern2b.BracketSensitive = true;
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");
Pattern2a.BracketSensitive = false;
Pattern2b.BracketSensitive = false;
t.Find();
Console.WriteLine(t.Matches.Text);
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >
BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >
Brackets used as part of pattern
--------------------------------
( a b (
) d e )
( a b (
) d e ) using uCalcSoftware; var uc = new uCalc(); var t = uc.NewTransformer(); var Pattern = t.Pattern("< {etc} >"); t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >"); // Note the difference in the final match Pattern.BracketSensitive = true; // true is the default Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}"); Console.WriteLine("----------------------"); t.Find(); Console.WriteLine(t.Matches.Text); Console.WriteLine(""); Pattern.BracketSensitive = false; Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}"); Console.WriteLine("-----------------------"); t.Find(); Console.WriteLine(t.Matches.Text); Console.WriteLine(""); t.Str("( a b ( c ) d e )"); // Here parentheses are captured as regular tokens, not bracket pairs var Pattern2a = t.Pattern("( {etc} ("); var Pattern2b = t.Pattern(") {etc} )"); Console.WriteLine("Brackets used as part of pattern"); Console.WriteLine("--------------------------------"); Pattern2a.BracketSensitive = true; Pattern2b.BracketSensitive = true; t.Find(); Console.WriteLine(t.Matches.Text); Console.WriteLine(""); Pattern2a.BracketSensitive = false; Pattern2b.BracketSensitive = false; t.Find(); Console.WriteLine(t.Matches.Text);
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
#define tf(IsTrue) ((IsTrue) ? "True" : "False")
int main() {
uCalc uc;
auto t = uc.NewTransformer();
auto Pattern = t.Pattern("< {etc} >");
t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >");
// Note the difference in the final match
Pattern.BracketSensitive(true); // true is the default
cout << "BracketSensitive: " << tf(Pattern.BracketSensitive()) << endl;
cout << "----------------------" << endl;
t.Find();
cout << t.Matches().Text() << endl;
cout << "" << endl;
Pattern.BracketSensitive(false);
cout << "BracketSensitive: " << tf(Pattern.BracketSensitive()) << endl;
cout << "-----------------------" << endl;
t.Find();
cout << t.Matches().Text() << endl;
cout << "" << endl;
t.Str("( a b ( c ) d e )");
// Here parentheses are captured as regular tokens, not bracket pairs
auto Pattern2a = t.Pattern("( {etc} (");
auto Pattern2b = t.Pattern(") {etc} )");
cout << "Brackets used as part of pattern" << endl;
cout << "--------------------------------" << endl;
Pattern2a.BracketSensitive(true);
Pattern2b.BracketSensitive(true);
t.Find();
cout << t.Matches().Text() << endl;
cout << "" << endl;
Pattern2a.BracketSensitive(false);
Pattern2b.BracketSensitive(false);
t.Find();
cout << t.Matches().Text() << endl;
}
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >
BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >
Brackets used as part of pattern
--------------------------------
( a b (
) d e )
( a b (
) d e ) #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; #define tf(IsTrue) ((IsTrue) ? "True" : "False") int main() { uCalc uc; auto t = uc.NewTransformer(); auto Pattern = t.Pattern("< {etc} >"); t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >"); // Note the difference in the final match Pattern.BracketSensitive(true); // true is the default cout << "BracketSensitive: " << tf(Pattern.BracketSensitive()) << endl; cout << "----------------------" << endl; t.Find(); cout << t.Matches().Text() << endl; cout << "" << endl; Pattern.BracketSensitive(false); cout << "BracketSensitive: " << tf(Pattern.BracketSensitive()) << endl; cout << "-----------------------" << endl; t.Find(); cout << t.Matches().Text() << endl; cout << "" << endl; t.Str("( a b ( c ) d e )"); // Here parentheses are captured as regular tokens, not bracket pairs auto Pattern2a = t.Pattern("( {etc} ("); auto Pattern2b = t.Pattern(") {etc} )"); cout << "Brackets used as part of pattern" << endl; cout << "--------------------------------" << endl; Pattern2a.BracketSensitive(true); Pattern2b.BracketSensitive(true); t.Find(); cout << t.Matches().Text() << endl; cout << "" << endl; Pattern2a.BracketSensitive(false); Pattern2b.BracketSensitive(false); t.Find(); cout << t.Matches().Text() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t = uc.NewTransformer()
Dim Pattern = t.Pattern("< {etc} >")
t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >")
'// Note the difference in the final match
Pattern.BracketSensitive = true '// true is the default
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}")
Console.WriteLine("----------------------")
t.Find()
Console.WriteLine(t.Matches.Text)
Console.WriteLine("")
Pattern.BracketSensitive = false
Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}")
Console.WriteLine("-----------------------")
t.Find()
Console.WriteLine(t.Matches.Text)
Console.WriteLine("")
t.Str("( a b ( c ) d e )")
'// Here parentheses are captured as regular tokens, not bracket pairs
Dim Pattern2a = t.Pattern("( {etc} (")
Dim Pattern2b = t.Pattern(") {etc} )")
Console.WriteLine("Brackets used as part of pattern")
Console.WriteLine("--------------------------------")
Pattern2a.BracketSensitive = true
Pattern2b.BracketSensitive = true
t.Find()
Console.WriteLine(t.Matches.Text)
Console.WriteLine("")
Pattern2a.BracketSensitive = false
Pattern2b.BracketSensitive = false
t.Find()
Console.WriteLine(t.Matches.Text)
End Sub
End Module
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >
BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >
Brackets used as part of pattern
--------------------------------
( a b (
) d e )
( a b (
) d e ) Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t = uc.NewTransformer() Dim Pattern = t.Pattern("< {etc} >") t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >") '// Note the difference in the final match Pattern.BracketSensitive = true '// true is the default Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}") Console.WriteLine("----------------------") t.Find() Console.WriteLine(t.Matches.Text) Console.WriteLine("") Pattern.BracketSensitive = false Console.WriteLine($"BracketSensitive: {Pattern.BracketSensitive}") Console.WriteLine("-----------------------") t.Find() Console.WriteLine(t.Matches.Text) Console.WriteLine("") t.Str("( a b ( c ) d e )") '// Here parentheses are captured as regular tokens, not bracket pairs Dim Pattern2a = t.Pattern("( {etc} (") Dim Pattern2b = t.Pattern(") {etc} )") Console.WriteLine("Brackets used as part of pattern") Console.WriteLine("--------------------------------") Pattern2a.BracketSensitive = true Pattern2b.BracketSensitive = true t.Find() Console.WriteLine(t.Matches.Text) Console.WriteLine("") Pattern2a.BracketSensitive = false Pattern2b.BracketSensitive = false t.Find() Console.WriteLine(t.Matches.Text) End Sub End Module
Building an Equation Solver with the Parser and Transformer
ID: 1461
using uCalcSoftware;
var uc = new uCalc();
static void EqSolveCb(uCalc.Callback cb) { // Callback based on the Bisection Method
var expr = cb.ArgExpr(1); // ByExpr: Unevaluated Expression object (lazy evaluation)
var a = cb.Arg(2); // Argument 2: Range Minimum
var b = cb.Arg(3); // Argument 3: Range Maximum
var variable = cb.ArgItem(4); // ByHandle: The variable Item object
// Helper to update the variable in the uCalc engine and evaluate the expression
double EvaluateAt(double val) {
variable.Value(val); // Push the new test value to the variable
return expr.Evaluate(); // Evaluate the pre-parsed expression
}
// Ensure f(a) < f(b) so we always know which direction to slide the bounds; swap a & b if necessary
if (EvaluateAt(b) < EvaluateAt(a)) (a, b) = (b, a);
var midpoint = 0.0;
var fMidpoint = 0.0;
// Bisection loop
for (int i = 0; i <= 100; i++) {
midpoint = (a + b) / 2;
fMidpoint = EvaluateAt(midpoint);
if (Math.Abs(fMidpoint) < 1e-7) break; // Stop if close enough to 0
// Narrow the bounds (compact logic!)
if (fMidpoint < 0) a = midpoint; else b = midpoint;
}
if (Math.Abs(fMidpoint) > 1e-5) cb.Error.Raise("No solution found in the given range.");
cb.Return(Math.Round(midpoint, 7)); // Return the final solved value
}
// 1. Define variables that might be used by the end-user
uc.DefineVariable("x");
uc.DefineVariable("MyVar");
// 2. Transformer converts `EqSolve(L = R)` into `EqSolve(L - (R))` & sets defaults before it hits the parser
var t = uc.ExpressionTransformer;
t.FromTo("EqSolve({L} = {R} [[,]for {var}][, {min}, {max}])",
"EqSolve({L} - ({R}), {min}{!min:-10000}, {max}{!max: 10000}, {var}{!var: x})");
// 3. Define the custom function signature
uc.DefineFunction("EqSolve(ByExpr eq, min, max, ByHandle variable)", EqSolveCb);
// --- Demo Executions ---
System.Collections.Generic.List eqList = new() {
"EqSolve(x + 5 = 125)", // Using default range [-10000,10000]
"EqSolve(x^2 + 5 = 105)", // Picks one result from the default range
"EqSolve(x^2 + 5 = 105, 0, 100)", // Restricts to positive root
"EqSolve(x^2 + 5 = 105, -100, 0)", // Restricts to negative root
"EqSolve(x^2 + 1000 = 5)", // No existing solution
"EqSolve(40 + MyVar * 6 = 88, for MyVar)" // Uses custom variable 'MyVar' instead of 'x'
};
foreach(var eq in eqList) {
Console.WriteLine(uc.ExpressionTransformer.Transform(eq)); // Displays transformed expression
Console.WriteLine($"Result: {uc.EvalStr(eq)}"); // Returns result
}
EqSolve(x + 5 - (125), -10000, 10000, x)
Result: 120
EqSolve(x^2 + 5 - (105), -10000, 10000, x)
Result: 10
EqSolve(x^2 + 5 - (105), 0, 100, x)
Result: 10
EqSolve(x^2 + 5 - (105), -100, 0, x)
Result: -10
EqSolve(x^2 + 1000 - (5), -10000, 10000, x)
Result: No solution found in the given range.
EqSolve(40 + MyVar * 6 - (88), -10000, 10000, MyVar)
Result: 8 using uCalcSoftware; var uc = new uCalc(); static void EqSolveCb(uCalc.Callback cb) { // Callback based on the Bisection Method var expr = cb.ArgExpr(1); // ByExpr: Unevaluated Expression object (lazy evaluation) var a = cb.Arg(2); // Argument 2: Range Minimum var b = cb.Arg(3); // Argument 3: Range Maximum var variable = cb.ArgItem(4); // ByHandle: The variable Item object // Helper to update the variable in the uCalc engine and evaluate the expression double EvaluateAt(double val) { variable.Value(val); // Push the new test value to the variable return expr.Evaluate(); // Evaluate the pre-parsed expression } // Ensure f(a) < f(b) so we always know which direction to slide the bounds; swap a & b if necessary if (EvaluateAt(b) < EvaluateAt(a)) (a, b) = (b, a); var midpoint = 0.0; var fMidpoint = 0.0; // Bisection loop for (int i = 0; i <= 100; i++) { midpoint = (a + b) / 2; fMidpoint = EvaluateAt(midpoint); if (Math.Abs(fMidpoint) < 1e-7) break; // Stop if close enough to 0 // Narrow the bounds (compact logic!) if (fMidpoint < 0) a = midpoint; else b = midpoint; } if (Math.Abs(fMidpoint) > 1e-5) cb.Error.Raise("No solution found in the given range."); cb.Return(Math.Round(midpoint, 7)); // Return the final solved value } // 1. Define variables that might be used by the end-user uc.DefineVariable("x"); uc.DefineVariable("MyVar"); // 2. Transformer converts `EqSolve(L = R)` into `EqSolve(L - (R))` & sets defaults before it hits the parser var t = uc.ExpressionTransformer; t.FromTo("EqSolve({L} = {R} [[,]for {var}][, {min}, {max}])", "EqSolve({L} - ({R}), {min}{!min:-10000}, {max}{!max: 10000}, {var}{!var: x})"); // 3. Define the custom function signature uc.DefineFunction("EqSolve(ByExpr eq, min, max, ByHandle variable)", EqSolveCb); // --- Demo Executions --- System.Collections.Generic.List<string> eqList = new() { "EqSolve(x + 5 = 125)", // Using default range [-10000,10000] "EqSolve(x^2 + 5 = 105)", // Picks one result from the default range "EqSolve(x^2 + 5 = 105, 0, 100)", // Restricts to positive root "EqSolve(x^2 + 5 = 105, -100, 0)", // Restricts to negative root "EqSolve(x^2 + 1000 = 5)", // No existing solution "EqSolve(40 + MyVar * 6 = 88, for MyVar)" // Uses custom variable 'MyVar' instead of 'x' }; foreach(var eq in eqList) { Console.WriteLine(uc.ExpressionTransformer.Transform(eq)); // Displays transformed expression Console.WriteLine($"Result: {uc.EvalStr(eq)}"); // Returns result }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call EqSolveCb(uCalcBase::Callback cb) { // Callback based on the Bisection Method
auto expr = cb.ArgExpr(1); // ByExpr: Unevaluated Expression object (lazy evaluation)
auto a = cb.Arg(2); // Argument 2: Range Minimum
auto b = cb.Arg(3); // Argument 3: Range Maximum
auto variable = cb.ArgItem(4); // ByHandle: The variable Item object
// Helper to update the variable in the uCalc engine and evaluate the expression
auto EvaluateAt = [&](double val) -> double {
variable.Value(val);
return expr.Evaluate();
};
// Ensure f(a) < f(b) so we always know which direction to slide the bounds; swap a & b if necessary
if (EvaluateAt(b) < EvaluateAt(a)) swap(a, b);
auto midpoint = 0.0;
auto fMidpoint = 0.0;
// Bisection loop
for (int i = 0; i <= 100; i++) {
midpoint = (a + b) / 2;
fMidpoint = EvaluateAt(midpoint);
if (abs(fMidpoint) < 1e-7) break; // Stop if close enough to 0
// Narrow the bounds (compact logic!)
if (fMidpoint < 0) a = midpoint; else b = midpoint;
}
if (abs(fMidpoint) > 1e-5) cb.Error().Raise("No solution found in the given range.");
cb.Return(round(midpoint * 10000000.0) / 10000000.0); // Return the final solved value
}
int main() {
uCalc uc;
// 1. Define variables that might be used by the end-user
uc.DefineVariable("x");
uc.DefineVariable("MyVar");
// 2. Transformer converts `EqSolve(L = R)` into `EqSolve(L - (R))` & sets defaults before it hits the parser
auto t = uc.ExpressionTransformer();
t.FromTo("EqSolve({L} = {R} [[,]for {var}][, {min}, {max}])",
"EqSolve({L} - ({R}), {min}{!min:-10000}, {max}{!max: 10000}, {var}{!var: x})");
// 3. Define the custom function signature
uc.DefineFunction("EqSolve(ByExpr eq, min, max, ByHandle variable)", EqSolveCb);
// --- Demo Executions ---
vector eqList = {
"EqSolve(x + 5 = 125)", // Using default range [-10000,10000]
"EqSolve(x^2 + 5 = 105)", // Picks one result from the default range
"EqSolve(x^2 + 5 = 105, 0, 100)", // Restricts to positive root
"EqSolve(x^2 + 5 = 105, -100, 0)", // Restricts to negative root
"EqSolve(x^2 + 1000 = 5)", // No existing solution
"EqSolve(40 + MyVar * 6 = 88, for MyVar)" // Uses custom variable 'MyVar' instead of 'x'
};
for(auto eq : eqList) {
cout << uc.ExpressionTransformer().Transform(eq) << endl; // Displays transformed expression
cout << "Result: " << uc.EvalStr(eq) << endl; // Returns result
}
}
EqSolve(x + 5 - (125), -10000, 10000, x)
Result: 120
EqSolve(x^2 + 5 - (105), -10000, 10000, x)
Result: 10
EqSolve(x^2 + 5 - (105), 0, 100, x)
Result: 10
EqSolve(x^2 + 5 - (105), -100, 0, x)
Result: -10
EqSolve(x^2 + 1000 - (5), -10000, 10000, x)
Result: No solution found in the given range.
EqSolve(40 + MyVar * 6 - (88), -10000, 10000, MyVar)
Result: 8 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call EqSolveCb(uCalcBase::Callback cb) { // Callback based on the Bisection Method auto expr = cb.ArgExpr(1); // ByExpr: Unevaluated Expression object (lazy evaluation) auto a = cb.Arg(2); // Argument 2: Range Minimum auto b = cb.Arg(3); // Argument 3: Range Maximum auto variable = cb.ArgItem(4); // ByHandle: The variable Item object // Helper to update the variable in the uCalc engine and evaluate the expression auto EvaluateAt = [&](double val) -> double { variable.Value(val); return expr.Evaluate(); }; // Ensure f(a) < f(b) so we always know which direction to slide the bounds; swap a & b if necessary if (EvaluateAt(b) < EvaluateAt(a)) swap(a, b); auto midpoint = 0.0; auto fMidpoint = 0.0; // Bisection loop for (int i = 0; i <= 100; i++) { midpoint = (a + b) / 2; fMidpoint = EvaluateAt(midpoint); if (abs(fMidpoint) < 1e-7) break; // Stop if close enough to 0 // Narrow the bounds (compact logic!) if (fMidpoint < 0) a = midpoint; else b = midpoint; } if (abs(fMidpoint) > 1e-5) cb.Error().Raise("No solution found in the given range."); cb.Return(round(midpoint * 10000000.0) / 10000000.0); // Return the final solved value } int main() { uCalc uc; // 1. Define variables that might be used by the end-user uc.DefineVariable("x"); uc.DefineVariable("MyVar"); // 2. Transformer converts `EqSolve(L = R)` into `EqSolve(L - (R))` & sets defaults before it hits the parser auto t = uc.ExpressionTransformer(); t.FromTo("EqSolve({L} = {R} [[,]for {var}][, {min}, {max}])", "EqSolve({L} - ({R}), {min}{!min:-10000}, {max}{!max: 10000}, {var}{!var: x})"); // 3. Define the custom function signature uc.DefineFunction("EqSolve(ByExpr eq, min, max, ByHandle variable)", EqSolveCb); // --- Demo Executions --- vector<string> eqList = { "EqSolve(x + 5 = 125)", // Using default range [-10000,10000] "EqSolve(x^2 + 5 = 105)", // Picks one result from the default range "EqSolve(x^2 + 5 = 105, 0, 100)", // Restricts to positive root "EqSolve(x^2 + 5 = 105, -100, 0)", // Restricts to negative root "EqSolve(x^2 + 1000 = 5)", // No existing solution "EqSolve(40 + MyVar * 6 = 88, for MyVar)" // Uses custom variable 'MyVar' instead of 'x' }; for(auto eq : eqList) { cout << uc.ExpressionTransformer().Transform(eq) << endl; // Displays transformed expression cout << "Result: " << uc.EvalStr(eq) << endl; // Returns result } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub EqSolveCb(ByVal cb As uCalc.Callback)REM // Callback based on the Bisection Method
Dim expr = cb.ArgExpr(1) '// ByExpr: Unevaluated Expression object (lazy evaluation)
Dim a = cb.Arg(2) '// Argument 2: Range Minimum
Dim b = cb.Arg(3) '// Argument 3: Range Maximum
Dim variable = cb.ArgItem(4) '// ByHandle: The variable Item object
'// Helper to update the variable in the uCalc engine and evaluate the expression
Dim EvaluateAt = Function (val as Double) As Double
variable.Value(val) '// Push the new test value to the variable
return expr.Evaluate() '// Evaluate the pre-parsed expression
End Function
'// Ensure f(a) < f(b) so we always know which direction to slide the bounds; swap a & b if necessary
If EvaluateAt(b) < EvaluateAt(a) Then Dim temp = a : a = b : b = temp
Dim midpoint = 0.0
Dim fMidpoint = 0.0
'// Bisection loop
For i As Integer = 0 To 100
midpoint = (a + b) / 2
fMidpoint = EvaluateAt(midpoint)
If Math.Abs(fMidpoint) < 1e-7 Then Exit For REM // Stop if close enough to 0
REM// Narrow the bounds (compact logic!)
If fMidpoint < 0 Then a = midpoint Else b = midpoint
Next
If Math.Abs(fMidpoint) > 1e-5 Then cb.Error.Raise("No solution found in the given range.")
cb.Return(Math.Round(midpoint, 7)) '// Return the final solved value
End Sub
Public Sub Main()
Dim uc As New uCalc()
'// 1. Define variables that might be used by the end-user
uc.DefineVariable("x")
uc.DefineVariable("MyVar")
'// 2. Transformer converts `EqSolve(L = R)` into `EqSolve(L - (R))` & sets defaults before it hits the parser
Dim t = uc.ExpressionTransformer
t.FromTo("EqSolve({L} = {R} [[,]for {var}][, {min}, {max}])",
"EqSolve({L} - ({R}), {min}{!min:-10000}, {max}{!max: 10000}, {var}{!var: x})")
'// 3. Define the custom function signature
uc.DefineFunction("EqSolve(ByExpr eq, min, max, ByHandle variable)", AddressOf EqSolveCb)
'// --- Demo Executions ---
Dim eqList As New List(Of String) From {
"EqSolve(x + 5 = 125)", '// Using default range [-10000,10000]
"EqSolve(x^2 + 5 = 105)", '// Picks one result from the default range
"EqSolve(x^2 + 5 = 105, 0, 100)", '// Restricts to positive root
"EqSolve(x^2 + 5 = 105, -100, 0)", '// Restricts to negative root
"EqSolve(x^2 + 1000 = 5)", '// No existing solution
"EqSolve(40 + MyVar * 6 = 88, for MyVar)" '// Uses custom variable 'MyVar' instead of 'x'
}
For Each eq In eqList
Console.WriteLine(uc.ExpressionTransformer.Transform(eq)) '// Displays transformed expression
Console.WriteLine($"Result: {uc.EvalStr(eq)}") '// Returns result
Next
End Sub
End Module
EqSolve(x + 5 - (125), -10000, 10000, x)
Result: 120
EqSolve(x^2 + 5 - (105), -10000, 10000, x)
Result: 10
EqSolve(x^2 + 5 - (105), 0, 100, x)
Result: 10
EqSolve(x^2 + 5 - (105), -100, 0, x)
Result: -10
EqSolve(x^2 + 1000 - (5), -10000, 10000, x)
Result: No solution found in the given range.
EqSolve(40 + MyVar * 6 - (88), -10000, 10000, MyVar)
Result: 8 Imports System Imports uCalcSoftware Public Module Program Public Sub EqSolveCb(ByVal cb As uCalc.Callback)REM // Callback based on the Bisection Method Dim expr = cb.ArgExpr(1) '// ByExpr: Unevaluated Expression object (lazy evaluation) Dim a = cb.Arg(2) '// Argument 2: Range Minimum Dim b = cb.Arg(3) '// Argument 3: Range Maximum Dim variable = cb.ArgItem(4) '// ByHandle: The variable Item object '// Helper to update the variable in the uCalc engine and evaluate the expression Dim EvaluateAt = Function (val as Double) As Double variable.Value(val) '// Push the new test value to the variable return expr.Evaluate() '// Evaluate the pre-parsed expression End Function '// Ensure f(a) < f(b) so we always know which direction to slide the bounds; swap a & b if necessary If EvaluateAt(b) < EvaluateAt(a) Then Dim temp = a : a = b : b = temp Dim midpoint = 0.0 Dim fMidpoint = 0.0 '// Bisection loop For i As Integer = 0 To 100 midpoint = (a + b) / 2 fMidpoint = EvaluateAt(midpoint) If Math.Abs(fMidpoint) < 1e-7 Then Exit For REM // Stop if close enough to 0 REM// Narrow the bounds (compact logic!) If fMidpoint < 0 Then a = midpoint Else b = midpoint Next If Math.Abs(fMidpoint) > 1e-5 Then cb.Error.Raise("No solution found in the given range.") cb.Return(Math.Round(midpoint, 7)) '// Return the final solved value End Sub Public Sub Main() Dim uc As New uCalc() '// 1. Define variables that might be used by the end-user uc.DefineVariable("x") uc.DefineVariable("MyVar") '// 2. Transformer converts `EqSolve(L = R)` into `EqSolve(L - (R))` & sets defaults before it hits the parser Dim t = uc.ExpressionTransformer t.FromTo("EqSolve({L} = {R} [[,]for {var}][, {min}, {max}])", "EqSolve({L} - ({R}), {min}{!min:-10000}, {max}{!max: 10000}, {var}{!var: x})") '// 3. Define the custom function signature uc.DefineFunction("EqSolve(ByExpr eq, min, max, ByHandle variable)", AddressOf EqSolveCb) '// --- Demo Executions --- Dim eqList As New List(Of String) From { "EqSolve(x + 5 = 125)", '// Using default range [-10000,10000] "EqSolve(x^2 + 5 = 105)", '// Picks one result from the default range "EqSolve(x^2 + 5 = 105, 0, 100)", '// Restricts to positive root "EqSolve(x^2 + 5 = 105, -100, 0)", '// Restricts to negative root "EqSolve(x^2 + 1000 = 5)", '// No existing solution "EqSolve(40 + MyVar * 6 = 88, for MyVar)" '// Uses custom variable 'MyVar' instead of 'x' } For Each eq In eqList Console.WriteLine(uc.ExpressionTransformer.Transform(eq)) '// Displays transformed expression Console.WriteLine($"Result: {uc.EvalStr(eq)}") '// Returns result Next End Sub End Module
Calculates a monthly loan payment by defining a custom function with the standard amortization formula, showcasing a practical, real-world use case.
ID: 1267
using uCalcSoftware;
var uc = new uCalc();
// Define a function for the standard loan payment formula
uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100");
// Define variables for the calculation
uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate
uc.DefineVariable("periods = 30 * 12"); // 30 years
uc.DefineVariable("loan_amount = 200000"); // $200,000
Console.WriteLine(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"));
1073.64 using uCalcSoftware; var uc = new uCalc(); // Define a function for the standard loan payment formula uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100"); // Define variables for the calculation uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate uc.DefineVariable("periods = 30 * 12"); // 30 years uc.DefineVariable("loan_amount = 200000"); // $200,000 Console.WriteLine(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// Define a function for the standard loan payment formula
uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100");
// Define variables for the calculation
uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate
uc.DefineVariable("periods = 30 * 12"); // 30 years
uc.DefineVariable("loan_amount = 200000"); // $200,000
cout << uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)") << endl;
}
1073.64 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // Define a function for the standard loan payment formula uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100"); // Define variables for the calculation uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate uc.DefineVariable("periods = 30 * 12"); // 30 years uc.DefineVariable("loan_amount = 200000"); // $200,000 cout << uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// Define a function for the standard loan payment formula
uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100")
'// Define variables for the calculation
uc.DefineVariable("monthly_rate = 0.05 / 12") '// 5% annual rate
uc.DefineVariable("periods = 30 * 12") '// 30 years
uc.DefineVariable("loan_amount = 200000") '// $200,000
Console.WriteLine(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"))
End Sub
End Module
1073.64 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// Define a function for the standard loan payment formula uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100") '// Define variables for the calculation uc.DefineVariable("monthly_rate = 0.05 / 12") '// 5% annual rate uc.DefineVariable("periods = 30 * 12") '// 30 years uc.DefineVariable("loan_amount = 200000") '// $200,000 Console.WriteLine(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)")) End Sub End Module
Calculates a total price using predefined variables and demonstrates the effect of output formatting.
ID: 338
See: EvalStr
using uCalcSoftware;
var uc = new uCalc();
// Define some context for the expression
uc.DefineVariable("price = 49.99");
uc.DefineVariable("quantity = 3");
uc.DefineConstant("TAX_RATE = 0.0825");
// Define a format for currency output
uc.Format("DataType: Double, Def: result = '$' + result");
// Expression to calculate total price, using variables
var expression = "price * quantity * (1 + TAX_RATE)";
// Evaluate with formatting enabled
Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, true)}");
// Evaluate with formatting disabled
Console.WriteLine($"Raw Total: {uc.EvalStr(expression, false)}");
Formatted Total: $162.342525
Raw Total: 162.342525 using uCalcSoftware; var uc = new uCalc(); // Define some context for the expression uc.DefineVariable("price = 49.99"); uc.DefineVariable("quantity = 3"); uc.DefineConstant("TAX_RATE = 0.0825"); // Define a format for currency output uc.Format("DataType: Double, Def: result = '$' + result"); // Expression to calculate total price, using variables var expression = "price * quantity * (1 + TAX_RATE)"; // Evaluate with formatting enabled Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, true)}"); // Evaluate with formatting disabled Console.WriteLine($"Raw Total: {uc.EvalStr(expression, false)}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// Define some context for the expression
uc.DefineVariable("price = 49.99");
uc.DefineVariable("quantity = 3");
uc.DefineConstant("TAX_RATE = 0.0825");
// Define a format for currency output
uc.Format("DataType: Double, Def: result = '$' + result");
// Expression to calculate total price, using variables
auto expression = "price * quantity * (1 + TAX_RATE)";
// Evaluate with formatting enabled
cout << "Formatted Total: " << uc.EvalStr(expression, true) << endl;
// Evaluate with formatting disabled
cout << "Raw Total: " << uc.EvalStr(expression, false) << endl;
}
Formatted Total: $162.342525
Raw Total: 162.342525 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // Define some context for the expression uc.DefineVariable("price = 49.99"); uc.DefineVariable("quantity = 3"); uc.DefineConstant("TAX_RATE = 0.0825"); // Define a format for currency output uc.Format("DataType: Double, Def: result = '$' + result"); // Expression to calculate total price, using variables auto expression = "price * quantity * (1 + TAX_RATE)"; // Evaluate with formatting enabled cout << "Formatted Total: " << uc.EvalStr(expression, true) << endl; // Evaluate with formatting disabled cout << "Raw Total: " << uc.EvalStr(expression, false) << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// Define some context for the expression
uc.DefineVariable("price = 49.99")
uc.DefineVariable("quantity = 3")
uc.DefineConstant("TAX_RATE = 0.0825")
'// Define a format for currency output
uc.Format("DataType: Double, Def: result = '$' + result")
'// Expression to calculate total price, using variables
Dim expression = "price * quantity * (1 + TAX_RATE)"
'// Evaluate with formatting enabled
Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, true)}")
'// Evaluate with formatting disabled
Console.WriteLine($"Raw Total: {uc.EvalStr(expression, false)}")
End Sub
End Module
Formatted Total: $162.342525
Raw Total: 162.342525 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// Define some context for the expression uc.DefineVariable("price = 49.99") uc.DefineVariable("quantity = 3") uc.DefineConstant("TAX_RATE = 0.0825") '// Define a format for currency output uc.Format("DataType: Double, Def: result = '$' + result") '// Expression to calculate total price, using variables Dim expression = "price * quantity * (1 + TAX_RATE)" '// Evaluate with formatting enabled Console.WriteLine($"Formatted Total: {uc.EvalStr(expression, true)}") '// Evaluate with formatting disabled Console.WriteLine($"Raw Total: {uc.EvalStr(expression, false)}") End Sub End Module
Calculates simple interest by defining variables and then evaluating an expression string that uses them.
ID: 335
See: Eval
using uCalcSoftware;
var uc = new uCalc();
// Define variables representing configuration or user inputs.
uc.DefineVariable("principal = 20000");
uc.DefineVariable("annual_rate = 0.0575");
uc.DefineVariable("years = 4");
// Evaluate an expression combining these variables.
var interest = uc.Eval("principal * annual_rate * years");
Console.WriteLine($"Total Interest: {interest}");
Total Interest: 4600 using uCalcSoftware; var uc = new uCalc(); // Define variables representing configuration or user inputs. uc.DefineVariable("principal = 20000"); uc.DefineVariable("annual_rate = 0.0575"); uc.DefineVariable("years = 4"); // Evaluate an expression combining these variables. var interest = uc.Eval("principal * annual_rate * years"); Console.WriteLine($"Total Interest: {interest}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// Define variables representing configuration or user inputs.
uc.DefineVariable("principal = 20000");
uc.DefineVariable("annual_rate = 0.0575");
uc.DefineVariable("years = 4");
// Evaluate an expression combining these variables.
auto interest = uc.Eval("principal * annual_rate * years");
cout << "Total Interest: " << interest << endl;
}
Total Interest: 4600 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // Define variables representing configuration or user inputs. uc.DefineVariable("principal = 20000"); uc.DefineVariable("annual_rate = 0.0575"); uc.DefineVariable("years = 4"); // Evaluate an expression combining these variables. auto interest = uc.Eval("principal * annual_rate * years"); cout << "Total Interest: " << interest << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// Define variables representing configuration or user inputs.
uc.DefineVariable("principal = 20000")
uc.DefineVariable("annual_rate = 0.0575")
uc.DefineVariable("years = 4")
'// Evaluate an expression combining these variables.
Dim interest = uc.Eval("principal * annual_rate * years")
Console.WriteLine($"Total Interest: {interest}")
End Sub
End Module
Total Interest: 4600 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// Define variables representing configuration or user inputs. uc.DefineVariable("principal = 20000") uc.DefineVariable("annual_rate = 0.0575") uc.DefineVariable("years = 4") '// Evaluate an expression combining these variables. Dim interest = uc.Eval("principal * annual_rate * years") Console.WriteLine($"Total Interest: {interest}") End Sub End Module
Calculates simple interest using pre-defined variables for a real-world scenario.
ID: 1181
using uCalcSoftware;
var uc = new uCalc();
uc.DefineVariable("principal = 5000");
uc.DefineVariable("rate = 0.05");
uc.DefineVariable("years = 4");
Console.WriteLine($"Interest: {uc.EvalStr("principal * rate * years")}");
Interest: 1000 using uCalcSoftware; var uc = new uCalc(); uc.DefineVariable("principal = 5000"); uc.DefineVariable("rate = 0.05"); uc.DefineVariable("years = 4"); Console.WriteLine($"Interest: {uc.EvalStr("principal * rate * years")}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uc.DefineVariable("principal = 5000");
uc.DefineVariable("rate = 0.05");
uc.DefineVariable("years = 4");
cout << "Interest: " << uc.EvalStr("principal * rate * years") << endl;
}
Interest: 1000 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uc.DefineVariable("principal = 5000"); uc.DefineVariable("rate = 0.05"); uc.DefineVariable("years = 4"); cout << "Interest: " << uc.EvalStr("principal * rate * years") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
uc.DefineVariable("principal = 5000")
uc.DefineVariable("rate = 0.05")
uc.DefineVariable("years = 4")
Console.WriteLine($"Interest: {uc.EvalStr("principal * rate * years")}")
End Sub
End Module
Interest: 1000 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() uc.DefineVariable("principal = 5000") uc.DefineVariable("rate = 0.05") uc.DefineVariable("years = 4") Console.WriteLine($"Interest: {uc.EvalStr("principal * rate * years")}") End Sub End Module
Calculating a simple percentage for a real-world financial scenario.
ID: 1178
using uCalcSoftware;
var uc = new uCalc();
// Calculate a 15% discount on a price of $75
Console.Write("Discounted price: ");
Console.WriteLine(uc.EvalStr("75 * (1 - 0.15)"));
Discounted price: 63.75 using uCalcSoftware; var uc = new uCalc(); // Calculate a 15% discount on a price of $75 Console.Write("Discounted price: "); Console.WriteLine(uc.EvalStr("75 * (1 - 0.15)"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// Calculate a 15% discount on a price of $75
cout << "Discounted price: ";
cout << uc.EvalStr("75 * (1 - 0.15)") << endl;
}
Discounted price: 63.75 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // Calculate a 15% discount on a price of $75 cout << "Discounted price: "; cout << uc.EvalStr("75 * (1 - 0.15)") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// Calculate a 15% discount on a price of $75
Console.Write("Discounted price: ")
Console.WriteLine(uc.EvalStr("75 * (1 - 0.15)"))
End Sub
End Module
Discounted price: 63.75 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// Calculate a 15% discount on a price of $75 Console.Write("Discounted price: ") Console.WriteLine(uc.EvalStr("75 * (1 - 0.15)")) End Sub End Module
Capturing both parsing-stage and evaluation-stage errors to see how ErrorLocation behaves differently.
ID: 321
using uCalcSoftware;
var uc = new uCalc();
static void MyErrorHandler(Handle_uCalc h) {
var uc = new uCalc(h);
Console.WriteLine("--- Error Captured ---");
Console.WriteLine($"Message: {uc.Error.Message}");
Console.WriteLine($"Symbol: '{uc.Error.Symbol}'");
Console.WriteLine($"Location: {uc.Error.Location}");
Console.WriteLine($"Expression: '{uc.Error.Expression}'");
}
uc.Error.AddHandler(MyErrorHandler);
Console.WriteLine("Demonstrating a PARSING error:");
uc.EvalStr("123//456");
Console.WriteLine("");
Console.WriteLine("Demonstrating an EVALUATION error:");
uc.Error.TrapOnDivideByZero = true;
uc.EvalStr("5/0");
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'
Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: '' using uCalcSoftware; var uc = new uCalc(); static void MyErrorHandler(Handle_uCalc h) { var uc = new uCalc(h); Console.WriteLine("--- Error Captured ---"); Console.WriteLine($"Message: {uc.Error.Message}"); Console.WriteLine($"Symbol: '{uc.Error.Symbol}'"); Console.WriteLine($"Location: {uc.Error.Location}"); Console.WriteLine($"Expression: '{uc.Error.Expression}'"); } uc.Error.AddHandler(MyErrorHandler); Console.WriteLine("Demonstrating a PARSING error:"); uc.EvalStr("123//456"); Console.WriteLine(""); Console.WriteLine("Demonstrating an EVALUATION error:"); uc.Error.TrapOnDivideByZero = true; uc.EvalStr("5/0");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call MyErrorHandler(Handle_uCalc h) {
auto uc = uCalc(h);
cout << "--- Error Captured ---" << endl;
cout << "Message: " << uc.Error().Message() << endl;
cout << "Symbol: '" << uc.Error().Symbol() << "'" << endl;
cout << "Location: " << uc.Error().Location() << endl;
cout << "Expression: '" << uc.Error().Expression() << "'" << endl;
}
int main() {
uCalc uc;
uc.Error().AddHandler(MyErrorHandler);
cout << "Demonstrating a PARSING error:" << endl;
uc.EvalStr("123//456");
cout << "" << endl;
cout << "Demonstrating an EVALUATION error:" << endl;
uc.Error().TrapOnDivideByZero(true);
uc.EvalStr("5/0");
}
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'
Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: '' #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call MyErrorHandler(Handle_uCalc h) { auto uc = uCalc(h); cout << "--- Error Captured ---" << endl; cout << "Message: " << uc.Error().Message() << endl; cout << "Symbol: '" << uc.Error().Symbol() << "'" << endl; cout << "Location: " << uc.Error().Location() << endl; cout << "Expression: '" << uc.Error().Expression() << "'" << endl; } int main() { uCalc uc; uc.Error().AddHandler(MyErrorHandler); cout << "Demonstrating a PARSING error:" << endl; uc.EvalStr("123//456"); cout << "" << endl; cout << "Demonstrating an EVALUATION error:" << endl; uc.Error().TrapOnDivideByZero(true); uc.EvalStr("5/0"); }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub MyErrorHandler(ByVal h As Handle_uCalc)
Dim uc As New uCalc(h)
Console.WriteLine("--- Error Captured ---")
Console.WriteLine($"Message: {uc.Error.Message}")
Console.WriteLine($"Symbol: '{uc.Error.Symbol}'")
Console.WriteLine($"Location: {uc.Error.Location}")
Console.WriteLine($"Expression: '{uc.Error.Expression}'")
End Sub
Public Sub Main()
Dim uc As New uCalc()
uc.Error.AddHandler(AddressOf MyErrorHandler)
Console.WriteLine("Demonstrating a PARSING error:")
uc.EvalStr("123//456")
Console.WriteLine("")
Console.WriteLine("Demonstrating an EVALUATION error:")
uc.Error.TrapOnDivideByZero = true
uc.EvalStr("5/0")
End Sub
End Module
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'
Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: '' Imports System Imports uCalcSoftware Public Module Program Public Sub MyErrorHandler(ByVal h As Handle_uCalc) Dim uc As New uCalc(h) Console.WriteLine("--- Error Captured ---") Console.WriteLine($"Message: {uc.Error.Message}") Console.WriteLine($"Symbol: '{uc.Error.Symbol}'") Console.WriteLine($"Location: {uc.Error.Location}") Console.WriteLine($"Expression: '{uc.Error.Expression}'") End Sub Public Sub Main() Dim uc As New uCalc() uc.Error.AddHandler(AddressOf MyErrorHandler) Console.WriteLine("Demonstrating a PARSING error:") uc.EvalStr("123//456") Console.WriteLine("") Console.WriteLine("Demonstrating an EVALUATION error:") uc.Error.TrapOnDivideByZero = true uc.EvalStr("5/0") End Sub End Module
CaseSensitive
ID: 122
using uCalcSoftware;
var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH");
var Pattern = t.Pattern("StArT {etc} FinISH");
Pattern.CaseSensitive = true;
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}");
Console.WriteLine("-------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
Console.WriteLine("");
Pattern.CaseSensitive = false;
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}");
Console.WriteLine("--------------------");
t.Find();
Console.WriteLine(t.Matches.Text);
CaseSensitive: True
-------------------
StArT a b c FinISH
CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH using uCalcSoftware; var uc = new uCalc(); var t = uc.NewTransformer(); t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH"); var Pattern = t.Pattern("StArT {etc} FinISH"); Pattern.CaseSensitive = true; Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}"); Console.WriteLine("-------------------"); t.Find(); Console.WriteLine(t.Matches.Text); Console.WriteLine(""); Pattern.CaseSensitive = false; Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}"); Console.WriteLine("--------------------"); t.Find(); Console.WriteLine(t.Matches.Text);
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
#define tf(IsTrue) ((IsTrue) ? "True" : "False")
int main() {
uCalc uc;
auto t = uc.NewTransformer();
t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH");
auto Pattern = t.Pattern("StArT {etc} FinISH");
Pattern.CaseSensitive(true);
cout << "CaseSensitive: " << tf(Pattern.CaseSensitive()) << endl;
cout << "-------------------" << endl;
t.Find();
cout << t.Matches().Text() << endl;
cout << "" << endl;
Pattern.CaseSensitive(false);
cout << "CaseSensitive: " << tf(Pattern.CaseSensitive()) << endl;
cout << "--------------------" << endl;
t.Find();
cout << t.Matches().Text() << endl;
}
CaseSensitive: True
-------------------
StArT a b c FinISH
CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; #define tf(IsTrue) ((IsTrue) ? "True" : "False") int main() { uCalc uc; auto t = uc.NewTransformer(); t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH"); auto Pattern = t.Pattern("StArT {etc} FinISH"); Pattern.CaseSensitive(true); cout << "CaseSensitive: " << tf(Pattern.CaseSensitive()) << endl; cout << "-------------------" << endl; t.Find(); cout << t.Matches().Text() << endl; cout << "" << endl; Pattern.CaseSensitive(false); cout << "CaseSensitive: " << tf(Pattern.CaseSensitive()) << endl; cout << "--------------------" << endl; t.Find(); cout << t.Matches().Text() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t = uc.NewTransformer()
t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH")
Dim Pattern = t.Pattern("StArT {etc} FinISH")
Pattern.CaseSensitive = true
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}")
Console.WriteLine("-------------------")
t.Find()
Console.WriteLine(t.Matches.Text)
Console.WriteLine("")
Pattern.CaseSensitive = false
Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}")
Console.WriteLine("--------------------")
t.Find()
Console.WriteLine(t.Matches.Text)
End Sub
End Module
CaseSensitive: True
-------------------
StArT a b c FinISH
CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t = uc.NewTransformer() t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH") Dim Pattern = t.Pattern("StArT {etc} FinISH") Pattern.CaseSensitive = true Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}") Console.WriteLine("-------------------") t.Find() Console.WriteLine(t.Matches.Text) Console.WriteLine("") Pattern.CaseSensitive = false Console.WriteLine($"CaseSensitive: {Pattern.CaseSensitive}") Console.WriteLine("--------------------") t.Find() Console.WriteLine(t.Matches.Text) End Sub End Module
Chains `Before` and `Replace` to modify only the scheme of a URL, demonstrating the live view concept.
ID: 1270
See: Before, Introduction
using uCalcSoftware;
var uc = new uCalc();
using (var url = new uCalc.String("http://example.com")) {
Console.WriteLine($"Original URL: {url}");
// Get a view of the scheme part
var schemeView = url.Before("://");
// Modify the view
schemeView.Replace("http", "https");
// The original string is updated
Console.WriteLine($"Modified URL: {url}");
}
Original URL: http://example.com
Modified URL: https://example.com using uCalcSoftware; var uc = new uCalc(); using (var url = new uCalc.String("http://example.com")) { Console.WriteLine($"Original URL: {url}"); // Get a view of the scheme part var schemeView = url.Before("://"); // Modify the view schemeView.Replace("http", "https"); // The original string is updated Console.WriteLine($"Modified URL: {url}"); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::String url("http://example.com");
url.Owned(); // Causes url to be released when it goes out of scope
cout << "Original URL: " << url << endl;
// Get a view of the scheme part
auto schemeView = url.Before("://");
// Modify the view
schemeView.Replace("http", "https");
// The original string is updated
cout << "Modified URL: " << url << endl;
}
}
Original URL: http://example.com
Modified URL: https://example.com #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::String url("http://example.com"); url.Owned(); // Causes url to be released when it goes out of scope cout << "Original URL: " << url << endl; // Get a view of the scheme part auto schemeView = url.Before("://"); // Modify the view schemeView.Replace("http", "https"); // The original string is updated cout << "Modified URL: " << url << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using url As New uCalc.String("http://example.com")
Console.WriteLine($"Original URL: {url}")
'// Get a view of the scheme part
Dim schemeView = url.Before("://")
'// Modify the view
schemeView.Replace("http", "https")
'// The original string is updated
Console.WriteLine($"Modified URL: {url}")
End Using
End Sub
End Module
Original URL: http://example.com
Modified URL: https://example.com Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using url As New uCalc.String("http://example.com") Console.WriteLine($"Original URL: {url}") '// Get a view of the scheme part Dim schemeView = url.Before("://") '// Modify the view schemeView.Replace("http", "https") '// The original string is updated Console.WriteLine($"Modified URL: {url}") End Using End Sub End Module
Change characters accepted as alphanumeric in expressions using ExpressionTokens() & Token()
ID: 71
using uCalcSoftware;
var uc = new uCalc();
// (See alternate version of this example using ItemOf instead of ExpressionTokens)
// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("Variable123 = 222");
Console.WriteLine(uc.Error.Message);
Console.WriteLine(uc.ExpressionTokens[TokenType.AlphaNumeric].Regex);
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");
// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z]+";
uc.DefineVariable("Other_Variable = 333");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("OtherVariable123 = 444");
Console.WriteLine(uc.Error.Message);
Console.WriteLine(uc.EvalStr("Other_Variable"));
Console.WriteLine(uc.EvalStr("OtherVariable123 "));
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");
// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*";
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222 using uCalcSoftware; var uc = new uCalc(); // (See alternate version of this example using ItemOf instead of ExpressionTokens) // In this section underscore, _, and numeric digits // are accepted as part of alphanumeric tokens uc.DefineVariable("My_Variable = 111"); Console.WriteLine(uc.Error.Message); uc.DefineVariable("Variable123 = 222"); Console.WriteLine(uc.Error.Message); Console.WriteLine(uc.ExpressionTokens[TokenType.AlphaNumeric].Regex); Console.WriteLine(uc.EvalStr("My_Variable")); Console.WriteLine(uc.EvalStr("Variable123")); Console.WriteLine("---"); // Now we no longer want underscore, _, or numeric digits // to be accepted in alphanumeric tokens; only A-Z uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z]+"; uc.DefineVariable("Other_Variable = 333"); Console.WriteLine(uc.Error.Message); uc.DefineVariable("OtherVariable123 = 444"); Console.WriteLine(uc.Error.Message); Console.WriteLine(uc.EvalStr("Other_Variable")); Console.WriteLine(uc.EvalStr("OtherVariable123 ")); Console.WriteLine(uc.EvalStr("My_Variable")); Console.WriteLine(uc.EvalStr("Variable123")); Console.WriteLine("---"); // We restore the alphanumeric regex to support _ and numbers again // Note: My_Variable and Variable123 remained; they were simply inaccessible uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*"; Console.WriteLine(uc.EvalStr("My_Variable")); Console.WriteLine(uc.EvalStr("Variable123"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// (See alternate version of this example using ItemOf instead of ExpressionTokens)
// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
cout << uc.Error().Message() << endl;
uc.DefineVariable("Variable123 = 222");
cout << uc.Error().Message() << endl;
cout << uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex() << endl;
cout << uc.EvalStr("My_Variable") << endl;
cout << uc.EvalStr("Variable123") << endl;
cout << "---" << endl;
// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z]+");
uc.DefineVariable("Other_Variable = 333");
cout << uc.Error().Message() << endl;
uc.DefineVariable("OtherVariable123 = 444");
cout << uc.Error().Message() << endl;
cout << uc.EvalStr("Other_Variable") << endl;
cout << uc.EvalStr("OtherVariable123 ") << endl;
cout << uc.EvalStr("My_Variable") << endl;
cout << uc.EvalStr("Variable123") << endl;
cout << "---" << endl;
// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z_][a-zA-Z0-9_]*");
cout << uc.EvalStr("My_Variable") << endl;
cout << uc.EvalStr("Variable123") << endl;
}
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // (See alternate version of this example using ItemOf instead of ExpressionTokens) // In this section underscore, _, and numeric digits // are accepted as part of alphanumeric tokens uc.DefineVariable("My_Variable = 111"); cout << uc.Error().Message() << endl; uc.DefineVariable("Variable123 = 222"); cout << uc.Error().Message() << endl; cout << uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex() << endl; cout << uc.EvalStr("My_Variable") << endl; cout << uc.EvalStr("Variable123") << endl; cout << "---" << endl; // Now we no longer want underscore, _, or numeric digits // to be accepted in alphanumeric tokens; only A-Z uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z]+"); uc.DefineVariable("Other_Variable = 333"); cout << uc.Error().Message() << endl; uc.DefineVariable("OtherVariable123 = 444"); cout << uc.Error().Message() << endl; cout << uc.EvalStr("Other_Variable") << endl; cout << uc.EvalStr("OtherVariable123 ") << endl; cout << uc.EvalStr("My_Variable") << endl; cout << uc.EvalStr("Variable123") << endl; cout << "---" << endl; // We restore the alphanumeric regex to support _ and numbers again // Note: My_Variable and Variable123 remained; they were simply inaccessible uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z_][a-zA-Z0-9_]*"); cout << uc.EvalStr("My_Variable") << endl; cout << uc.EvalStr("Variable123") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// (See alternate version of this example using ItemOf instead of ExpressionTokens)
'// In this section underscore, _, and numeric digits
'// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111")
Console.WriteLine(uc.Error.Message)
uc.DefineVariable("Variable123 = 222")
Console.WriteLine(uc.Error.Message)
Console.WriteLine(uc.ExpressionTokens(TokenType.AlphaNumeric).Regex)
Console.WriteLine(uc.EvalStr("My_Variable"))
Console.WriteLine(uc.EvalStr("Variable123"))
Console.WriteLine("---")
'// Now we no longer want underscore, _, or numeric digits
'// to be accepted in alphanumeric tokens; only A-Z
uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z]+"
uc.DefineVariable("Other_Variable = 333")
Console.WriteLine(uc.Error.Message)
uc.DefineVariable("OtherVariable123 = 444")
Console.WriteLine(uc.Error.Message)
Console.WriteLine(uc.EvalStr("Other_Variable"))
Console.WriteLine(uc.EvalStr("OtherVariable123 "))
Console.WriteLine(uc.EvalStr("My_Variable"))
Console.WriteLine(uc.EvalStr("Variable123"))
Console.WriteLine("---")
'// We restore the alphanumeric regex to support _ and numbers again
'// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z_][a-zA-Z0-9_]*"
Console.WriteLine(uc.EvalStr("My_Variable"))
Console.WriteLine(uc.EvalStr("Variable123"))
End Sub
End Module
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// (See alternate version of this example using ItemOf instead of ExpressionTokens) '// In this section underscore, _, and numeric digits '// are accepted as part of alphanumeric tokens uc.DefineVariable("My_Variable = 111") Console.WriteLine(uc.Error.Message) uc.DefineVariable("Variable123 = 222") Console.WriteLine(uc.Error.Message) Console.WriteLine(uc.ExpressionTokens(TokenType.AlphaNumeric).Regex) Console.WriteLine(uc.EvalStr("My_Variable")) Console.WriteLine(uc.EvalStr("Variable123")) Console.WriteLine("---") '// Now we no longer want underscore, _, or numeric digits '// to be accepted in alphanumeric tokens; only A-Z uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z]+" uc.DefineVariable("Other_Variable = 333") Console.WriteLine(uc.Error.Message) uc.DefineVariable("OtherVariable123 = 444") Console.WriteLine(uc.Error.Message) Console.WriteLine(uc.EvalStr("Other_Variable")) Console.WriteLine(uc.EvalStr("OtherVariable123 ")) Console.WriteLine(uc.EvalStr("My_Variable")) Console.WriteLine(uc.EvalStr("Variable123")) Console.WriteLine("---") '// We restore the alphanumeric regex to support _ and numbers again '// Note: My_Variable and Variable123 remained; they were simply inaccessible uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z_][a-zA-Z0-9_]*" Console.WriteLine(uc.EvalStr("My_Variable")) Console.WriteLine(uc.EvalStr("Variable123")) End Sub End Module
Change newline from statement separator to whitespace
ID: 220
See: ByName, Whitespace
using uCalcSoftware;
var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("""
a b c
x
y
z
1 2 3
""");
t.Pattern("{body}");
Console.WriteLine("Newline as statement separator (default)");
Console.WriteLine("----------------------------------------");
Console.WriteLine(t.Find().Matches.Text);
Console.WriteLine("");
Console.WriteLine("Newline as whitespace");
Console.WriteLine("---------------------");
t.Tokens["_token_newline"].TypeOfToken = TokenType.Whitespace;
Console.WriteLine(t.Find().Matches.Text);
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>
Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div> using uCalcSoftware; var uc = new uCalc(); var t = uc.NewTransformer(); t.Str(""" <div>a b c</div> <div> x y z </div> <div>1 2 3</div> """); t.Pattern("<div>{body}</div>"); Console.WriteLine("Newline as statement separator (default)"); Console.WriteLine("----------------------------------------"); Console.WriteLine(t.Find().Matches.Text); Console.WriteLine(""); Console.WriteLine("Newline as whitespace"); Console.WriteLine("---------------------"); t.Tokens["_token_newline"].TypeOfToken = TokenType.Whitespace; Console.WriteLine(t.Find().Matches.Text);
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
auto t = uc.NewTransformer();
t.Str(R"(
a b c
x
y
z
1 2 3
)");
t.Pattern("{body}");
cout << "Newline as statement separator (default)" << endl;
cout << "----------------------------------------" << endl;
cout << t.Find().Matches().Text() << endl;
cout << "" << endl;
cout << "Newline as whitespace" << endl;
cout << "---------------------" << endl;
t.Tokens()["_token_newline"].TypeOfToken(TokenType::Whitespace);
cout << t.Find().Matches().Text() << endl;
}
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>
Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div> #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; auto t = uc.NewTransformer(); t.Str(R"( <div>a b c</div> <div> x y z </div> <div>1 2 3</div> )"); t.Pattern("<div>{body}</div>"); cout << "Newline as statement separator (default)" << endl; cout << "----------------------------------------" << endl; cout << t.Find().Matches().Text() << endl; cout << "" << endl; cout << "Newline as whitespace" << endl; cout << "---------------------" << endl; t.Tokens()["_token_newline"].TypeOfToken(TokenType::Whitespace); cout << t.Find().Matches().Text() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t = uc.NewTransformer()
t.Str("
a b c
x
y
z
1 2 3
")
t.Pattern("{body}")
Console.WriteLine("Newline as statement separator (default)")
Console.WriteLine("----------------------------------------")
Console.WriteLine(t.Find().Matches.Text)
Console.WriteLine("")
Console.WriteLine("Newline as whitespace")
Console.WriteLine("---------------------")
t.Tokens("_token_newline").TypeOfToken = TokenType.Whitespace
Console.WriteLine(t.Find().Matches.Text)
End Sub
End Module
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>
Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div> Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t = uc.NewTransformer() t.Str(" <div>a b c</div> <div> x y z </div> <div>1 2 3</div> ") t.Pattern("<div>{body}</div>") Console.WriteLine("Newline as statement separator (default)") Console.WriteLine("----------------------------------------") Console.WriteLine(t.Find().Matches.Text) Console.WriteLine("") Console.WriteLine("Newline as whitespace") Console.WriteLine("---------------------") t.Tokens("_token_newline").TypeOfToken = TokenType.Whitespace Console.WriteLine(t.Find().Matches.Text) End Sub End Module
Change newline from statement separator to whitespace using TypeOfToken
ID: 221
using uCalcSoftware;
var uc = new uCalc();
var t = uc.NewTransformer();
t.Str("""
a b c
x
y
z
1 2 3
""");
t.Pattern("{body}");
var NewLineToken = t.Tokens["_token_newline"];
Console.WriteLine("Newline as statement separator (default)");
Console.WriteLine("----------------------------------------");
Console.WriteLine(t.Find().Matches.Text);
Console.WriteLine("");
Console.WriteLine("Newline as whitespace");
Console.WriteLine("---------------------");
NewLineToken.TypeOfToken = TokenType.Whitespace;
Console.WriteLine(t.Find().Matches.Text);
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>
Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div> using uCalcSoftware; var uc = new uCalc(); var t = uc.NewTransformer(); t.Str(""" <div>a b c</div> <div> x y z </div> <div>1 2 3</div> """); t.Pattern("<div>{body}</div>"); var NewLineToken = t.Tokens["_token_newline"]; Console.WriteLine("Newline as statement separator (default)"); Console.WriteLine("----------------------------------------"); Console.WriteLine(t.Find().Matches.Text); Console.WriteLine(""); Console.WriteLine("Newline as whitespace"); Console.WriteLine("---------------------"); NewLineToken.TypeOfToken = TokenType.Whitespace; Console.WriteLine(t.Find().Matches.Text);
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
auto t = uc.NewTransformer();
t.Str(R"(
a b c
x
y
z
1 2 3
)");
t.Pattern("{body}");
auto NewLineToken = t.Tokens()["_token_newline"];
cout << "Newline as statement separator (default)" << endl;
cout << "----------------------------------------" << endl;
cout << t.Find().Matches().Text() << endl;
cout << "" << endl;
cout << "Newline as whitespace" << endl;
cout << "---------------------" << endl;
NewLineToken.TypeOfToken(TokenType::Whitespace);
cout << t.Find().Matches().Text() << endl;
}
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>
Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div> #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; auto t = uc.NewTransformer(); t.Str(R"( <div>a b c</div> <div> x y z </div> <div>1 2 3</div> )"); t.Pattern("<div>{body}</div>"); auto NewLineToken = t.Tokens()["_token_newline"]; cout << "Newline as statement separator (default)" << endl; cout << "----------------------------------------" << endl; cout << t.Find().Matches().Text() << endl; cout << "" << endl; cout << "Newline as whitespace" << endl; cout << "---------------------" << endl; NewLineToken.TypeOfToken(TokenType::Whitespace); cout << t.Find().Matches().Text() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t = uc.NewTransformer()
t.Str("
a b c
x
y
z
1 2 3
")
t.Pattern("{body}")
Dim NewLineToken = t.Tokens("_token_newline")
Console.WriteLine("Newline as statement separator (default)")
Console.WriteLine("----------------------------------------")
Console.WriteLine(t.Find().Matches.Text)
Console.WriteLine("")
Console.WriteLine("Newline as whitespace")
Console.WriteLine("---------------------")
NewLineToken.TypeOfToken = TokenType.Whitespace
Console.WriteLine(t.Find().Matches.Text)
End Sub
End Module
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>
Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div> Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t = uc.NewTransformer() t.Str(" <div>a b c</div> <div> x y z </div> <div>1 2 3</div> ") t.Pattern("<div>{body}</div>") Dim NewLineToken = t.Tokens("_token_newline") Console.WriteLine("Newline as statement separator (default)") Console.WriteLine("----------------------------------------") Console.WriteLine(t.Find().Matches.Text) Console.WriteLine("") Console.WriteLine("Newline as whitespace") Console.WriteLine("---------------------") NewLineToken.TypeOfToken = TokenType.Whitespace Console.WriteLine(t.Find().Matches.Text) End Sub End Module
Changing accepted tokens with ItemOf().Regex or ExpressionTokens().Token
ID: 72
using uCalcSoftware;
var uc = new uCalc();
// (See alternate version of this example using ExpressionTokens instead of ItemOf)
// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("Variable123 = 222");
Console.WriteLine(uc.Error.Message);
Console.WriteLine(uc.ItemOf("_Token_Alphanumeric").Regex);
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");
// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ItemOf("_Token_Alphanumeric").Regex = "[a-zA-Z]+";
uc.DefineVariable("Other_Variable = 333");
Console.WriteLine(uc.Error.Message);
uc.DefineVariable("OtherVariable123 = 444");
Console.WriteLine(uc.Error.Message);
Console.WriteLine(uc.EvalStr("Other_Variable"));
Console.WriteLine(uc.EvalStr("OtherVariable123 "));
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
Console.WriteLine("---");
//
// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
// Also: We can't use the commented line below because it has the underscore, _,
// character that we had removed.
// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*";
Console.WriteLine(uc.EvalStr("My_Variable"));
Console.WriteLine(uc.EvalStr("Variable123"));
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222 using uCalcSoftware; var uc = new uCalc(); // (See alternate version of this example using ExpressionTokens instead of ItemOf) // In this section underscore, _, and numeric digits // are accepted as part of alphanumeric tokens uc.DefineVariable("My_Variable = 111"); Console.WriteLine(uc.Error.Message); uc.DefineVariable("Variable123 = 222"); Console.WriteLine(uc.Error.Message); Console.WriteLine(uc.ItemOf("_Token_Alphanumeric").Regex); Console.WriteLine(uc.EvalStr("My_Variable")); Console.WriteLine(uc.EvalStr("Variable123")); Console.WriteLine("---"); // Now we no longer want underscore, _, or numeric digits // to be accepted in alphanumeric tokens; only A-Z uc.ItemOf("_Token_Alphanumeric").Regex = "[a-zA-Z]+"; uc.DefineVariable("Other_Variable = 333"); Console.WriteLine(uc.Error.Message); uc.DefineVariable("OtherVariable123 = 444"); Console.WriteLine(uc.Error.Message); Console.WriteLine(uc.EvalStr("Other_Variable")); Console.WriteLine(uc.EvalStr("OtherVariable123 ")); Console.WriteLine(uc.EvalStr("My_Variable")); Console.WriteLine(uc.EvalStr("Variable123")); Console.WriteLine("---"); // // We restore the alphanumeric regex to support _ and numbers again // Note: My_Variable and Variable123 remained; they were simply inaccessible // Also: We can't use the commented line below because it has the underscore, _, // character that we had removed. // uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*"); uc.ExpressionTokens[TokenType.AlphaNumeric].Regex = "[a-zA-Z_][a-zA-Z0-9_]*"; Console.WriteLine(uc.EvalStr("My_Variable")); Console.WriteLine(uc.EvalStr("Variable123"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// (See alternate version of this example using ExpressionTokens instead of ItemOf)
// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
cout << uc.Error().Message() << endl;
uc.DefineVariable("Variable123 = 222");
cout << uc.Error().Message() << endl;
cout << uc.ItemOf("_Token_Alphanumeric").Regex() << endl;
cout << uc.EvalStr("My_Variable") << endl;
cout << uc.EvalStr("Variable123") << endl;
cout << "---" << endl;
// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ItemOf("_Token_Alphanumeric").Regex("[a-zA-Z]+");
uc.DefineVariable("Other_Variable = 333");
cout << uc.Error().Message() << endl;
uc.DefineVariable("OtherVariable123 = 444");
cout << uc.Error().Message() << endl;
cout << uc.EvalStr("Other_Variable") << endl;
cout << uc.EvalStr("OtherVariable123 ") << endl;
cout << uc.EvalStr("My_Variable") << endl;
cout << uc.EvalStr("Variable123") << endl;
cout << "---" << endl;
//
// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
// Also: We can't use the commented line below because it has the underscore, _,
// character that we had removed.
// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z_][a-zA-Z0-9_]*");
cout << uc.EvalStr("My_Variable") << endl;
cout << uc.EvalStr("Variable123") << endl;
}
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // (See alternate version of this example using ExpressionTokens instead of ItemOf) // In this section underscore, _, and numeric digits // are accepted as part of alphanumeric tokens uc.DefineVariable("My_Variable = 111"); cout << uc.Error().Message() << endl; uc.DefineVariable("Variable123 = 222"); cout << uc.Error().Message() << endl; cout << uc.ItemOf("_Token_Alphanumeric").Regex() << endl; cout << uc.EvalStr("My_Variable") << endl; cout << uc.EvalStr("Variable123") << endl; cout << "---" << endl; // Now we no longer want underscore, _, or numeric digits // to be accepted in alphanumeric tokens; only A-Z uc.ItemOf("_Token_Alphanumeric").Regex("[a-zA-Z]+"); uc.DefineVariable("Other_Variable = 333"); cout << uc.Error().Message() << endl; uc.DefineVariable("OtherVariable123 = 444"); cout << uc.Error().Message() << endl; cout << uc.EvalStr("Other_Variable") << endl; cout << uc.EvalStr("OtherVariable123 ") << endl; cout << uc.EvalStr("My_Variable") << endl; cout << uc.EvalStr("Variable123") << endl; cout << "---" << endl; // // We restore the alphanumeric regex to support _ and numbers again // Note: My_Variable and Variable123 remained; they were simply inaccessible // Also: We can't use the commented line below because it has the underscore, _, // character that we had removed. // uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*"); uc.ExpressionTokens()[TokenType::AlphaNumeric].Regex("[a-zA-Z_][a-zA-Z0-9_]*"); cout << uc.EvalStr("My_Variable") << endl; cout << uc.EvalStr("Variable123") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// (See alternate version of this example using ExpressionTokens instead of ItemOf)
'// In this section underscore, _, and numeric digits
'// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111")
Console.WriteLine(uc.Error.Message)
uc.DefineVariable("Variable123 = 222")
Console.WriteLine(uc.Error.Message)
Console.WriteLine(uc.ItemOf("_Token_Alphanumeric").Regex)
Console.WriteLine(uc.EvalStr("My_Variable"))
Console.WriteLine(uc.EvalStr("Variable123"))
Console.WriteLine("---")
'// Now we no longer want underscore, _, or numeric digits
'// to be accepted in alphanumeric tokens; only A-Z
uc.ItemOf("_Token_Alphanumeric").Regex = "[a-zA-Z]+"
uc.DefineVariable("Other_Variable = 333")
Console.WriteLine(uc.Error.Message)
uc.DefineVariable("OtherVariable123 = 444")
Console.WriteLine(uc.Error.Message)
Console.WriteLine(uc.EvalStr("Other_Variable"))
Console.WriteLine(uc.EvalStr("OtherVariable123 "))
Console.WriteLine(uc.EvalStr("My_Variable"))
Console.WriteLine(uc.EvalStr("Variable123"))
Console.WriteLine("---")
'//
'// We restore the alphanumeric regex to support _ and numbers again
'// Note: My_Variable and Variable123 remained; they were simply inaccessible
'// Also: We can't use the commented line below because it has the underscore, _,
'// character that we had removed.
'// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z_][a-zA-Z0-9_]*"
Console.WriteLine(uc.EvalStr("My_Variable"))
Console.WriteLine(uc.EvalStr("Variable123"))
End Sub
End Module
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// (See alternate version of this example using ExpressionTokens instead of ItemOf) '// In this section underscore, _, and numeric digits '// are accepted as part of alphanumeric tokens uc.DefineVariable("My_Variable = 111") Console.WriteLine(uc.Error.Message) uc.DefineVariable("Variable123 = 222") Console.WriteLine(uc.Error.Message) Console.WriteLine(uc.ItemOf("_Token_Alphanumeric").Regex) Console.WriteLine(uc.EvalStr("My_Variable")) Console.WriteLine(uc.EvalStr("Variable123")) Console.WriteLine("---") '// Now we no longer want underscore, _, or numeric digits '// to be accepted in alphanumeric tokens; only A-Z uc.ItemOf("_Token_Alphanumeric").Regex = "[a-zA-Z]+" uc.DefineVariable("Other_Variable = 333") Console.WriteLine(uc.Error.Message) uc.DefineVariable("OtherVariable123 = 444") Console.WriteLine(uc.Error.Message) Console.WriteLine(uc.EvalStr("Other_Variable")) Console.WriteLine(uc.EvalStr("OtherVariable123 ")) Console.WriteLine(uc.EvalStr("My_Variable")) Console.WriteLine(uc.EvalStr("Variable123")) Console.WriteLine("---") '// '// We restore the alphanumeric regex to support _ and numbers again '// Note: My_Variable and Variable123 remained; they were simply inaccessible '// Also: We can't use the commented line below because it has the underscore, _, '// character that we had removed. '// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*"); uc.ExpressionTokens(TokenType.AlphaNumeric).Regex = "[a-zA-Z_][a-zA-Z0-9_]*" Console.WriteLine(uc.EvalStr("My_Variable")) Console.WriteLine(uc.EvalStr("Variable123")) End Sub End Module
Changing an item's property
ID: 101
using uCalcSoftware;
var uc = new uCalc();
var MyVar = uc.DefineVariable("x = 100");
Console.WriteLine(uc.EvalStr("x"));
uc.EvalStr("x = 200");
Console.WriteLine(uc.EvalStr("x")); // x can change here
// Locking an item prevents it from being changed
MyVar.IsProperty(ItemIs.Locked, true);
uc.EvalStr("x = 300"); // x cannot change here
Console.WriteLine(uc.EvalStr("x")); // x retains the previous value
100
200
200 using uCalcSoftware; var uc = new uCalc(); var MyVar = uc.DefineVariable("x = 100"); Console.WriteLine(uc.EvalStr("x")); uc.EvalStr("x = 200"); Console.WriteLine(uc.EvalStr("x")); // x can change here // Locking an item prevents it from being changed MyVar.IsProperty(ItemIs.Locked, true); uc.EvalStr("x = 300"); // x cannot change here Console.WriteLine(uc.EvalStr("x")); // x retains the previous value
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
auto MyVar = uc.DefineVariable("x = 100");
cout << uc.EvalStr("x") << endl;
uc.EvalStr("x = 200");
cout << uc.EvalStr("x") << endl; // x can change here
// Locking an item prevents it from being changed
MyVar.IsProperty(ItemIs::Locked, true);
uc.EvalStr("x = 300"); // x cannot change here
cout << uc.EvalStr("x") << endl; // x retains the previous value
}
100
200
200 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; auto MyVar = uc.DefineVariable("x = 100"); cout << uc.EvalStr("x") << endl; uc.EvalStr("x = 200"); cout << uc.EvalStr("x") << endl; // x can change here // Locking an item prevents it from being changed MyVar.IsProperty(ItemIs::Locked, true); uc.EvalStr("x = 300"); // x cannot change here cout << uc.EvalStr("x") << endl; // x retains the previous value }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim MyVar = uc.DefineVariable("x = 100")
Console.WriteLine(uc.EvalStr("x"))
uc.EvalStr("x = 200")
Console.WriteLine(uc.EvalStr("x")) '// x can change here
'// Locking an item prevents it from being changed
MyVar.IsProperty(ItemIs.Locked, true)
uc.EvalStr("x = 300") '// x cannot change here
Console.WriteLine(uc.EvalStr("x")) '// x retains the previous value
End Sub
End Module
100
200
200 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim MyVar = uc.DefineVariable("x = 100") Console.WriteLine(uc.EvalStr("x")) uc.EvalStr("x = 200") Console.WriteLine(uc.EvalStr("x")) '// x can change here '// Locking an item prevents it from being changed MyVar.IsProperty(ItemIs.Locked, true) uc.EvalStr("x = 300") '// x cannot change here Console.WriteLine(uc.EvalStr("x")) '// x retains the previous value End Sub End Module
Changing the parent uCalc object for a Transformer
ID: 160
using uCalcSoftware;
var uc = new uCalc();
uc.DefineVariable("x = 1");
uc.DefineVariable("y = 2");
uc.DefineFunction("f(x) = x * 10");
var t = uc.NewTransformer();
var text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}";
var uNew = new uCalc();
uNew.DefineVariable("x = 111");
uNew.DefineVariable("y = 222");
uNew.DefineFunction("f(x) = x * 1000");
// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
// which is what's needed for to evaluate the expression
// resulting from the match that is not known ahead of time
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
Console.WriteLine(t.Transform(text));
t.uCalc = uNew;
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
Console.WriteLine(t.Transform(text));
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000 using uCalcSoftware; var uc = new uCalc(); uc.DefineVariable("x = 1"); uc.DefineVariable("y = 2"); uc.DefineFunction("f(x) = x * 10"); var t = uc.NewTransformer(); var text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}"; var uNew = new uCalc(); uNew.DefineVariable("x = 111"); uNew.DefineVariable("y = 222"); uNew.DefineFunction("f(x) = x * 1000"); // Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)} // which is what's needed for to evaluate the expression // resulting from the match that is not known ahead of time t.FromTo("'{' {expr} '}'", "{@@Eval: expr}"); Console.WriteLine(t.Transform(text)); t.uCalc = uNew; t.FromTo("'{' {expr} '}'", "{@@Eval: expr}"); Console.WriteLine(t.Transform(text));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uc.DefineVariable("x = 1");
uc.DefineVariable("y = 2");
uc.DefineFunction("f(x) = x * 10");
auto t = uc.NewTransformer();
auto text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}";
uCalc uNew;
uNew.DefineVariable("x = 111");
uNew.DefineVariable("y = 222");
uNew.DefineFunction("f(x) = x * 1000");
// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
// which is what's needed for to evaluate the expression
// resulting from the match that is not known ahead of time
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
cout << t.Transform(text) << endl;
t.uCalc(uNew);
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
cout << t.Transform(text) << endl;
}
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uc.DefineVariable("x = 1"); uc.DefineVariable("y = 2"); uc.DefineFunction("f(x) = x * 10"); auto t = uc.NewTransformer(); auto text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}"; uCalc uNew; uNew.DefineVariable("x = 111"); uNew.DefineVariable("y = 222"); uNew.DefineFunction("f(x) = x * 1000"); // Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)} // which is what's needed for to evaluate the expression // resulting from the match that is not known ahead of time t.FromTo("'{' {expr} '}'", "{@@Eval: expr}"); cout << t.Transform(text) << endl; t.uCalc(uNew); t.FromTo("'{' {expr} '}'", "{@@Eval: expr}"); cout << t.Transform(text) << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
uc.DefineVariable("x = 1")
uc.DefineVariable("y = 2")
uc.DefineFunction("f(x) = x * 10")
Dim t = uc.NewTransformer()
Dim text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}"
Dim uNew As New uCalc()
uNew.DefineVariable("x = 111")
uNew.DefineVariable("y = 222")
uNew.DefineFunction("f(x) = x * 1000")
'// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
'// which is what's needed for to evaluate the expression
'// resulting from the match that is not known ahead of time
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}")
Console.WriteLine(t.Transform(text))
t.uCalc = uNew
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}")
Console.WriteLine(t.Transform(text))
End Sub
End Module
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() uc.DefineVariable("x = 1") uc.DefineVariable("y = 2") uc.DefineFunction("f(x) = x * 10") Dim t = uc.NewTransformer() Dim text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}" Dim uNew As New uCalc() uNew.DefineVariable("x = 111") uNew.DefineVariable("y = 222") uNew.DefineFunction("f(x) = x * 1000") '// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)} '// which is what's needed for to evaluate the expression '// resulting from the match that is not known ahead of time t.FromTo("'{' {expr} '}'", "{@@Eval: expr}") Console.WriteLine(t.Transform(text)) t.uCalc = uNew t.FromTo("'{' {expr} '}'", "{@@Eval: expr}") Console.WriteLine(t.Transform(text)) End Sub End Module
Checking if a uCalc object is the default with IsDefault
ID: 75
using uCalcSoftware;
var uc = new uCalc();
var Status = uc.DefineVariable("Status As Bool");
Console.WriteLine(Status.ValueBool());
var MyuCalc = new uCalc();
Status.ValueBool(MyuCalc.IsDefault);
Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"));
MyuCalc.IsDefault = true;
Status.ValueBool(MyuCalc.IsDefault);
Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"));
False
MyuCalc is the current default? false
MyuCalc is the current default? true using uCalcSoftware; var uc = new uCalc(); var Status = uc.DefineVariable("Status As Bool"); Console.WriteLine(Status.ValueBool()); var MyuCalc = new uCalc(); Status.ValueBool(MyuCalc.IsDefault); Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'")); MyuCalc.IsDefault = true; Status.ValueBool(MyuCalc.IsDefault); Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
#define tf(IsTrue) ((IsTrue) ? "True" : "False")
int main() {
uCalc uc;
auto Status = uc.DefineVariable("Status As Bool");
cout << tf(Status.ValueBool()) << endl;
uCalc MyuCalc;
Status.ValueBool(MyuCalc.IsDefault());
cout << uc.EvalStr("$'MyuCalc is the current default? {Status}'") << endl;
MyuCalc.IsDefault(true);
Status.ValueBool(MyuCalc.IsDefault());
cout << uc.EvalStr("$'MyuCalc is the current default? {Status}'") << endl;
}
False
MyuCalc is the current default? false
MyuCalc is the current default? true #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; #define tf(IsTrue) ((IsTrue) ? "True" : "False") int main() { uCalc uc; auto Status = uc.DefineVariable("Status As Bool"); cout << tf(Status.ValueBool()) << endl; uCalc MyuCalc; Status.ValueBool(MyuCalc.IsDefault()); cout << uc.EvalStr("$'MyuCalc is the current default? {Status}'") << endl; MyuCalc.IsDefault(true); Status.ValueBool(MyuCalc.IsDefault()); cout << uc.EvalStr("$'MyuCalc is the current default? {Status}'") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim Status = uc.DefineVariable("Status As Bool")
Console.WriteLine(Status.ValueBool())
Dim MyuCalc As New uCalc()
Status.ValueBool(MyuCalc.IsDefault)
Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
MyuCalc.IsDefault = true
Status.ValueBool(MyuCalc.IsDefault)
Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
End Sub
End Module
False
MyuCalc is the current default? false
MyuCalc is the current default? true Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim Status = uc.DefineVariable("Status As Bool") Console.WriteLine(Status.ValueBool()) Dim MyuCalc As New uCalc() Status.ValueBool(MyuCalc.IsDefault) Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'")) MyuCalc.IsDefault = true Status.ValueBool(MyuCalc.IsDefault) Console.WriteLine(uc.EvalStr("$'MyuCalc is the current default? {Status}'")) End Sub End Module
Checking the error code for a simple syntax error
ID: 1457
using uCalcSoftware;
var uc = new uCalc();
var result = uc.Eval("MyVar * 10");
Console.WriteLine("An error has occurred!");
Console.WriteLine($"Error #: {(int)uc.Error.Code}");
Console.WriteLine($"Error Message: {uc.Error.Message}");
Console.WriteLine($"Error Location: {uc.Error.Location}");
Console.WriteLine($"Error Expression: {uc.Error.Expression}");
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10 using uCalcSoftware; var uc = new uCalc(); var result = uc.Eval("MyVar * 10"); Console.WriteLine("An error has occurred!"); Console.WriteLine($"Error #: {(int)uc.Error.Code}"); Console.WriteLine($"Error Message: {uc.Error.Message}"); Console.WriteLine($"Error Location: {uc.Error.Location}"); Console.WriteLine($"Error Expression: {uc.Error.Expression}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
auto result = uc.Eval("MyVar * 10");
cout << "An error has occurred!" << endl;
cout << "Error #: " << (int)uc.Error().Code() << endl;
cout << "Error Message: " << uc.Error().Message() << endl;
cout << "Error Location: " << uc.Error().Location() << endl;
cout << "Error Expression: " << uc.Error().Expression() << endl;
}
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; auto result = uc.Eval("MyVar * 10"); cout << "An error has occurred!" << endl; cout << "Error #: " << (int)uc.Error().Code() << endl; cout << "Error Message: " << uc.Error().Message() << endl; cout << "Error Location: " << uc.Error().Location() << endl; cout << "Error Expression: " << uc.Error().Expression() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim result = uc.Eval("MyVar * 10")
Console.WriteLine("An error has occurred!")
Console.WriteLine($"Error #: {CInt(uc.Error.Code)}")
Console.WriteLine($"Error Message: {uc.Error.Message}")
Console.WriteLine($"Error Location: {uc.Error.Location}")
Console.WriteLine($"Error Expression: {uc.Error.Expression}")
End Sub
End Module
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim result = uc.Eval("MyVar * 10") Console.WriteLine("An error has occurred!") Console.WriteLine($"Error #: {CInt(uc.Error.Code)}") Console.WriteLine($"Error Message: {uc.Error.Message}") Console.WriteLine($"Error Location: {uc.Error.Location}") Console.WriteLine($"Error Expression: {uc.Error.Expression}") End Sub End Module
Checking the error code for a simple syntax error using a callback.
ID: 325
using uCalcSoftware;
var uc = new uCalc();
static void MyHandler(Handle_uCalc h) {
var uc = new uCalc(h);
// Retrieve the error code as an integer for display
int code = (int)uc.Error.Code;
Console.WriteLine($"Caught Error Code: {code}");
// Compare the error code against the ErrorCode enum for logic
if (uc.Error.Code == ErrorCode.Syntax_Error) {
Console.WriteLine("This was a syntax error.");
}
}
// Register the error handler
uc.Error.AddHandler(MyHandler);
// Intentionally cause a syntax error, which will trigger the handler
Console.WriteLine(uc.EvalStr("5 *"));
Caught Error Code: 257
This was a syntax error.
Syntax error using uCalcSoftware; var uc = new uCalc(); static void MyHandler(Handle_uCalc h) { var uc = new uCalc(h); // Retrieve the error code as an integer for display int code = (int)uc.Error.Code; Console.WriteLine($"Caught Error Code: {code}"); // Compare the error code against the ErrorCode enum for logic if (uc.Error.Code == ErrorCode.Syntax_Error) { Console.WriteLine("This was a syntax error."); } } // Register the error handler uc.Error.AddHandler(MyHandler); // Intentionally cause a syntax error, which will trigger the handler Console.WriteLine(uc.EvalStr("5 *"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call MyHandler(Handle_uCalc h) {
auto uc = uCalc(h);
// Retrieve the error code as an integer for display
int code = (int)uc.Error().Code();
cout << "Caught Error Code: " << code << endl;
// Compare the error code against the ErrorCode enum for logic
if (uc.Error().Code() == ErrorCode::Syntax_Error) {
cout << "This was a syntax error." << endl;
}
}
int main() {
uCalc uc;
// Register the error handler
uc.Error().AddHandler(MyHandler);
// Intentionally cause a syntax error, which will trigger the handler
cout << uc.EvalStr("5 *") << endl;
}
Caught Error Code: 257
This was a syntax error.
Syntax error #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call MyHandler(Handle_uCalc h) { auto uc = uCalc(h); // Retrieve the error code as an integer for display int code = (int)uc.Error().Code(); cout << "Caught Error Code: " << code << endl; // Compare the error code against the ErrorCode enum for logic if (uc.Error().Code() == ErrorCode::Syntax_Error) { cout << "This was a syntax error." << endl; } } int main() { uCalc uc; // Register the error handler uc.Error().AddHandler(MyHandler); // Intentionally cause a syntax error, which will trigger the handler cout << uc.EvalStr("5 *") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub MyHandler(ByVal h As Handle_uCalc)
Dim uc As New uCalc(h)
'// Retrieve the error code as an integer for display
Dim code As Integer = uc.Error.Code
Console.WriteLine($"Caught Error Code: {code}")
'// Compare the error code against the ErrorCode enum for logic
If uc.Error.Code = ErrorCode.Syntax_Error Then
Console.WriteLine("This was a syntax error.")
End If
End Sub
Public Sub Main()
Dim uc As New uCalc()
'// Register the error handler
uc.Error.AddHandler(AddressOf MyHandler)
'// Intentionally cause a syntax error, which will trigger the handler
Console.WriteLine(uc.EvalStr("5 *"))
End Sub
End Module
Caught Error Code: 257
This was a syntax error.
Syntax error Imports System Imports uCalcSoftware Public Module Program Public Sub MyHandler(ByVal h As Handle_uCalc) Dim uc As New uCalc(h) '// Retrieve the error code as an integer for display Dim code As Integer = uc.Error.Code Console.WriteLine($"Caught Error Code: {code}") '// Compare the error code against the ErrorCode enum for logic If uc.Error.Code = ErrorCode.Syntax_Error Then Console.WriteLine("This was a syntax error.") End If End Sub Public Sub Main() Dim uc As New uCalc() '// Register the error handler uc.Error.AddHandler(AddressOf MyHandler) '// Intentionally cause a syntax error, which will trigger the handler Console.WriteLine(uc.EvalStr("5 *")) End Sub End Module
Checking variable types against BuiltInType
ID: 278
using uCalcSoftware;
var uc = new uCalc();
// Define a variable with a specific type
uc.DefineVariable("myVar As Int16");
// Retrieve the generic Int16 type object
var typeObj = uc.DataTypeOf(BuiltInType.Integer_16);
// Check if the variable's type matches Int16
if (uc.ItemOf("myVar").DataType.BuiltInTypeEnum == typeObj.BuiltInTypeEnum) {
Console.WriteLine("Variable 'myVar' is an Int16.");
} else {
Console.WriteLine("Type mismatch.");
}
Variable 'myVar' is an Int16. using uCalcSoftware; var uc = new uCalc(); // Define a variable with a specific type uc.DefineVariable("myVar As Int16"); // Retrieve the generic Int16 type object var typeObj = uc.DataTypeOf(BuiltInType.Integer_16); // Check if the variable's type matches Int16 if (uc.ItemOf("myVar").DataType.BuiltInTypeEnum == typeObj.BuiltInTypeEnum) { Console.WriteLine("Variable 'myVar' is an Int16."); } else { Console.WriteLine("Type mismatch."); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// Define a variable with a specific type
uc.DefineVariable("myVar As Int16");
// Retrieve the generic Int16 type object
auto typeObj = uc.DataTypeOf(BuiltInType::Integer_16);
// Check if the variable's type matches Int16
if (uc.ItemOf("myVar").DataType().BuiltInTypeEnum() == typeObj.BuiltInTypeEnum()) {
cout << "Variable 'myVar' is an Int16." << endl;
} else {
cout << "Type mismatch." << endl;
}
}
Variable 'myVar' is an Int16. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // Define a variable with a specific type uc.DefineVariable("myVar As Int16"); // Retrieve the generic Int16 type object auto typeObj = uc.DataTypeOf(BuiltInType::Integer_16); // Check if the variable's type matches Int16 if (uc.ItemOf("myVar").DataType().BuiltInTypeEnum() == typeObj.BuiltInTypeEnum()) { cout << "Variable 'myVar' is an Int16." << endl; } else { cout << "Type mismatch." << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// Define a variable with a specific type
uc.DefineVariable("myVar As Int16")
'// Retrieve the generic Int16 type object
Dim typeObj = uc.DataTypeOf(BuiltInType.Integer_16)
'// Check if the variable's type matches Int16
If uc.ItemOf("myVar").DataType.BuiltInTypeEnum = typeObj.BuiltInTypeEnum Then
Console.WriteLine("Variable 'myVar' is an Int16.")
Else
Console.WriteLine("Type mismatch.")
End If
End Sub
End Module
Variable 'myVar' is an Int16. Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// Define a variable with a specific type uc.DefineVariable("myVar As Int16") '// Retrieve the generic Int16 type object Dim typeObj = uc.DataTypeOf(BuiltInType.Integer_16) '// Check if the variable's type matches Int16 If uc.ItemOf("myVar").DataType.BuiltInTypeEnum = typeObj.BuiltInTypeEnum Then Console.WriteLine("Variable 'myVar' is an Int16.") Else Console.WriteLine("Type mismatch.") End If End Sub End Module
Checks for the existence of a required header in a string.
ID: 1341
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
var text_ok = "Header: OK";
var text_fail = "Header: ERROR";
// This rule only matches if the status is "OK"
t.Pattern("Header: OK");
// Find() returns the transformer, so we can chain Matches().Count()
if (t.SetText(text_ok).Find().Matches.Count() > 0) {
Console.WriteLine("text_ok is valid.");
}
if (t.SetText(text_fail).Find().Matches.Count() == 0) {
Console.WriteLine("text_fail is invalid.");
}
}
text_ok is valid.
text_fail is invalid. using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer()) { var text_ok = "Header: OK"; var text_fail = "Header: ERROR"; // This rule only matches if the status is "OK" t.Pattern("Header: OK"); // Find() returns the transformer, so we can chain Matches().Count() if (t.SetText(text_ok).Find().Matches.Count() > 0) { Console.WriteLine("text_ok is valid."); } if (t.SetText(text_fail).Find().Matches.Count() == 0) { Console.WriteLine("text_fail is invalid."); } }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::Transformer t;
t.Owned(); // Causes t to be released when it goes out of scope
auto text_ok = "Header: OK";
auto text_fail = "Header: ERROR";
// This rule only matches if the status is "OK"
t.Pattern("Header: OK");
// Find() returns the transformer, so we can chain Matches().Count()
if (t.SetText(text_ok).Find().Matches().Count() > 0) {
cout << "text_ok is valid." << endl;
}
if (t.SetText(text_fail).Find().Matches().Count() == 0) {
cout << "text_fail is invalid." << endl;
}
}
}
text_ok is valid.
text_fail is invalid. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::Transformer t; t.Owned(); // Causes t to be released when it goes out of scope auto text_ok = "Header: OK"; auto text_fail = "Header: ERROR"; // This rule only matches if the status is "OK" t.Pattern("Header: OK"); // Find() returns the transformer, so we can chain Matches().Count() if (t.SetText(text_ok).Find().Matches().Count() > 0) { cout << "text_ok is valid." << endl; } if (t.SetText(text_fail).Find().Matches().Count() == 0) { cout << "text_fail is invalid." << endl; } } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer()
Dim text_ok = "Header: OK"
Dim text_fail = "Header: ERROR"
'// This rule only matches if the status is "OK"
t.Pattern("Header: OK")
'// Find() returns the transformer, so we can chain Matches().Count()
If t.SetText(text_ok).Find().Matches.Count() > 0 Then
Console.WriteLine("text_ok is valid.")
End If
If t.SetText(text_fail).Find().Matches.Count() = 0 Then
Console.WriteLine("text_fail is invalid.")
End If
End Using
End Sub
End Module
text_ok is valid.
text_fail is invalid. Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer() Dim text_ok = "Header: OK" Dim text_fail = "Header: ERROR" '// This rule only matches if the status is "OK" t.Pattern("Header: OK") '// Find() returns the transformer, so we can chain Matches().Count() If t.SetText(text_ok).Find().Matches.Count() > 0 Then Console.WriteLine("text_ok is valid.") End If If t.SetText(text_fail).Find().Matches.Count() = 0 Then Console.WriteLine("text_fail is invalid.") End If End Using End Sub End Module
Checks for the existence of a required header in a string.
ID: 1449
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
var text_ok = "Header: OK";
var text_fail = "Header: ERROR";
// This rule only matches if the status is "OK"
t.Pattern("Header: OK");
// Find() returns the transformer, so we can chain Matches().Count()
if (t.SetText(text_ok).Find().Matches.Count() > 0) {
Console.WriteLine("text_ok is valid.");
}
if (t.SetText(text_fail).Find().Matches.Count() == 0) {
Console.WriteLine("text_fail is invalid.");
}
}
text_ok is valid.
text_fail is invalid. using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer()) { var text_ok = "Header: OK"; var text_fail = "Header: ERROR"; // This rule only matches if the status is "OK" t.Pattern("Header: OK"); // Find() returns the transformer, so we can chain Matches().Count() if (t.SetText(text_ok).Find().Matches.Count() > 0) { Console.WriteLine("text_ok is valid."); } if (t.SetText(text_fail).Find().Matches.Count() == 0) { Console.WriteLine("text_fail is invalid."); } }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::Transformer t;
t.Owned(); // Causes t to be released when it goes out of scope
auto text_ok = "Header: OK";
auto text_fail = "Header: ERROR";
// This rule only matches if the status is "OK"
t.Pattern("Header: OK");
// Find() returns the transformer, so we can chain Matches().Count()
if (t.SetText(text_ok).Find().Matches().Count() > 0) {
cout << "text_ok is valid." << endl;
}
if (t.SetText(text_fail).Find().Matches().Count() == 0) {
cout << "text_fail is invalid." << endl;
}
}
}
text_ok is valid.
text_fail is invalid. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::Transformer t; t.Owned(); // Causes t to be released when it goes out of scope auto text_ok = "Header: OK"; auto text_fail = "Header: ERROR"; // This rule only matches if the status is "OK" t.Pattern("Header: OK"); // Find() returns the transformer, so we can chain Matches().Count() if (t.SetText(text_ok).Find().Matches().Count() > 0) { cout << "text_ok is valid." << endl; } if (t.SetText(text_fail).Find().Matches().Count() == 0) { cout << "text_fail is invalid." << endl; } } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer()
Dim text_ok = "Header: OK"
Dim text_fail = "Header: ERROR"
'// This rule only matches if the status is "OK"
t.Pattern("Header: OK")
'// Find() returns the transformer, so we can chain Matches().Count()
If t.SetText(text_ok).Find().Matches.Count() > 0 Then
Console.WriteLine("text_ok is valid.")
End If
If t.SetText(text_fail).Find().Matches.Count() = 0 Then
Console.WriteLine("text_fail is invalid.")
End If
End Using
End Sub
End Module
text_ok is valid.
text_fail is invalid. Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer() Dim text_ok = "Header: OK" Dim text_fail = "Header: ERROR" '// This rule only matches if the status is "OK" t.Pattern("Header: OK") '// Find() returns the transformer, so we can chain Matches().Count() If t.SetText(text_ok).Find().Matches.Count() > 0 Then Console.WriteLine("text_ok is valid.") End If If t.SetText(text_fail).Find().Matches.Count() = 0 Then Console.WriteLine("text_fail is invalid.") End If End Using End Sub End Module
Comprehensive demonstration of Count() across arrays, functions with different parameter types, and operators.
ID: 611
See: Count = [Int64]
using uCalcSoftware;
var uc = new uCalc();
static void MyAverage(uCalc.Callback cb) {
double Total = 0;
for (int x = 1; x <= cb.ArgCount(); x++) {
Total = Total + cb.Arg(x);
}
cb.Return(Total / cb.ArgCount());
}
var MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
var MyArrayB = uc.DefineVariable("MyArrayB[15]");
var FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
var FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
var FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
var FunctionD = uc.DefineFunction("FuncD() = 1+1");
Console.WriteLine($"Elements in array (from initializer): {MyArrayA.Count}");
Console.WriteLine($"Elements in array (from size): {MyArrayB.Count}");
Console.WriteLine($"Parameters in FuncA() (fixed): {FunctionA.Count}");
Console.WriteLine($"Parameters in FuncB() (with optional): {FunctionB.Count}");
Console.WriteLine($"Parameters in FuncC() (variadic): {FunctionC.Count}");
Console.WriteLine($"Parameters in FuncD() (none): {FunctionD.Count}");
Console.WriteLine($"Operands in '!' operator (postfix): {uc.ItemOf("!").Count}");
Console.WriteLine($"Operands in '>' operator (infix): {uc.ItemOf(">").Count}");
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2 using uCalcSoftware; var uc = new uCalc(); static void MyAverage(uCalc.Callback cb) { double Total = 0; for (int x = 1; x <= cb.ArgCount(); x++) { Total = Total + cb.Arg(x); } cb.Return(Total / cb.ArgCount()); } var MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}"); var MyArrayB = uc.DefineVariable("MyArrayB[15]"); var FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z"); var FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b"); var FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage); var FunctionD = uc.DefineFunction("FuncD() = 1+1"); Console.WriteLine($"Elements in array (from initializer): {MyArrayA.Count}"); Console.WriteLine($"Elements in array (from size): {MyArrayB.Count}"); Console.WriteLine($"Parameters in FuncA() (fixed): {FunctionA.Count}"); Console.WriteLine($"Parameters in FuncB() (with optional): {FunctionB.Count}"); Console.WriteLine($"Parameters in FuncC() (variadic): {FunctionC.Count}"); Console.WriteLine($"Parameters in FuncD() (none): {FunctionD.Count}"); Console.WriteLine($"Operands in '!' operator (postfix): {uc.ItemOf("!").Count}"); Console.WriteLine($"Operands in '>' operator (infix): {uc.ItemOf(">").Count}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call MyAverage(uCalcBase::Callback cb) {
double Total = 0;
for (int x = 1; x <= cb.ArgCount(); x++) {
Total = Total + cb.Arg(x);
}
cb.Return(Total / cb.ArgCount());
}
int main() {
uCalc uc;
auto MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
auto MyArrayB = uc.DefineVariable("MyArrayB[15]");
auto FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
auto FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
auto FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
auto FunctionD = uc.DefineFunction("FuncD() = 1+1");
cout << "Elements in array (from initializer): " << MyArrayA.Count() << endl;
cout << "Elements in array (from size): " << MyArrayB.Count() << endl;
cout << "Parameters in FuncA() (fixed): " << FunctionA.Count() << endl;
cout << "Parameters in FuncB() (with optional): " << FunctionB.Count() << endl;
cout << "Parameters in FuncC() (variadic): " << FunctionC.Count() << endl;
cout << "Parameters in FuncD() (none): " << FunctionD.Count() << endl;
cout << "Operands in '!' operator (postfix): " << uc.ItemOf("!").Count() << endl;
cout << "Operands in '>' operator (infix): " << uc.ItemOf(">").Count() << endl;
}
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call MyAverage(uCalcBase::Callback cb) { double Total = 0; for (int x = 1; x <= cb.ArgCount(); x++) { Total = Total + cb.Arg(x); } cb.Return(Total / cb.ArgCount()); } int main() { uCalc uc; auto MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}"); auto MyArrayB = uc.DefineVariable("MyArrayB[15]"); auto FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z"); auto FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b"); auto FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage); auto FunctionD = uc.DefineFunction("FuncD() = 1+1"); cout << "Elements in array (from initializer): " << MyArrayA.Count() << endl; cout << "Elements in array (from size): " << MyArrayB.Count() << endl; cout << "Parameters in FuncA() (fixed): " << FunctionA.Count() << endl; cout << "Parameters in FuncB() (with optional): " << FunctionB.Count() << endl; cout << "Parameters in FuncC() (variadic): " << FunctionC.Count() << endl; cout << "Parameters in FuncD() (none): " << FunctionD.Count() << endl; cout << "Operands in '!' operator (postfix): " << uc.ItemOf("!").Count() << endl; cout << "Operands in '>' operator (infix): " << uc.ItemOf(">").Count() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub MyAverage(ByVal cb As uCalc.Callback)
Dim Total As Double = 0
For x As Integer = 1 To cb.ArgCount()
Total = Total + cb.Arg(x)
Next
cb.Return(Total / cb.ArgCount())
End Sub
Public Sub Main()
Dim uc As New uCalc()
Dim MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}")
Dim MyArrayB = uc.DefineVariable("MyArrayB[15]")
Dim FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z")
Dim FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b")
Dim FunctionC = uc.DefineFunction("FuncC(x, y ...)", AddressOf MyAverage)
Dim FunctionD = uc.DefineFunction("FuncD() = 1+1")
Console.WriteLine($"Elements in array (from initializer): {MyArrayA.Count}")
Console.WriteLine($"Elements in array (from size): {MyArrayB.Count}")
Console.WriteLine($"Parameters in FuncA() (fixed): {FunctionA.Count}")
Console.WriteLine($"Parameters in FuncB() (with optional): {FunctionB.Count}")
Console.WriteLine($"Parameters in FuncC() (variadic): {FunctionC.Count}")
Console.WriteLine($"Parameters in FuncD() (none): {FunctionD.Count}")
Console.WriteLine($"Operands in '!' operator (postfix): {uc.ItemOf("!").Count}")
Console.WriteLine($"Operands in '>' operator (infix): {uc.ItemOf(">").Count}")
End Sub
End Module
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2 Imports System Imports uCalcSoftware Public Module Program Public Sub MyAverage(ByVal cb As uCalc.Callback) Dim Total As Double = 0 For x As Integer = 1 To cb.ArgCount() Total = Total + cb.Arg(x) Next cb.Return(Total / cb.ArgCount()) End Sub Public Sub Main() Dim uc As New uCalc() Dim MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}") Dim MyArrayB = uc.DefineVariable("MyArrayB[15]") Dim FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z") Dim FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b") Dim FunctionC = uc.DefineFunction("FuncC(x, y ...)", AddressOf MyAverage) Dim FunctionD = uc.DefineFunction("FuncD() = 1+1") Console.WriteLine($"Elements in array (from initializer): {MyArrayA.Count}") Console.WriteLine($"Elements in array (from size): {MyArrayB.Count}") Console.WriteLine($"Parameters in FuncA() (fixed): {FunctionA.Count}") Console.WriteLine($"Parameters in FuncB() (with optional): {FunctionB.Count}") Console.WriteLine($"Parameters in FuncC() (variadic): {FunctionC.Count}") Console.WriteLine($"Parameters in FuncD() (none): {FunctionD.Count}") Console.WriteLine($"Operands in '!' operator (postfix): {uc.ItemOf("!").Count}") Console.WriteLine($"Operands in '>' operator (infix): {uc.ItemOf(">").Count}") End Sub End Module
Converting a single line of legacy variable declaration syntax to a modern equivalent.
ID: 1376
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
// Rule to convert legacy variable declaration
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");
Console.WriteLine(t.Transform("LET X = 100"));
}
var X = 100; using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer()) { // Rule to convert legacy variable declaration t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};"); Console.WriteLine(t.Transform("LET X = 100")); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::Transformer t;
t.Owned(); // Causes t to be released when it goes out of scope
// Rule to convert legacy variable declaration
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");
cout << t.Transform("LET X = 100") << endl;
}
}
var X = 100; #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::Transformer t; t.Owned(); // Causes t to be released when it goes out of scope // Rule to convert legacy variable declaration t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};"); cout << t.Transform("LET X = 100") << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer()
'// Rule to convert legacy variable declaration
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};")
Console.WriteLine(t.Transform("LET X = 100"))
End Using
End Sub
End Module
var X = 100; Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer() '// Rule to convert legacy variable declaration t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};") Console.WriteLine(t.Transform("LET X = 100")) End Using End Sub End Module
Converting from Celsius to Fahrenheit with the Transformer
ID: 174
See: {@Eval}, Syntax Definitions
using uCalcSoftware;
var uc = new uCalc();
var t = uc.NewTransformer();
// Define the pattern first
t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F");
// Perform the Transform() operation
Console.WriteLine(t.Transform("Here is the temperature: 22.5 C"));
Here is the temperature: 72.5 F using uCalcSoftware; var uc = new uCalc(); var t = uc.NewTransformer(); // Define the pattern first t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F"); // Perform the Transform() operation Console.WriteLine(t.Transform("Here is the temperature: 22.5 C"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
auto t = uc.NewTransformer();
// Define the pattern first
t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F");
// Perform the Transform() operation
cout << t.Transform("Here is the temperature: 22.5 C") << endl;
}
Here is the temperature: 72.5 F #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; auto t = uc.NewTransformer(); // Define the pattern first t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F"); // Perform the Transform() operation cout << t.Transform("Here is the temperature: 22.5 C") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t = uc.NewTransformer()
'// Define the pattern first
t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F")
'// Perform the Transform() operation
Console.WriteLine(t.Transform("Here is the temperature: 22.5 C"))
End Sub
End Module
Here is the temperature: 72.5 F Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t = uc.NewTransformer() '// Define the pattern first t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F") '// Perform the Transform() operation Console.WriteLine(t.Transform("Here is the temperature: 22.5 C")) End Sub End Module
Converting quoted strings into XML-style elements by stripping the original quotes.
ID: 895
See: {@String}
using uCalcSoftware;
var uc = new uCalc();
var t = new uCalc.Transformer();
// Use {s(1)} to get just the text inside the quotes
t.FromTo("msg = {@String:s}", "{s(1)} ");
string input = """
msg = "Welcome to uCalc!"
""";
Console.WriteLine(t.Transform(input));
<message>Welcome to uCalc!</message> using uCalcSoftware; var uc = new uCalc(); var t = new uCalc.Transformer(); // Use {s(1)} to get just the text inside the quotes t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>"); string input = """ msg = "Welcome to uCalc!" """; Console.WriteLine(t.Transform(input));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uCalc::Transformer t;
// Use {s(1)} to get just the text inside the quotes
t.FromTo("msg = {@String:s}", "{s(1)} ");
string input = R"(msg = "Welcome to uCalc!")";
cout << t.Transform(input) << endl;
}
<message>Welcome to uCalc!</message> #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uCalc::Transformer t; // Use {s(1)} to get just the text inside the quotes t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>"); string input = R"(msg = "Welcome to uCalc!")"; cout << t.Transform(input) << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t As New uCalc.Transformer()
'// Use {s(1)} to get just the text inside the quotes
t.FromTo("msg = {@String:s}", "{s(1)} ")
Dim input As String = "msg = ""Welcome to uCalc!"""
Console.WriteLine(t.Transform(input))
End Sub
End Module
<message>Welcome to uCalc!</message> Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t As New uCalc.Transformer() '// Use {s(1)} to get just the text inside the quotes t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>") Dim input As String = "msg = ""Welcome to uCalc!""" Console.WriteLine(t.Transform(input)) End Sub End Module
Converting single-quoted strings to double-quoted ones by targeting the delimiters.
ID: 888
See: {@sq}
using uCalcSoftware;
var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("{@sq}", """
"
""");
Console.WriteLine(t.Transform("print 'Hello'"));
print "Hello" using uCalcSoftware; var uc = new uCalc(); var t = new uCalc.Transformer(); t.FromTo("{@sq}", """ " """); Console.WriteLine(t.Transform("print 'Hello'"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uCalc::Transformer t;
t.FromTo("{@sq}", R"(")");
cout << t.Transform("print 'Hello'") << endl;
}
print "Hello" #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uCalc::Transformer t; t.FromTo("{@sq}", R"(")"); cout << t.Transform("print 'Hello'") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t As New uCalc.Transformer()
t.FromTo("{@sq}", """")
Console.WriteLine(t.Transform("print 'Hello'"))
End Sub
End Module
print "Hello" Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t As New uCalc.Transformer() t.FromTo("{@sq}", """") Console.WriteLine(t.Transform("print 'Hello'")) End Sub End Module