uCalc SDK Interactive Examples
A basic example to get the starting index of a single word.
ID: 829
using uCalcSoftware;
var uc = new uCalc();
var t = new uCalc.Transformer();
t.Text = "Hello World";
t.Pattern("World");
t.Find();
var matches = t.Matches;
Console.WriteLine($"Match found at position: {matches[0].StartPosition}");
Match found at position: 6 using uCalcSoftware; var uc = new uCalc(); var t = new uCalc.Transformer(); t.Text = "Hello World"; t.Pattern("World"); t.Find(); var matches = t.Matches; Console.WriteLine($"Match found at position: {matches[0].StartPosition}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uCalc::Transformer t;
t.Text("Hello World");
t.Pattern("World");
t.Find();
auto matches = t.Matches();
cout << "Match found at position: " << matches[0].StartPosition() << endl;
}
Match found at position: 6 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uCalc::Transformer t; t.Text("Hello World"); t.Pattern("World"); t.Find(); auto matches = t.Matches(); cout << "Match found at position: " << matches[0].StartPosition() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t As New uCalc.Transformer()
t.Text = "Hello World"
t.Pattern("World")
t.Find()
Dim matches = t.Matches
Console.WriteLine($"Match found at position: {matches(0).StartPosition}")
End Sub
End Module
Match found at position: 6 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t As New uCalc.Transformer() t.Text = "Hello World" t.Pattern("World") t.Find() Dim matches = t.Matches Console.WriteLine($"Match found at position: {matches(0).StartPosition}") End Sub End Module
A basic find-and-replace operation to change one word to another using a fluent, chainable syntax.
ID: 1195
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
// Define the rule and execute the transform in a single, chained statement.
t.FromTo("Hello", "Greetings");
Console.WriteLine(t.Transform("Hello World!"));
}
Greetings World! using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer()) { // Define the rule and execute the transform in a single, chained statement. t.FromTo("Hello", "Greetings"); Console.WriteLine(t.Transform("Hello World!")); }
#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
// Define the rule and execute the transform in a single, chained statement.
t.FromTo("Hello", "Greetings");
cout << t.Transform("Hello World!") << endl;
}
}
Greetings World! #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 // Define the rule and execute the transform in a single, chained statement. t.FromTo("Hello", "Greetings"); cout << t.Transform("Hello World!") << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer()
'// Define the rule and execute the transform in a single, chained statement.
t.FromTo("Hello", "Greetings")
Console.WriteLine(t.Transform("Hello World!"))
End Using
End Sub
End Module
Greetings World! Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer() '// Define the rule and execute the transform in a single, chained statement. t.FromTo("Hello", "Greetings") Console.WriteLine(t.Transform("Hello World!")) End Using End Sub End Module
A basic pattern demonstrating how an optional word affects the match.
ID: 1204
See: Optional Parts
using uCalcSoftware;
var uc = new uCalc();
var t = new uCalc.Transformer();
t.FromTo("Log [ERROR] entry", "MATCHED");
// This matches because the optional word is present
Console.WriteLine(t.Transform("Log ERROR entry found."));
// This also matches because the word is optional
Console.WriteLine(t.Transform("Log entry found."));
MATCHED found.
MATCHED found. using uCalcSoftware; var uc = new uCalc(); var t = new uCalc.Transformer(); t.FromTo("Log [ERROR] entry", "MATCHED"); // This matches because the optional word is present Console.WriteLine(t.Transform("Log ERROR entry found.")); // This also matches because the word is optional Console.WriteLine(t.Transform("Log entry found."));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uCalc::Transformer t;
t.FromTo("Log [ERROR] entry", "MATCHED");
// This matches because the optional word is present
cout << t.Transform("Log ERROR entry found.") << endl;
// This also matches because the word is optional
cout << t.Transform("Log entry found.") << endl;
}
MATCHED found.
MATCHED found. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uCalc::Transformer t; t.FromTo("Log [ERROR] entry", "MATCHED"); // This matches because the optional word is present cout << t.Transform("Log ERROR entry found.") << endl; // This also matches because the word is optional cout << t.Transform("Log entry found.") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t As New uCalc.Transformer()
t.FromTo("Log [ERROR] entry", "MATCHED")
'// This matches because the optional word is present
Console.WriteLine(t.Transform("Log ERROR entry found."))
'// This also matches because the word is optional
Console.WriteLine(t.Transform("Log entry found."))
End Sub
End Module
MATCHED found.
MATCHED found. Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t As New uCalc.Transformer() t.FromTo("Log [ERROR] entry", "MATCHED") '// This matches because the optional word is present Console.WriteLine(t.Transform("Log ERROR entry found.")) '// This also matches because the word is optional Console.WriteLine(t.Transform("Log entry found.")) End Sub End Module
A basic, token-aware variable rename.
ID: 1401
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
// This rule will only match the standalone token 'rate', not 'exchange_rate'.
t.FromTo("rate", "interestRate");
var code = "var exchange_rate = 0.5; var rate = 0.1;";
Console.WriteLine(t.Transform(code));
}
var exchange_rate = 0.5; var interestRate = 0.1; using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer()) { // This rule will only match the standalone token 'rate', not 'exchange_rate'. t.FromTo("rate", "interestRate"); var code = "var exchange_rate = 0.5; var rate = 0.1;"; Console.WriteLine(t.Transform(code)); }
#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
// This rule will only match the standalone token 'rate', not 'exchange_rate'.
t.FromTo("rate", "interestRate");
auto code = "var exchange_rate = 0.5; var rate = 0.1;";
cout << t.Transform(code) << endl;
}
}
var exchange_rate = 0.5; var interestRate = 0.1; #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 // This rule will only match the standalone token 'rate', not 'exchange_rate'. t.FromTo("rate", "interestRate"); auto code = "var exchange_rate = 0.5; var rate = 0.1;"; cout << t.Transform(code) << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer()
'// This rule will only match the standalone token 'rate', not 'exchange_rate'.
t.FromTo("rate", "interestRate")
Dim code = "var exchange_rate = 0.5; var rate = 0.1;"
Console.WriteLine(t.Transform(code))
End Using
End Sub
End Module
var exchange_rate = 0.5; var interestRate = 0.1; Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer() '// This rule will only match the standalone token 'rate', not 'exchange_rate'. t.FromTo("rate", "interestRate") Dim code = "var exchange_rate = 0.5; var rate = 0.1;" Console.WriteLine(t.Transform(code)) End Using End Sub End Module
A complete data sanitization pipeline that processes multiple key-value pairs, using a native callback to perform custom email validation.
ID: 1371
using uCalcSoftware;
var uc = new uCalc();
static void IsValidEmail(uCalc.Callback cb) {
var email = cb.ArgStr(1);
var uc = cb.uCalc;
// Simple validation: check for '@' and '.'
var isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')");
if (isValid == "true") {
cb.ReturnBool(true);
} else {
cb.ReturnBool(false);
}
}
// 1. Define the custom validation function in the uCalc engine
uc.DefineFunction("IsValidEmail(email As String) As Bool", IsValidEmail);
// 2. Create and configure the transformer
using (var t = new uCalc.Transformer(uc)) {
// 3. Define the sanitization and validation rules
t.FromTo("user = {val};", "User: {val},");
t.FromTo("age = {val};", "Age: {val},");
t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}"); // Last rule, no trailing comma
// The email rule uses the custom function for validation
t.FromTo("email = {val};",
"Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},");
// 4. Define the messy input strings
var input1 = "user= Alice ; age =30 ; email= alice@ucalc.com ; status=active";
var input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive";
// 5. Run the transformations
Console.WriteLine(t.Transform(input1));
Console.WriteLine(t.Transform(input2));
};
User: Alice, Age: 30, Email: alice@ucalc.com (Valid), Status: ACTIVE
User: Bob, Age: 45, Email: bob-at-ucalc (INVALID), Status: INACTIVE using uCalcSoftware; var uc = new uCalc(); static void IsValidEmail(uCalc.Callback cb) { var email = cb.ArgStr(1); var uc = cb.uCalc; // Simple validation: check for '@' and '.' var isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')"); if (isValid == "true") { cb.ReturnBool(true); } else { cb.ReturnBool(false); } } // 1. Define the custom validation function in the uCalc engine uc.DefineFunction("IsValidEmail(email As String) As Bool", IsValidEmail); // 2. Create and configure the transformer using (var t = new uCalc.Transformer(uc)) { // 3. Define the sanitization and validation rules t.FromTo("user = {val};", "User: {val},"); t.FromTo("age = {val};", "Age: {val},"); t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}"); // Last rule, no trailing comma // The email rule uses the custom function for validation t.FromTo("email = {val};", "Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},"); // 4. Define the messy input strings var input1 = "user= Alice ; age =30 ; email= alice@ucalc.com ; status=active"; var input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive"; // 5. Run the transformations Console.WriteLine(t.Transform(input1)); Console.WriteLine(t.Transform(input2)); };
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call IsValidEmail(uCalcBase::Callback cb) {
auto email = cb.ArgStr(1);
auto uc = cb.uCalc();
// Simple validation: check for '@' and '.'
auto isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')");
if (isValid == "true") {
cb.ReturnBool(true);
} else {
cb.ReturnBool(false);
}
}
int main() {
uCalc uc;
// 1. Define the custom validation function in the uCalc engine
uc.DefineFunction("IsValidEmail(email As String) As Bool", IsValidEmail);
// 2. Create and configure the transformer
{
uCalc::Transformer t(uc);
t.Owned(); // Causes t to be released when it goes out of scope
// 3. Define the sanitization and validation rules
t.FromTo("user = {val};", "User: {val},");
t.FromTo("age = {val};", "Age: {val},");
t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}"); // Last rule, no trailing comma
// The email rule uses the custom function for validation
t.FromTo("email = {val};",
"Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},");
// 4. Define the messy input strings
auto input1 = "user= Alice ; age =30 ; email= alice@ucalc.com ; status=active";
auto input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive";
// 5. Run the transformations
cout << t.Transform(input1) << endl;
cout << t.Transform(input2) << endl;
};
}
User: Alice, Age: 30, Email: alice@ucalc.com (Valid), Status: ACTIVE
User: Bob, Age: 45, Email: bob-at-ucalc (INVALID), Status: INACTIVE #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call IsValidEmail(uCalcBase::Callback cb) { auto email = cb.ArgStr(1); auto uc = cb.uCalc(); // Simple validation: check for '@' and '.' auto isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')"); if (isValid == "true") { cb.ReturnBool(true); } else { cb.ReturnBool(false); } } int main() { uCalc uc; // 1. Define the custom validation function in the uCalc engine uc.DefineFunction("IsValidEmail(email As String) As Bool", IsValidEmail); // 2. Create and configure the transformer { uCalc::Transformer t(uc); t.Owned(); // Causes t to be released when it goes out of scope // 3. Define the sanitization and validation rules t.FromTo("user = {val};", "User: {val},"); t.FromTo("age = {val};", "Age: {val},"); t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}"); // Last rule, no trailing comma // The email rule uses the custom function for validation t.FromTo("email = {val};", "Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},"); // 4. Define the messy input strings auto input1 = "user= Alice ; age =30 ; email= alice@ucalc.com ; status=active"; auto input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive"; // 5. Run the transformations cout << t.Transform(input1) << endl; cout << t.Transform(input2) << endl; }; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub IsValidEmail(ByVal cb As uCalc.Callback)
Dim email = cb.ArgStr(1)
Dim uc = cb.uCalc
'// Simple validation: check for '@' and '.'
Dim isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')")
If isValid = "true" Then
cb.ReturnBool(true)
Else
cb.ReturnBool(false)
End If
End Sub
Public Sub Main()
Dim uc As New uCalc()
'// 1. Define the custom validation function in the uCalc engine
uc.DefineFunction("IsValidEmail(email As String) As Bool", AddressOf IsValidEmail)
'// 2. Create and configure the transformer
Using t As New uCalc.Transformer(uc)
'// 3. Define the sanitization and validation rules
t.FromTo("user = {val};", "User: {val},")
t.FromTo("age = {val};", "Age: {val},")
t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}") '// Last rule, no trailing comma
'// The email rule uses the custom function for validation
t.FromTo("email = {val};",
"Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},")
'// 4. Define the messy input strings
Dim input1 = "user= Alice ; age =30 ; email= alice@ucalc.com ; status=active"
Dim input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive"
'// 5. Run the transformations
Console.WriteLine(t.Transform(input1))
Console.WriteLine(t.Transform(input2))
End Using
End Sub
End Module
User: Alice, Age: 30, Email: alice@ucalc.com (Valid), Status: ACTIVE
User: Bob, Age: 45, Email: bob-at-ucalc (INVALID), Status: INACTIVE Imports System Imports uCalcSoftware Public Module Program Public Sub IsValidEmail(ByVal cb As uCalc.Callback) Dim email = cb.ArgStr(1) Dim uc = cb.uCalc '// Simple validation: check for '@' and '.' Dim isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')") If isValid = "true" Then cb.ReturnBool(true) Else cb.ReturnBool(false) End If End Sub Public Sub Main() Dim uc As New uCalc() '// 1. Define the custom validation function in the uCalc engine uc.DefineFunction("IsValidEmail(email As String) As Bool", AddressOf IsValidEmail) '// 2. Create and configure the transformer Using t As New uCalc.Transformer(uc) '// 3. Define the sanitization and validation rules t.FromTo("user = {val};", "User: {val},") t.FromTo("age = {val};", "Age: {val},") t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}") '// Last rule, no trailing comma '// The email rule uses the custom function for validation t.FromTo("email = {val};", "Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},") '// 4. Define the messy input strings Dim input1 = "user= Alice ; age =30 ; email= alice@ucalc.com ; status=active" Dim input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive" '// 5. Run the transformations Console.WriteLine(t.Transform(input1)) Console.WriteLine(t.Transform(input2)) End Using End Sub End Module
A complete game turn script demonstrating multiple DSL commands for moving, gaining resources, and drawing cards.
ID: 1386
using uCalcSoftware;
var uc = new uCalc();
// 1. Define the initial game state
uc.DefineVariable("p1_pos = 0");
uc.DefineVariable("p1_gold = 10");
uc.DefineVariable("p2_pos = 0");
uc.DefineVariable("p2_gold = 10");
// 2. Define the DSL rules
var t = uc.ExpressionTransformer;
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}");
t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}");
// 3. Define the script for the turn
var game_turn_script = """
PLAYER 1 MOVES 4
PLAYER 2 MOVES 2
PLAYER 1 GAINS 5 GOLD
PLAYER 2 MOVES 3
""";
// 4. Execute the script
uc.EvalStr(game_turn_script);
// 5. Display the final state
Console.WriteLine("--- End of Turn State ---");
Console.WriteLine($"Player 1 Position: {uc.EvalStr("p1_pos")}");
Console.WriteLine($"Player 1 Gold: {uc.EvalStr("p1_gold")}");
Console.WriteLine($"Player 2 Position: {uc.EvalStr("p2_pos")}");
Console.WriteLine($"Player 2 Gold: {uc.EvalStr("p2_gold")}");
--- End of Turn State ---
Player 1 Position: 4
Player 1 Gold: 15
Player 2 Position: 5
Player 2 Gold: 10 using uCalcSoftware; var uc = new uCalc(); // 1. Define the initial game state uc.DefineVariable("p1_pos = 0"); uc.DefineVariable("p1_gold = 10"); uc.DefineVariable("p2_pos = 0"); uc.DefineVariable("p2_gold = 10"); // 2. Define the DSL rules var t = uc.ExpressionTransformer; t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}"); t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}"); // 3. Define the script for the turn var game_turn_script = """ PLAYER 1 MOVES 4 PLAYER 2 MOVES 2 PLAYER 1 GAINS 5 GOLD PLAYER 2 MOVES 3 """; // 4. Execute the script uc.EvalStr(game_turn_script); // 5. Display the final state Console.WriteLine("--- End of Turn State ---"); Console.WriteLine($"Player 1 Position: {uc.EvalStr("p1_pos")}"); Console.WriteLine($"Player 1 Gold: {uc.EvalStr("p1_gold")}"); Console.WriteLine($"Player 2 Position: {uc.EvalStr("p2_pos")}"); Console.WriteLine($"Player 2 Gold: {uc.EvalStr("p2_gold")}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// 1. Define the initial game state
uc.DefineVariable("p1_pos = 0");
uc.DefineVariable("p1_gold = 10");
uc.DefineVariable("p2_pos = 0");
uc.DefineVariable("p2_gold = 10");
// 2. Define the DSL rules
auto t = uc.ExpressionTransformer();
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}");
t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}");
// 3. Define the script for the turn
auto game_turn_script = R"(
PLAYER 1 MOVES 4
PLAYER 2 MOVES 2
PLAYER 1 GAINS 5 GOLD
PLAYER 2 MOVES 3
)";
// 4. Execute the script
uc.EvalStr(game_turn_script);
// 5. Display the final state
cout << "--- End of Turn State ---" << endl;
cout << "Player 1 Position: " << uc.EvalStr("p1_pos") << endl;
cout << "Player 1 Gold: " << uc.EvalStr("p1_gold") << endl;
cout << "Player 2 Position: " << uc.EvalStr("p2_pos") << endl;
cout << "Player 2 Gold: " << uc.EvalStr("p2_gold") << endl;
}
--- End of Turn State ---
Player 1 Position: 4
Player 1 Gold: 15
Player 2 Position: 5
Player 2 Gold: 10 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // 1. Define the initial game state uc.DefineVariable("p1_pos = 0"); uc.DefineVariable("p1_gold = 10"); uc.DefineVariable("p2_pos = 0"); uc.DefineVariable("p2_gold = 10"); // 2. Define the DSL rules auto t = uc.ExpressionTransformer(); t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}"); t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}"); // 3. Define the script for the turn auto game_turn_script = R"( PLAYER 1 MOVES 4 PLAYER 2 MOVES 2 PLAYER 1 GAINS 5 GOLD PLAYER 2 MOVES 3 )"; // 4. Execute the script uc.EvalStr(game_turn_script); // 5. Display the final state cout << "--- End of Turn State ---" << endl; cout << "Player 1 Position: " << uc.EvalStr("p1_pos") << endl; cout << "Player 1 Gold: " << uc.EvalStr("p1_gold") << endl; cout << "Player 2 Position: " << uc.EvalStr("p2_pos") << endl; cout << "Player 2 Gold: " << uc.EvalStr("p2_gold") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// 1. Define the initial game state
uc.DefineVariable("p1_pos = 0")
uc.DefineVariable("p1_gold = 10")
uc.DefineVariable("p2_pos = 0")
uc.DefineVariable("p2_gold = 10")
'// 2. Define the DSL rules
Dim t = uc.ExpressionTransformer
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}")
t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}")
'// 3. Define the script for the turn
Dim game_turn_script = "
PLAYER 1 MOVES 4
PLAYER 2 MOVES 2
PLAYER 1 GAINS 5 GOLD
PLAYER 2 MOVES 3
"
'// 4. Execute the script
uc.EvalStr(game_turn_script)
'// 5. Display the final state
Console.WriteLine("--- End of Turn State ---")
Console.WriteLine($"Player 1 Position: {uc.EvalStr("p1_pos")}")
Console.WriteLine($"Player 1 Gold: {uc.EvalStr("p1_gold")}")
Console.WriteLine($"Player 2 Position: {uc.EvalStr("p2_pos")}")
Console.WriteLine($"Player 2 Gold: {uc.EvalStr("p2_gold")}")
End Sub
End Module
--- End of Turn State ---
Player 1 Position: 4
Player 1 Gold: 15
Player 2 Position: 5
Player 2 Gold: 10 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// 1. Define the initial game state uc.DefineVariable("p1_pos = 0") uc.DefineVariable("p1_gold = 10") uc.DefineVariable("p2_pos = 0") uc.DefineVariable("p2_gold = 10") '// 2. Define the DSL rules Dim t = uc.ExpressionTransformer t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}") t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}") '// 3. Define the script for the turn Dim game_turn_script = " PLAYER 1 MOVES 4 PLAYER 2 MOVES 2 PLAYER 1 GAINS 5 GOLD PLAYER 2 MOVES 3 " '// 4. Execute the script uc.EvalStr(game_turn_script) '// 5. Display the final state Console.WriteLine("--- End of Turn State ---") Console.WriteLine($"Player 1 Position: {uc.EvalStr("p1_pos")}") Console.WriteLine($"Player 1 Gold: {uc.EvalStr("p1_gold")}") Console.WriteLine($"Player 2 Position: {uc.EvalStr("p2_pos")}") Console.WriteLine($"Player 2 Gold: {uc.EvalStr("p2_gold")}") End Sub End Module
A complete JSON formatter that takes a minified string and pretty-prints it with proper indentation.
ID: 1382
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer(uc)) {
// 1. Define state variable in the uCalc instance.
uc.DefineVariable("indent = 0");
// 2. Define the transformation rules.
// Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals.
// Rule for '{' and '[': Add newline, increment indent, add indent string.
t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: ' ' * indent}");
// Rule for '}' and ']': Add newline, decrement indent, add indent string.
t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: ' ' * indent}{@Self}");
// Rule for ',': Add newline and current indent string.
t.FromTo(",", ",{@nl}{@Eval: ' ' * indent}");
// Rule for ':': Add a space after it for readability.
t.FromTo(":", ": ");
// 3. Define the minified input string.
var minifiedJson = """
{"id":123,"name":"Example","tags":["A","B"],"active":true}
""";
// 4. Run the transformation and print the result.
Console.WriteLine(t.Transform(minifiedJson));
}
{
"id": 123,
"name": "Example",
"tags": [
"A",
"B"
],
"active": true
} using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer(uc)) { // 1. Define state variable in the uCalc instance. uc.DefineVariable("indent = 0"); // 2. Define the transformation rules. // Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals. // Rule for '{' and '[': Add newline, increment indent, add indent string. t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: ' ' * indent}"); // Rule for '}' and ']': Add newline, decrement indent, add indent string. t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: ' ' * indent}{@Self}"); // Rule for ',': Add newline and current indent string. t.FromTo(",", ",{@nl}{@Eval: ' ' * indent}"); // Rule for ':': Add a space after it for readability. t.FromTo(":", ": "); // 3. Define the minified input string. var minifiedJson = """ {"id":123,"name":"Example","tags":["A","B"],"active":true} """; // 4. Run the transformation and print the result. Console.WriteLine(t.Transform(minifiedJson)); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::Transformer t(uc);
t.Owned(); // Causes t to be released when it goes out of scope
// 1. Define state variable in the uCalc instance.
uc.DefineVariable("indent = 0");
// 2. Define the transformation rules.
// Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals.
// Rule for '{' and '[': Add newline, increment indent, add indent string.
t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: ' ' * indent}");
// Rule for '}' and ']': Add newline, decrement indent, add indent string.
t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: ' ' * indent}{@Self}");
// Rule for ',': Add newline and current indent string.
t.FromTo(",", ",{@nl}{@Eval: ' ' * indent}");
// Rule for ':': Add a space after it for readability.
t.FromTo(":", ": ");
// 3. Define the minified input string.
auto minifiedJson = R"({"id":123,"name":"Example","tags":["A","B"],"active":true})";
// 4. Run the transformation and print the result.
cout << t.Transform(minifiedJson) << endl;
}
}
{
"id": 123,
"name": "Example",
"tags": [
"A",
"B"
],
"active": true
} #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::Transformer t(uc); t.Owned(); // Causes t to be released when it goes out of scope // 1. Define state variable in the uCalc instance. uc.DefineVariable("indent = 0"); // 2. Define the transformation rules. // Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals. // Rule for '{' and '[': Add newline, increment indent, add indent string. t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: ' ' * indent}"); // Rule for '}' and ']': Add newline, decrement indent, add indent string. t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: ' ' * indent}{@Self}"); // Rule for ',': Add newline and current indent string. t.FromTo(",", ",{@nl}{@Eval: ' ' * indent}"); // Rule for ':': Add a space after it for readability. t.FromTo(":", ": "); // 3. Define the minified input string. auto minifiedJson = R"({"id":123,"name":"Example","tags":["A","B"],"active":true})"; // 4. Run the transformation and print the result. cout << t.Transform(minifiedJson) << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer(uc)
'// 1. Define state variable in the uCalc instance.
uc.DefineVariable("indent = 0")
'// 2. Define the transformation rules.
'// Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals.
'// Rule for '{' and '[': Add newline, increment indent, add indent string.
t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: ' ' * indent}")
'// Rule for '}' and ']': Add newline, decrement indent, add indent string.
t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: ' ' * indent}{@Self}")
'// Rule for ',': Add newline and current indent string.
t.FromTo(",", ",{@nl}{@Eval: ' ' * indent}")
'// Rule for ':': Add a space after it for readability.
t.FromTo(":", ": ")
'// 3. Define the minified input string.
Dim minifiedJson = "{""id"":123,""name"":""Example"",""tags"":[""A"",""B""],""active"":true}"
'// 4. Run the transformation and print the result.
Console.WriteLine(t.Transform(minifiedJson))
End Using
End Sub
End Module
{
"id": 123,
"name": "Example",
"tags": [
"A",
"B"
],
"active": true
} Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer(uc) '// 1. Define state variable in the uCalc instance. uc.DefineVariable("indent = 0") '// 2. Define the transformation rules. '// Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals. '// Rule for '{' and '[': Add newline, increment indent, add indent string. t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: ' ' * indent}") '// Rule for '}' and ']': Add newline, decrement indent, add indent string. t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: ' ' * indent}{@Self}") '// Rule for ',': Add newline and current indent string. t.FromTo(",", ",{@nl}{@Eval: ' ' * indent}") '// Rule for ':': Add a space after it for readability. t.FromTo(":", ": ") '// 3. Define the minified input string. Dim minifiedJson = "{""id"":123,""name"":""Example"",""tags"":[""A"",""B""],""active"":true}" '// 4. Run the transformation and print the result. Console.WriteLine(t.Transform(minifiedJson)) End Using End Sub End Module
A complete JSON minifier that takes a formatted string and removes all non-essential whitespace.
ID: 1383
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
// 1. Define rules to remove whitespace and newlines.
// The engine's default QuoteSensitive=true ensures whitespace inside strings is protected.
t.FromTo("{@Whitespace}", "");
t.FromTo("{@Newline}", "");
// 2. Define the formatted input string.
var formattedJson = """
{
"id": 123,
"name": "Example, with spaces",
"tags": [
"A",
"B"
]
}
""";
// 3. Run the transformation and print the result.
Console.WriteLine(t.Transform(formattedJson));
}
{"id":123,"name":"Example, with spaces","tags":["A","B"]} using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer()) { // 1. Define rules to remove whitespace and newlines. // The engine's default QuoteSensitive=true ensures whitespace inside strings is protected. t.FromTo("{@Whitespace}", ""); t.FromTo("{@Newline}", ""); // 2. Define the formatted input string. var formattedJson = """ { "id": 123, "name": "Example, with spaces", "tags": [ "A", "B" ] } """; // 3. Run the transformation and print the result. Console.WriteLine(t.Transform(formattedJson)); }
#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
// 1. Define rules to remove whitespace and newlines.
// The engine's default QuoteSensitive=true ensures whitespace inside strings is protected.
t.FromTo("{@Whitespace}", "");
t.FromTo("{@Newline}", "");
// 2. Define the formatted input string.
auto formattedJson = R"({
"id": 123,
"name": "Example, with spaces",
"tags": [
"A",
"B"
]
})";
// 3. Run the transformation and print the result.
cout << t.Transform(formattedJson) << endl;
}
}
{"id":123,"name":"Example, with spaces","tags":["A","B"]} #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 // 1. Define rules to remove whitespace and newlines. // The engine's default QuoteSensitive=true ensures whitespace inside strings is protected. t.FromTo("{@Whitespace}", ""); t.FromTo("{@Newline}", ""); // 2. Define the formatted input string. auto formattedJson = R"({ "id": 123, "name": "Example, with spaces", "tags": [ "A", "B" ] })"; // 3. Run the transformation and print the result. cout << t.Transform(formattedJson) << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer()
'// 1. Define rules to remove whitespace and newlines.
'// The engine's default QuoteSensitive=true ensures whitespace inside strings is protected.
t.FromTo("{@Whitespace}", "")
t.FromTo("{@Newline}", "")
'// 2. Define the formatted input string.
Dim formattedJson = "{
""id"": 123,
""name"": ""Example, with spaces"",
""tags"": [
""A"",
""B""
]
}"
'// 3. Run the transformation and print the result.
Console.WriteLine(t.Transform(formattedJson))
End Using
End Sub
End Module
{"id":123,"name":"Example, with spaces","tags":["A","B"]} Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer() '// 1. Define rules to remove whitespace and newlines. '// The engine's default QuoteSensitive=true ensures whitespace inside strings is protected. t.FromTo("{@Whitespace}", "") t.FromTo("{@Newline}", "") '// 2. Define the formatted input string. Dim formattedJson = "{ ""id"": 123, ""name"": ""Example, with spaces"", ""tags"": [ ""A"", ""B"" ] }" '// 3. Run the transformation and print the result. Console.WriteLine(t.Transform(formattedJson)) End Using End Sub End Module
A complete log processing pipeline that parses multiple lines and calculates aggregate metrics like total requests, error count, and average response time.
ID: 1389
using uCalcSoftware;
var uc = new uCalc();
// 1. Define variables to hold the metrics
uc.DefineVariable("request_count = 0");
uc.DefineVariable("error_count = 0");
uc.DefineVariable("total_response_time = 0.0");
uc.DefineVariable("max_response_time = 0.0");
// 2. Create the transformer and define the rule
using (var t = new uCalc.Transformer(uc)) {
var pattern = "{@String:request} {@Number:status} {@Number:time}ms";
// 3. The replacement string uses @Exec for side-effects (updating variables)
var replacement = """
{@Exec: request_count++}
{@Exec: total_response_time = total_response_time + Double(time)}
{@Exec: max_response_time = Max(max_response_time, Double(time))}
{@Exec: iif(Double(status) >= 400, error_count++, 0)}
""";
t.FromTo(pattern, replacement);
// 4. Define the multi-line log data
var logText = """
2024-10-26 10:00:05 INFO 192.168.1.10 "GET /api/users HTTP/1.1" 200 15ms
2024-10-26 10:00:06 INFO 192.168.1.15 "GET /api/products HTTP/1.1" 200 22ms
2024-10-26 10:00:07 ERROR 192.168.1.22 "POST /api/login HTTP/1.1" 500 120ms
2024-10-26 10:00:08 INFO 192.168.1.10 "GET /api/users/1 HTTP/1.1" 200 8ms
""";
// 5. Run the transformation (the output will be empty as we only use @Exec)
t.Transform(logText);
}
// 6. Display the final aggregated metrics
Console.WriteLine("--- Log Analysis Summary ---");
Console.WriteLine($"Total Requests: {uc.EvalStr("request_count")}");
Console.WriteLine($"Total Errors: {uc.EvalStr("error_count")}");
Console.WriteLine($"Average Response Time: {uc.EvalStr("total_response_time / request_count")}ms");
Console.WriteLine($"Maximum Response Time: {uc.EvalStr("max_response_time")}ms");
--- Log Analysis Summary ---
Total Requests: 4
Total Errors: 1
Average Response Time: 41.25ms
Maximum Response Time: 120ms using uCalcSoftware; var uc = new uCalc(); // 1. Define variables to hold the metrics uc.DefineVariable("request_count = 0"); uc.DefineVariable("error_count = 0"); uc.DefineVariable("total_response_time = 0.0"); uc.DefineVariable("max_response_time = 0.0"); // 2. Create the transformer and define the rule using (var t = new uCalc.Transformer(uc)) { var pattern = "{@String:request} {@Number:status} {@Number:time}ms"; // 3. The replacement string uses @Exec for side-effects (updating variables) var replacement = """ {@Exec: request_count++} {@Exec: total_response_time = total_response_time + Double(time)} {@Exec: max_response_time = Max(max_response_time, Double(time))} {@Exec: iif(Double(status) >= 400, error_count++, 0)} """; t.FromTo(pattern, replacement); // 4. Define the multi-line log data var logText = """ 2024-10-26 10:00:05 INFO 192.168.1.10 "GET /api/users HTTP/1.1" 200 15ms 2024-10-26 10:00:06 INFO 192.168.1.15 "GET /api/products HTTP/1.1" 200 22ms 2024-10-26 10:00:07 ERROR 192.168.1.22 "POST /api/login HTTP/1.1" 500 120ms 2024-10-26 10:00:08 INFO 192.168.1.10 "GET /api/users/1 HTTP/1.1" 200 8ms """; // 5. Run the transformation (the output will be empty as we only use @Exec) t.Transform(logText); } // 6. Display the final aggregated metrics Console.WriteLine("--- Log Analysis Summary ---"); Console.WriteLine($"Total Requests: {uc.EvalStr("request_count")}"); Console.WriteLine($"Total Errors: {uc.EvalStr("error_count")}"); Console.WriteLine($"Average Response Time: {uc.EvalStr("total_response_time / request_count")}ms"); Console.WriteLine($"Maximum Response Time: {uc.EvalStr("max_response_time")}ms");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// 1. Define variables to hold the metrics
uc.DefineVariable("request_count = 0");
uc.DefineVariable("error_count = 0");
uc.DefineVariable("total_response_time = 0.0");
uc.DefineVariable("max_response_time = 0.0");
// 2. Create the transformer and define the rule
{
uCalc::Transformer t(uc);
t.Owned(); // Causes t to be released when it goes out of scope
auto pattern = "{@String:request} {@Number:status} {@Number:time}ms";
// 3. The replacement string uses @Exec for side-effects (updating variables)
auto replacement = R"(
{@Exec: request_count++}
{@Exec: total_response_time = total_response_time + Double(time)}
{@Exec: max_response_time = Max(max_response_time, Double(time))}
{@Exec: iif(Double(status) >= 400, error_count++, 0)}
)";
t.FromTo(pattern, replacement);
// 4. Define the multi-line log data
auto logText = R"(
2024-10-26 10:00:05 INFO 192.168.1.10 "GET /api/users HTTP/1.1" 200 15ms
2024-10-26 10:00:06 INFO 192.168.1.15 "GET /api/products HTTP/1.1" 200 22ms
2024-10-26 10:00:07 ERROR 192.168.1.22 "POST /api/login HTTP/1.1" 500 120ms
2024-10-26 10:00:08 INFO 192.168.1.10 "GET /api/users/1 HTTP/1.1" 200 8ms
)";
// 5. Run the transformation (the output will be empty as we only use @Exec)
t.Transform(logText);
}
// 6. Display the final aggregated metrics
cout << "--- Log Analysis Summary ---" << endl;
cout << "Total Requests: " << uc.EvalStr("request_count") << endl;
cout << "Total Errors: " << uc.EvalStr("error_count") << endl;
cout << "Average Response Time: " << uc.EvalStr("total_response_time / request_count") << "ms" << endl;
cout << "Maximum Response Time: " << uc.EvalStr("max_response_time") << "ms" << endl;
}
--- Log Analysis Summary ---
Total Requests: 4
Total Errors: 1
Average Response Time: 41.25ms
Maximum Response Time: 120ms #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // 1. Define variables to hold the metrics uc.DefineVariable("request_count = 0"); uc.DefineVariable("error_count = 0"); uc.DefineVariable("total_response_time = 0.0"); uc.DefineVariable("max_response_time = 0.0"); // 2. Create the transformer and define the rule { uCalc::Transformer t(uc); t.Owned(); // Causes t to be released when it goes out of scope auto pattern = "{@String:request} {@Number:status} {@Number:time}ms"; // 3. The replacement string uses @Exec for side-effects (updating variables) auto replacement = R"( {@Exec: request_count++} {@Exec: total_response_time = total_response_time + Double(time)} {@Exec: max_response_time = Max(max_response_time, Double(time))} {@Exec: iif(Double(status) >= 400, error_count++, 0)} )"; t.FromTo(pattern, replacement); // 4. Define the multi-line log data auto logText = R"( 2024-10-26 10:00:05 INFO 192.168.1.10 "GET /api/users HTTP/1.1" 200 15ms 2024-10-26 10:00:06 INFO 192.168.1.15 "GET /api/products HTTP/1.1" 200 22ms 2024-10-26 10:00:07 ERROR 192.168.1.22 "POST /api/login HTTP/1.1" 500 120ms 2024-10-26 10:00:08 INFO 192.168.1.10 "GET /api/users/1 HTTP/1.1" 200 8ms )"; // 5. Run the transformation (the output will be empty as we only use @Exec) t.Transform(logText); } // 6. Display the final aggregated metrics cout << "--- Log Analysis Summary ---" << endl; cout << "Total Requests: " << uc.EvalStr("request_count") << endl; cout << "Total Errors: " << uc.EvalStr("error_count") << endl; cout << "Average Response Time: " << uc.EvalStr("total_response_time / request_count") << "ms" << endl; cout << "Maximum Response Time: " << uc.EvalStr("max_response_time") << "ms" << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// 1. Define variables to hold the metrics
uc.DefineVariable("request_count = 0")
uc.DefineVariable("error_count = 0")
uc.DefineVariable("total_response_time = 0.0")
uc.DefineVariable("max_response_time = 0.0")
'// 2. Create the transformer and define the rule
Using t As New uCalc.Transformer(uc)
Dim pattern = "{@String:request} {@Number:status} {@Number:time}ms"
'// 3. The replacement string uses @Exec for side-effects (updating variables)
Dim replacement = "
{@Exec: request_count++}
{@Exec: total_response_time = total_response_time + Double(time)}
{@Exec: max_response_time = Max(max_response_time, Double(time))}
{@Exec: iif(Double(status) >= 400, error_count++, 0)}
"
t.FromTo(pattern, replacement)
'// 4. Define the multi-line log data
Dim logText = "
2024-10-26 10:00:05 INFO 192.168.1.10 ""GET /api/users HTTP/1.1"" 200 15ms
2024-10-26 10:00:06 INFO 192.168.1.15 ""GET /api/products HTTP/1.1"" 200 22ms
2024-10-26 10:00:07 ERROR 192.168.1.22 ""POST /api/login HTTP/1.1"" 500 120ms
2024-10-26 10:00:08 INFO 192.168.1.10 ""GET /api/users/1 HTTP/1.1"" 200 8ms
"
'// 5. Run the transformation (the output will be empty as we only use @Exec)
t.Transform(logText)
End Using
'// 6. Display the final aggregated metrics
Console.WriteLine("--- Log Analysis Summary ---")
Console.WriteLine($"Total Requests: {uc.EvalStr("request_count")}")
Console.WriteLine($"Total Errors: {uc.EvalStr("error_count")}")
Console.WriteLine($"Average Response Time: {uc.EvalStr("total_response_time / request_count")}ms")
Console.WriteLine($"Maximum Response Time: {uc.EvalStr("max_response_time")}ms")
End Sub
End Module
--- Log Analysis Summary ---
Total Requests: 4
Total Errors: 1
Average Response Time: 41.25ms
Maximum Response Time: 120ms Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// 1. Define variables to hold the metrics uc.DefineVariable("request_count = 0") uc.DefineVariable("error_count = 0") uc.DefineVariable("total_response_time = 0.0") uc.DefineVariable("max_response_time = 0.0") '// 2. Create the transformer and define the rule Using t As New uCalc.Transformer(uc) Dim pattern = "{@String:request} {@Number:status} {@Number:time}ms" '// 3. The replacement string uses @Exec for side-effects (updating variables) Dim replacement = " {@Exec: request_count++} {@Exec: total_response_time = total_response_time + Double(time)} {@Exec: max_response_time = Max(max_response_time, Double(time))} {@Exec: iif(Double(status) >= 400, error_count++, 0)} " t.FromTo(pattern, replacement) '// 4. Define the multi-line log data Dim logText = " 2024-10-26 10:00:05 INFO 192.168.1.10 ""GET /api/users HTTP/1.1"" 200 15ms 2024-10-26 10:00:06 INFO 192.168.1.15 ""GET /api/products HTTP/1.1"" 200 22ms 2024-10-26 10:00:07 ERROR 192.168.1.22 ""POST /api/login HTTP/1.1"" 500 120ms 2024-10-26 10:00:08 INFO 192.168.1.10 ""GET /api/users/1 HTTP/1.1"" 200 8ms " '// 5. Run the transformation (the output will be empty as we only use @Exec) t.Transform(logText) End Using '// 6. Display the final aggregated metrics Console.WriteLine("--- Log Analysis Summary ---") Console.WriteLine($"Total Requests: {uc.EvalStr("request_count")}") Console.WriteLine($"Total Errors: {uc.EvalStr("error_count")}") Console.WriteLine($"Average Response Time: {uc.EvalStr("total_response_time / request_count")}ms") Console.WriteLine($"Maximum Response Time: {uc.EvalStr("max_response_time")}ms") End Sub End Module
A complete syntax highlighter that finds keywords, strings, and comments, and wraps them in pseudo-HTML tags for styling.
ID: 1384
using uCalcSoftware;
var uc = new uCalc();
using (var t = new uCalc.Transformer()) {
// 1. Define integer constants for our syntax categories
var TAG_KEYWORD = 1;
var TAG_STRING = 2;
var TAG_COMMENT = 3;
// 2. Define the transformation rules and tag them
t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
t.Pattern("{@String}").SetTag(TAG_STRING);
t.Pattern("// {text}").SetTag(TAG_COMMENT);
// 3. Set the source code and run the find operation
string sourceCode = """
for (i=0; i<10; i++) {
s = "hello";
// comment
}
""";
t.Text = sourceCode;
t.Find();
// 4. Build the highlighted output string
string highlightedOutput = "";
var lastPos = 0;
foreach(var match in t.Matches) {
// Append the plain text between the last match and this one
highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos, match.StartPosition - lastPos);
// Get the tag and wrap the matched text accordingly
var tag = match.Rule.Tag;
if (tag == TAG_KEYWORD) {
highlightedOutput = highlightedOutput + "" + match.Text + " ";
} else if (tag == TAG_STRING) {
highlightedOutput = highlightedOutput + "" + match.Text + " ";
} else if (tag == TAG_COMMENT) {
highlightedOutput = highlightedOutput + "" + match.Text + " ";
} else {
highlightedOutput = highlightedOutput + match.Text; // No tag, append as-is
}
// Update the position for the next iteration
lastPos = match.EndPosition;
}
// Append any remaining text after the last match
highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos);
Console.WriteLine(highlightedOutput);
}
<keyword>for</keyword> (i=0; i<10; i++) {
s = <string>"hello"</string>;
<comment>// comment</comment>
} using uCalcSoftware; var uc = new uCalc(); using (var t = new uCalc.Transformer()) { // 1. Define integer constants for our syntax categories var TAG_KEYWORD = 1; var TAG_STRING = 2; var TAG_COMMENT = 3; // 2. Define the transformation rules and tag them t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD); t.Pattern("{@String}").SetTag(TAG_STRING); t.Pattern("// {text}").SetTag(TAG_COMMENT); // 3. Set the source code and run the find operation string sourceCode = """ for (i=0; i<10; i++) { s = "hello"; // comment } """; t.Text = sourceCode; t.Find(); // 4. Build the highlighted output string string highlightedOutput = ""; var lastPos = 0; foreach(var match in t.Matches) { // Append the plain text between the last match and this one highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos, match.StartPosition - lastPos); // Get the tag and wrap the matched text accordingly var tag = match.Rule.Tag; if (tag == TAG_KEYWORD) { highlightedOutput = highlightedOutput + "<keyword>" + match.Text + "</keyword>"; } else if (tag == TAG_STRING) { highlightedOutput = highlightedOutput + "<string>" + match.Text + "</string>"; } else if (tag == TAG_COMMENT) { highlightedOutput = highlightedOutput + "<comment>" + match.Text + "</comment>"; } else { highlightedOutput = highlightedOutput + match.Text; // No tag, append as-is } // Update the position for the next iteration lastPos = match.EndPosition; } // Append any remaining text after the last match highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos); Console.WriteLine(highlightedOutput); }
#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
// 1. Define integer constants for our syntax categories
auto TAG_KEYWORD = 1;
auto TAG_STRING = 2;
auto TAG_COMMENT = 3;
// 2. Define the transformation rules and tag them
t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
t.Pattern("{@String}").SetTag(TAG_STRING);
t.Pattern("// {text}").SetTag(TAG_COMMENT);
// 3. Set the source code and run the find operation
string sourceCode = R"(for (i=0; i<10; i++) {
s = "hello";
// comment
})";
t.Text(sourceCode);
t.Find();
// 4. Build the highlighted output string
string highlightedOutput = "";
auto lastPos = 0;
for(auto match : t.Matches()) {
// Append the plain text between the last match and this one
highlightedOutput = highlightedOutput + sourceCode.substr(lastPos, match.StartPosition() - lastPos);
// Get the tag and wrap the matched text accordingly
auto tag = match.Rule().Tag();
if (tag == TAG_KEYWORD) {
highlightedOutput = highlightedOutput + "" + match.Text() + " ";
} else if (tag == TAG_STRING) {
highlightedOutput = highlightedOutput + "" + match.Text() + " ";
} else if (tag == TAG_COMMENT) {
highlightedOutput = highlightedOutput + "" + match.Text() + " ";
} else {
highlightedOutput = highlightedOutput + match.Text(); // No tag, append as-is
}
// Update the position for the next iteration
lastPos = match.EndPosition();
}
// Append any remaining text after the last match
highlightedOutput = highlightedOutput + sourceCode.substr(lastPos);
cout << highlightedOutput << endl;
}
}
<keyword>for</keyword> (i=0; i<10; i++) {
s = <string>"hello"</string>;
<comment>// comment</comment>
} #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 // 1. Define integer constants for our syntax categories auto TAG_KEYWORD = 1; auto TAG_STRING = 2; auto TAG_COMMENT = 3; // 2. Define the transformation rules and tag them t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD); t.Pattern("{@String}").SetTag(TAG_STRING); t.Pattern("// {text}").SetTag(TAG_COMMENT); // 3. Set the source code and run the find operation string sourceCode = R"(for (i=0; i<10; i++) { s = "hello"; // comment })"; t.Text(sourceCode); t.Find(); // 4. Build the highlighted output string string highlightedOutput = ""; auto lastPos = 0; for(auto match : t.Matches()) { // Append the plain text between the last match and this one highlightedOutput = highlightedOutput + sourceCode.substr(lastPos, match.StartPosition() - lastPos); // Get the tag and wrap the matched text accordingly auto tag = match.Rule().Tag(); if (tag == TAG_KEYWORD) { highlightedOutput = highlightedOutput + "<keyword>" + match.Text() + "</keyword>"; } else if (tag == TAG_STRING) { highlightedOutput = highlightedOutput + "<string>" + match.Text() + "</string>"; } else if (tag == TAG_COMMENT) { highlightedOutput = highlightedOutput + "<comment>" + match.Text() + "</comment>"; } else { highlightedOutput = highlightedOutput + match.Text(); // No tag, append as-is } // Update the position for the next iteration lastPos = match.EndPosition(); } // Append any remaining text after the last match highlightedOutput = highlightedOutput + sourceCode.substr(lastPos); cout << highlightedOutput << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using t As New uCalc.Transformer()
'// 1. Define integer constants for our syntax categories
Dim TAG_KEYWORD = 1
Dim TAG_STRING = 2
Dim TAG_COMMENT = 3
'// 2. Define the transformation rules and tag them
t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD)
t.Pattern("{@String}").SetTag(TAG_STRING)
t.Pattern("// {text}").SetTag(TAG_COMMENT)
'// 3. Set the source code and run the find operation
Dim sourceCode As String = "for (i=0; i<10; i++) {
s = ""hello"";
// comment
}"
t.Text = sourceCode
t.Find()
'// 4. Build the highlighted output string
Dim highlightedOutput As String = ""
Dim lastPos = 0
For Each match In t.Matches
'// Append the plain text between the last match and this one
highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos, match.StartPosition - lastPos)
'// Get the tag and wrap the matched text accordingly
Dim tag = match.Rule.Tag
If tag = TAG_KEYWORD Then
highlightedOutput = highlightedOutput + "" + match.Text + " "
ElseIf tag = TAG_STRING Then
highlightedOutput = highlightedOutput + "" + match.Text + " "
ElseIf tag = TAG_COMMENT Then
highlightedOutput = highlightedOutput + "" + match.Text + " "
Else
highlightedOutput = highlightedOutput + match.Text '// No tag, append as-is
End If
'// Update the position for the next iteration
lastPos = match.EndPosition
Next
'// Append any remaining text after the last match
highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos)
Console.WriteLine(highlightedOutput)
End Using
End Sub
End Module
<keyword>for</keyword> (i=0; i<10; i++) {
s = <string>"hello"</string>;
<comment>// comment</comment>
} Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using t As New uCalc.Transformer() '// 1. Define integer constants for our syntax categories Dim TAG_KEYWORD = 1 Dim TAG_STRING = 2 Dim TAG_COMMENT = 3 '// 2. Define the transformation rules and tag them t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD) t.Pattern("{@String}").SetTag(TAG_STRING) t.Pattern("// {text}").SetTag(TAG_COMMENT) '// 3. Set the source code and run the find operation Dim sourceCode As String = "for (i=0; i<10; i++) { s = ""hello""; // comment }" t.Text = sourceCode t.Find() '// 4. Build the highlighted output string Dim highlightedOutput As String = "" Dim lastPos = 0 For Each match In t.Matches '// Append the plain text between the last match and this one highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos, match.StartPosition - lastPos) '// Get the tag and wrap the matched text accordingly Dim tag = match.Rule.Tag If tag = TAG_KEYWORD Then highlightedOutput = highlightedOutput + "<keyword>" + match.Text + "</keyword>" ElseIf tag = TAG_STRING Then highlightedOutput = highlightedOutput + "<string>" + match.Text + "</string>" ElseIf tag = TAG_COMMENT Then highlightedOutput = highlightedOutput + "<comment>" + match.Text + "</comment>" Else highlightedOutput = highlightedOutput + match.Text '// No tag, append as-is End If '// Update the position for the next iteration lastPos = match.EndPosition Next '// Append any remaining text after the last match highlightedOutput = highlightedOutput + sourceCode.Substring(lastPos) Console.WriteLine(highlightedOutput) End Using End Sub End Module
A complete, single-pass transformer that converts common BBCode tags (bold, italic, underline, URL, and quote) to their Markdown equivalents.
ID: 1434
using uCalcSoftware;
var uc = new uCalc();
// 1. Setup the Transformer
using (var t = new uCalc.Transformer()) {
// Allow patterns to match across multiple lines
t.DefaultRuleSet.StatementSensitive = false;
// 2. Define the conversion rules
// Simple inline tags
t.FromTo("'['b']'{text}'['/b']'", "**{text}**");
t.FromTo("'['i']'{text}'['/i']'", "*{text}*");
t.FromTo("'['u']'{text}'['/u']'", "{text}");
// URL tag with attribute
t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})");
// Quote block tag
t.FromTo("'['quote']'{content}'['/quote']'", "> {content}");
// 3. Define the input BBCode text
var bbCode = """
Hello, this is a test of the converter.
This text is [b]bold[/b] and this is [i]italic[/i].
You can also [u]underline[/u] text.
Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url].
[quote]This is a block of quoted text.
It can span multiple lines.[/quote]
""";
// 4. Run the transformation and print the result
Console.WriteLine(t.Transform(bbCode));
}
Hello, this is a test of the converter.
This text is **bold** and this is *italic*.
You can also <u>underline</u> text.
Here is a link to the uCalc website: [uCalc](https://www.ucalc.com).
> This is a block of quoted text.
It can span multiple lines.
using uCalcSoftware; var uc = new uCalc(); // 1. Setup the Transformer using (var t = new uCalc.Transformer()) { // Allow patterns to match across multiple lines t.DefaultRuleSet.StatementSensitive = false; // 2. Define the conversion rules // Simple inline tags t.FromTo("'['b']'{text}'['/b']'", "**{text}**"); t.FromTo("'['i']'{text}'['/i']'", "*{text}*"); t.FromTo("'['u']'{text}'['/u']'", "<u>{text}</u>"); // URL tag with attribute t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})"); // Quote block tag t.FromTo("'['quote']'{content}'['/quote']'", "> {content}"); // 3. Define the input BBCode text var bbCode = """ Hello, this is a test of the converter. This text is [b]bold[/b] and this is [i]italic[/i]. You can also [u]underline[/u] text. Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url]. [quote]This is a block of quoted text. It can span multiple lines.[/quote] """; // 4. Run the transformation and print the result Console.WriteLine(t.Transform(bbCode)); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// 1. Setup the Transformer
{
uCalc::Transformer t;
t.Owned(); // Causes t to be released when it goes out of scope
// Allow patterns to match across multiple lines
t.DefaultRuleSet().StatementSensitive(false);
// 2. Define the conversion rules
// Simple inline tags
t.FromTo("'['b']'{text}'['/b']'", "**{text}**");
t.FromTo("'['i']'{text}'['/i']'", "*{text}*");
t.FromTo("'['u']'{text}'['/u']'", "{text}");
// URL tag with attribute
t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})");
// Quote block tag
t.FromTo("'['quote']'{content}'['/quote']'", "> {content}");
// 3. Define the input BBCode text
auto bbCode = R"(
Hello, this is a test of the converter.
This text is [b]bold[/b] and this is [i]italic[/i].
You can also [u]underline[/u] text.
Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url].
[quote]This is a block of quoted text.
It can span multiple lines.[/quote]
)";
// 4. Run the transformation and print the result
cout << t.Transform(bbCode) << endl;
}
}
Hello, this is a test of the converter.
This text is **bold** and this is *italic*.
You can also <u>underline</u> text.
Here is a link to the uCalc website: [uCalc](https://www.ucalc.com).
> This is a block of quoted text.
It can span multiple lines.
#include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // 1. Setup the Transformer { uCalc::Transformer t; t.Owned(); // Causes t to be released when it goes out of scope // Allow patterns to match across multiple lines t.DefaultRuleSet().StatementSensitive(false); // 2. Define the conversion rules // Simple inline tags t.FromTo("'['b']'{text}'['/b']'", "**{text}**"); t.FromTo("'['i']'{text}'['/i']'", "*{text}*"); t.FromTo("'['u']'{text}'['/u']'", "<u>{text}</u>"); // URL tag with attribute t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})"); // Quote block tag t.FromTo("'['quote']'{content}'['/quote']'", "> {content}"); // 3. Define the input BBCode text auto bbCode = R"( Hello, this is a test of the converter. This text is [b]bold[/b] and this is [i]italic[/i]. You can also [u]underline[/u] text. Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url]. [quote]This is a block of quoted text. It can span multiple lines.[/quote] )"; // 4. Run the transformation and print the result cout << t.Transform(bbCode) << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// 1. Setup the Transformer
Using t As New uCalc.Transformer()
'// Allow patterns to match across multiple lines
t.DefaultRuleSet.StatementSensitive = false
'// 2. Define the conversion rules
'// Simple inline tags
t.FromTo("'['b']'{text}'['/b']'", "**{text}**")
t.FromTo("'['i']'{text}'['/i']'", "*{text}*")
t.FromTo("'['u']'{text}'['/u']'", "{text}")
'// URL tag with attribute
t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})")
'// Quote block tag
t.FromTo("'['quote']'{content}'['/quote']'", "> {content}")
'// 3. Define the input BBCode text
Dim bbCode = "
Hello, this is a test of the converter.
This text is [b]bold[/b] and this is [i]italic[/i].
You can also [u]underline[/u] text.
Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url].
[quote]This is a block of quoted text.
It can span multiple lines.[/quote]
"
'// 4. Run the transformation and print the result
Console.WriteLine(t.Transform(bbCode))
End Using
End Sub
End Module
Hello, this is a test of the converter.
This text is **bold** and this is *italic*.
You can also <u>underline</u> text.
Here is a link to the uCalc website: [uCalc](https://www.ucalc.com).
> This is a block of quoted text.
It can span multiple lines.
Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// 1. Setup the Transformer Using t As New uCalc.Transformer() '// Allow patterns to match across multiple lines t.DefaultRuleSet.StatementSensitive = false '// 2. Define the conversion rules '// Simple inline tags t.FromTo("'['b']'{text}'['/b']'", "**{text}**") t.FromTo("'['i']'{text}'['/i']'", "*{text}*") t.FromTo("'['u']'{text}'['/u']'", "<u>{text}</u>") '// URL tag with attribute t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})") '// Quote block tag t.FromTo("'['quote']'{content}'['/quote']'", "> {content}") '// 3. Define the input BBCode text Dim bbCode = " Hello, this is a test of the converter. This text is [b]bold[/b] and this is [i]italic[/i]. You can also [u]underline[/u] text. Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url]. [quote]This is a block of quoted text. It can span multiple lines.[/quote] " '// 4. Run the transformation and print the result Console.WriteLine(t.Transform(bbCode)) End Using End Sub End Module
A complete, single-pass transformer that converts headers, list items, bold, and italic Markdown syntax to HTML.
ID: 1347
See:
using uCalcSoftware;
var uc = new uCalc();
// 1. Setup the Transformer
using (var t = new uCalc.Transformer()) {
t.DefaultRuleSet.RewindOnChange = true;
// 2. Define Rules (General rules first, specific rules last for LIFO precedence)
// -- Inline rules --
// Italic is defined before Bold, giving Bold higher precedence.
t.FromTo("*{text}*", "{text}");
t.FromTo("**{text}**", "{text}");
// -- Block-level rules --
t.FromTo("#{@Whitespace}{line}", "{line}
");
t.FromTo("*{@Whitespace}{line}", " {line} ");
// 3. Define the input Markdown text
var markdown = """
# Main Header
* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.
Another paragraph with **bold** and *italic*.
""";
// 4. Run the transformation and print the result
Console.WriteLine(t.Transform(markdown));
}
<h1>Main Header</h1>
<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>
Another paragraph with <b>bold</b> and <i>italic</i>. using uCalcSoftware; var uc = new uCalc(); // 1. Setup the Transformer using (var t = new uCalc.Transformer()) { t.DefaultRuleSet.RewindOnChange = true; // 2. Define Rules (General rules first, specific rules last for LIFO precedence) // -- Inline rules -- // Italic is defined before Bold, giving Bold higher precedence. t.FromTo("*{text}*", "<i>{text}</i>"); t.FromTo("**{text}**", "<b>{text}</b>"); // -- Block-level rules -- t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>"); t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>"); // 3. Define the input Markdown text var markdown = """ # Main Header * First list item * Second list item with **bold** text. * Third list item with *italic* text. Another paragraph with **bold** and *italic*. """; // 4. Run the transformation and print the result Console.WriteLine(t.Transform(markdown)); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// 1. Setup the Transformer
{
uCalc::Transformer t;
t.Owned(); // Causes t to be released when it goes out of scope
t.DefaultRuleSet().RewindOnChange(true);
// 2. Define Rules (General rules first, specific rules last for LIFO precedence)
// -- Inline rules --
// Italic is defined before Bold, giving Bold higher precedence.
t.FromTo("*{text}*", "{text}");
t.FromTo("**{text}**", "{text}");
// -- Block-level rules --
t.FromTo("#{@Whitespace}{line}", "{line}
");
t.FromTo("*{@Whitespace}{line}", "{line} ");
// 3. Define the input Markdown text
auto markdown = R"(
# Main Header
* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.
Another paragraph with **bold** and *italic*.
)";
// 4. Run the transformation and print the result
cout << t.Transform(markdown) << endl;
}
}
<h1>Main Header</h1>
<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>
Another paragraph with <b>bold</b> and <i>italic</i>. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // 1. Setup the Transformer { uCalc::Transformer t; t.Owned(); // Causes t to be released when it goes out of scope t.DefaultRuleSet().RewindOnChange(true); // 2. Define Rules (General rules first, specific rules last for LIFO precedence) // -- Inline rules -- // Italic is defined before Bold, giving Bold higher precedence. t.FromTo("*{text}*", "<i>{text}</i>"); t.FromTo("**{text}**", "<b>{text}</b>"); // -- Block-level rules -- t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>"); t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>"); // 3. Define the input Markdown text auto markdown = R"( # Main Header * First list item * Second list item with **bold** text. * Third list item with *italic* text. Another paragraph with **bold** and *italic*. )"; // 4. Run the transformation and print the result cout << t.Transform(markdown) << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// 1. Setup the Transformer
Using t As New uCalc.Transformer()
t.DefaultRuleSet.RewindOnChange = true
'// 2. Define Rules (General rules first, specific rules last for LIFO precedence)
'// -- Inline rules --
'// Italic is defined before Bold, giving Bold higher precedence.
t.FromTo("*{text}*", "{text}")
t.FromTo("**{text}**", "{text}")
'// -- Block-level rules --
t.FromTo("#{@Whitespace}{line}", "{line}
")
t.FromTo("*{@Whitespace}{line}", " {line} ")
'// 3. Define the input Markdown text
Dim markdown = "
# Main Header
* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.
Another paragraph with **bold** and *italic*.
"
'// 4. Run the transformation and print the result
Console.WriteLine(t.Transform(markdown))
End Using
End Sub
End Module
<h1>Main Header</h1>
<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>
Another paragraph with <b>bold</b> and <i>italic</i>. Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// 1. Setup the Transformer Using t As New uCalc.Transformer() t.DefaultRuleSet.RewindOnChange = true '// 2. Define Rules (General rules first, specific rules last for LIFO precedence) '// -- Inline rules -- '// Italic is defined before Bold, giving Bold higher precedence. t.FromTo("*{text}*", "<i>{text}</i>") t.FromTo("**{text}**", "<b>{text}</b>") '// -- Block-level rules -- t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>") t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>") '// 3. Define the input Markdown text Dim markdown = " # Main Header * First list item * Second list item with **bold** text. * Third list item with *italic* text. Another paragraph with **bold** and *italic*. " '// 4. Run the transformation and print the result Console.WriteLine(t.Transform(markdown)) End Using End Sub End Module
A complete, working command-line REPL that reads user input, evaluates it with uCalc, and prints the result or any error messages.
ID: 1357
using uCalcSoftware;
var uc = new uCalc();
// This example simulates a full REPL session by iterating through a series of inputs.
Console.WriteLine("uCalc Interactive Shell (simulated session)");
Console.WriteLine("Type 'exit' or 'quit' to end.");
Console.WriteLine("");
string[] inputs = {
"10 * (5 + 3)",
"UCase('hello world')",
"1 / 0",
"1 +",
"exit"
};
var index = 0;
do {
Console.Write("> ");
// Simulate reading from the console by assigning inputs sequentially.
// In a real application, this would read the input interactively from the console.
var input = inputs[index];
Console.WriteLine(input);
// 1. Check for an exit command
if (input == "exit" || input == "quit") {
Console.WriteLine("Exiting.");
return ;
}
// 2. Evaluate the input and 3. Print the result
Console.WriteLine(uc.EvalStr(input));
Console.WriteLine("");
index = index + 1;
} while (true);
uCalc Interactive Shell (simulated session)
Type 'exit' or 'quit' to end.
> 10 * (5 + 3)
80
> UCase('hello world')
HELLO WORLD
> 1 / 0
inf
> 1 +
Syntax error
> exit
Exiting. using uCalcSoftware; var uc = new uCalc(); // This example simulates a full REPL session by iterating through a series of inputs. Console.WriteLine("uCalc Interactive Shell (simulated session)"); Console.WriteLine("Type 'exit' or 'quit' to end."); Console.WriteLine(""); string[] inputs = { "10 * (5 + 3)", "UCase('hello world')", "1 / 0", "1 +", "exit" }; var index = 0; do { Console.Write("> "); // Simulate reading from the console by assigning inputs sequentially. // In a real application, this would read the input interactively from the console. var input = inputs[index]; Console.WriteLine(input); // 1. Check for an exit command if (input == "exit" || input == "quit") { Console.WriteLine("Exiting."); return ; } // 2. Evaluate the input and 3. Print the result Console.WriteLine(uc.EvalStr(input)); Console.WriteLine(""); index = index + 1; } while (true);
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// This example simulates a full REPL session by iterating through a series of inputs.
cout << "uCalc Interactive Shell (simulated session)" << endl;
cout << "Type 'exit' or 'quit' to end." << endl;
cout << "" << endl;
vector inputs = {
"10 * (5 + 3)",
"UCase('hello world')",
"1 / 0",
"1 +",
"exit"
};
auto index = 0;
do {
cout << "> ";
// Simulate reading from the console by assigning inputs sequentially.
// In a real application, this would read the input interactively from the console.
auto input = inputs[index];
cout << input << endl;
// 1. Check for an exit command
if (input == "exit" || input == "quit") {
cout << "Exiting." << endl;
return 0;
}
// 2. Evaluate the input and 3. Print the result
cout << uc.EvalStr(input) << endl;
cout << "" << endl;
index = index + 1;
} while (true);
}
uCalc Interactive Shell (simulated session)
Type 'exit' or 'quit' to end.
> 10 * (5 + 3)
80
> UCase('hello world')
HELLO WORLD
> 1 / 0
inf
> 1 +
Syntax error
> exit
Exiting. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // This example simulates a full REPL session by iterating through a series of inputs. cout << "uCalc Interactive Shell (simulated session)" << endl; cout << "Type 'exit' or 'quit' to end." << endl; cout << "" << endl; vector<string> inputs = { "10 * (5 + 3)", "UCase('hello world')", "1 / 0", "1 +", "exit" }; auto index = 0; do { cout << "> "; // Simulate reading from the console by assigning inputs sequentially. // In a real application, this would read the input interactively from the console. auto input = inputs[index]; cout << input << endl; // 1. Check for an exit command if (input == "exit" || input == "quit") { cout << "Exiting." << endl; return 0; } // 2. Evaluate the input and 3. Print the result cout << uc.EvalStr(input) << endl; cout << "" << endl; index = index + 1; } while (true); }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// This example simulates a full REPL session by iterating through a series of inputs.
Console.WriteLine("uCalc Interactive Shell (simulated session)")
Console.WriteLine("Type 'exit' or 'quit' to end.")
Console.WriteLine("")
Dim inputs() As String = {
"10 * (5 + 3)",
"UCase('hello world')",
"1 / 0",
"1 +",
"exit"
}
Dim index = 0
Do
Console.Write("> ")
'// Simulate reading from the console by assigning inputs sequentially.
'// In a real application, this would read the input interactively from the console.
Dim input = inputs(index)
Console.WriteLine(input)
'// 1. Check for an exit command
If input = "exit" Or input = "quit" Then
Console.WriteLine("Exiting.")
return
End If
'// 2. Evaluate the input and 3. Print the result
Console.WriteLine(uc.EvalStr(input))
Console.WriteLine("")
index = index + 1
Loop While true
End Sub
End Module
uCalc Interactive Shell (simulated session)
Type 'exit' or 'quit' to end.
> 10 * (5 + 3)
80
> UCase('hello world')
HELLO WORLD
> 1 / 0
inf
> 1 +
Syntax error
> exit
Exiting. Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// This example simulates a full REPL session by iterating through a series of inputs. Console.WriteLine("uCalc Interactive Shell (simulated session)") Console.WriteLine("Type 'exit' or 'quit' to end.") Console.WriteLine("") Dim inputs() As String = { "10 * (5 + 3)", "UCase('hello world')", "1 / 0", "1 +", "exit" } Dim index = 0 Do Console.Write("> ") '// Simulate reading from the console by assigning inputs sequentially. '// In a real application, this would read the input interactively from the console. Dim input = inputs(index) Console.WriteLine(input) '// 1. Check for an exit command If input = "exit" Or input = "quit" Then Console.WriteLine("Exiting.") return End If '// 2. Evaluate the input and 3. Print the result Console.WriteLine(uc.EvalStr(input)) Console.WriteLine("") index = index + 1 Loop While true End Sub End Module
A complete, working natural language date parser that handles keywords, relative days, and future durations.
ID: 1415
using uCalcSoftware;
var uc = new uCalc();
static void GetCurrentDate(uCalc.Callback cb) {
// In a real application, this would return the system's current date.
// For this example, we'll use a fixed date for consistent output.
// Let's pretend today is January 15, 2026 (a Thursday).
cb.Return(46036); // Using Excel-style date serial number for simplicity
}
static void AddDuration(uCalc.Callback cb) {
var startDate = cb.Arg(1);
var number = cb.Arg(2);
var unit = cb.ArgStr(3);
var result = startDate;
if (unit == "day" || unit == "days") {
result = startDate + number;
} else if (unit == "week" || unit == "weeks") {
result = startDate + (number * 7);
} else if (unit == "month" || unit == "months") {
result = startDate + (number * 30); // Approximation for example
}
cb.Return(result);
}
static void GetNextDayOfWeek(uCalc.Callback cb) {
var dayName = cb.ArgStr(1);
var today = 46036; // Thursday, Jan 15, 2026
var todayDayOfWeek = 5; // 1=Sun, 2=Mon, ..., 5=Thu
var targetDay = 0;
if (dayName == "Sunday") targetDay = 1;
if (dayName == "Monday") targetDay = 2;
if (dayName == "Tuesday") targetDay = 3;
if (dayName == "Wednesday") targetDay = 4;
if (dayName == "Thursday") targetDay = 5;
if (dayName == "Friday") targetDay = 6;
if (dayName == "Saturday") targetDay = 7;
var daysToAdd = (targetDay - todayDayOfWeek + 7) % 7;
// Always get the *next* week's day
if (daysToAdd == 0) daysToAdd = 7;
cb.Return(today + daysToAdd);
}
static void FormatDate(uCalc.Callback cb) {
// This is a simplified formatter for the example.
// A real implementation would be more robust.
var dateSerial = cb.Arg(1);
if (dateSerial == 46036) cb.ReturnStr("2026-01-15");
if (dateSerial == 46037) cb.ReturnStr("2026-01-16");
if (dateSerial == 46039) cb.ReturnStr("2026-01-18");
if (dateSerial == 46043) cb.ReturnStr("2026-01-22");
if (dateSerial == 46050) cb.ReturnStr("2026-01-29");
if (dateSerial == 46096) cb.ReturnStr("2026-03-16");
}
// 1. Define the helper functions in the uCalc engine
uc.DefineFunction("GetCurrentDate()", GetCurrentDate);
uc.DefineFunction("AddDuration(date, num, unit As String)", AddDuration);
uc.DefineFunction("GetNextDayOfWeek(dayName As String)", GetNextDayOfWeek);
uc.DefineFunction("FormatDate(date) As String", FormatDate);
// 2. Create the transformer and define the DSL rules
using (var t = new uCalc.Transformer(uc)) {
// Set case-insensitivity for all rules
t.DefaultRuleSet.CaseSensitive = false;
// Define the rules
t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}");
t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}");
t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}");
t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}");
// 3. Process the input strings
Console.WriteLine($"Input: 'today' -> Output: {t.Transform("today")}");
Console.WriteLine($"Input: 'tomorrow' -> Output: {t.Transform("tomorrow")}");
Console.WriteLine($"Input: 'next Sunday' -> Output: {t.Transform("next Sunday")}");
Console.WriteLine($"Input: 'in 2 weeks' -> Output: {t.Transform("in 2 weeks")}");
Console.WriteLine($"Input: 'in 60 days' -> Output: {t.Transform("in 60 days")}");
}
Input: 'today' -> Output: 2026-01-15
Input: 'tomorrow' -> Output: 2026-01-16
Input: 'next Sunday' -> Output: 2026-01-18
Input: 'in 2 weeks' -> Output: 2026-01-29
Input: 'in 60 days' -> Output: 2026-03-16 using uCalcSoftware; var uc = new uCalc(); static void GetCurrentDate(uCalc.Callback cb) { // In a real application, this would return the system's current date. // For this example, we'll use a fixed date for consistent output. // Let's pretend today is January 15, 2026 (a Thursday). cb.Return(46036); // Using Excel-style date serial number for simplicity } static void AddDuration(uCalc.Callback cb) { var startDate = cb.Arg(1); var number = cb.Arg(2); var unit = cb.ArgStr(3); var result = startDate; if (unit == "day" || unit == "days") { result = startDate + number; } else if (unit == "week" || unit == "weeks") { result = startDate + (number * 7); } else if (unit == "month" || unit == "months") { result = startDate + (number * 30); // Approximation for example } cb.Return(result); } static void GetNextDayOfWeek(uCalc.Callback cb) { var dayName = cb.ArgStr(1); var today = 46036; // Thursday, Jan 15, 2026 var todayDayOfWeek = 5; // 1=Sun, 2=Mon, ..., 5=Thu var targetDay = 0; if (dayName == "Sunday") targetDay = 1; if (dayName == "Monday") targetDay = 2; if (dayName == "Tuesday") targetDay = 3; if (dayName == "Wednesday") targetDay = 4; if (dayName == "Thursday") targetDay = 5; if (dayName == "Friday") targetDay = 6; if (dayName == "Saturday") targetDay = 7; var daysToAdd = (targetDay - todayDayOfWeek + 7) % 7; // Always get the *next* week's day if (daysToAdd == 0) daysToAdd = 7; cb.Return(today + daysToAdd); } static void FormatDate(uCalc.Callback cb) { // This is a simplified formatter for the example. // A real implementation would be more robust. var dateSerial = cb.Arg(1); if (dateSerial == 46036) cb.ReturnStr("2026-01-15"); if (dateSerial == 46037) cb.ReturnStr("2026-01-16"); if (dateSerial == 46039) cb.ReturnStr("2026-01-18"); if (dateSerial == 46043) cb.ReturnStr("2026-01-22"); if (dateSerial == 46050) cb.ReturnStr("2026-01-29"); if (dateSerial == 46096) cb.ReturnStr("2026-03-16"); } // 1. Define the helper functions in the uCalc engine uc.DefineFunction("GetCurrentDate()", GetCurrentDate); uc.DefineFunction("AddDuration(date, num, unit As String)", AddDuration); uc.DefineFunction("GetNextDayOfWeek(dayName As String)", GetNextDayOfWeek); uc.DefineFunction("FormatDate(date) As String", FormatDate); // 2. Create the transformer and define the DSL rules using (var t = new uCalc.Transformer(uc)) { // Set case-insensitivity for all rules t.DefaultRuleSet.CaseSensitive = false; // Define the rules t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}"); t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}"); t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}"); t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}"); // 3. Process the input strings Console.WriteLine($"Input: 'today' -> Output: {t.Transform("today")}"); Console.WriteLine($"Input: 'tomorrow' -> Output: {t.Transform("tomorrow")}"); Console.WriteLine($"Input: 'next Sunday' -> Output: {t.Transform("next Sunday")}"); Console.WriteLine($"Input: 'in 2 weeks' -> Output: {t.Transform("in 2 weeks")}"); Console.WriteLine($"Input: 'in 60 days' -> Output: {t.Transform("in 60 days")}"); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call GetCurrentDate(uCalcBase::Callback cb) {
// In a real application, this would return the system's current date.
// For this example, we'll use a fixed date for consistent output.
// Let's pretend today is January 15, 2026 (a Thursday).
cb.Return(46036); // Using Excel-style date serial number for simplicity
}
void ucalc_call AddDuration(uCalcBase::Callback cb) {
auto startDate = cb.Arg(1);
auto number = cb.Arg(2);
auto unit = cb.ArgStr(3);
auto result = startDate;
if (unit == "day" || unit == "days") {
result = startDate + number;
} else if (unit == "week" || unit == "weeks") {
result = startDate + (number * 7);
} else if (unit == "month" || unit == "months") {
result = startDate + (number * 30); // Approximation for example
}
cb.Return(result);
}
void ucalc_call GetNextDayOfWeek(uCalcBase::Callback cb) {
auto dayName = cb.ArgStr(1);
auto today = 46036; // Thursday, Jan 15, 2026
auto todayDayOfWeek = 5; // 1=Sun, 2=Mon, ..., 5=Thu
auto targetDay = 0;
if (dayName == "Sunday") targetDay = 1;
if (dayName == "Monday") targetDay = 2;
if (dayName == "Tuesday") targetDay = 3;
if (dayName == "Wednesday") targetDay = 4;
if (dayName == "Thursday") targetDay = 5;
if (dayName == "Friday") targetDay = 6;
if (dayName == "Saturday") targetDay = 7;
auto daysToAdd = (targetDay - todayDayOfWeek + 7) % 7;
// Always get the *next* week's day
if (daysToAdd == 0) daysToAdd = 7;
cb.Return(today + daysToAdd);
}
void ucalc_call FormatDate(uCalcBase::Callback cb) {
// This is a simplified formatter for the example.
// A real implementation would be more robust.
auto dateSerial = cb.Arg(1);
if (dateSerial == 46036) cb.ReturnStr("2026-01-15");
if (dateSerial == 46037) cb.ReturnStr("2026-01-16");
if (dateSerial == 46039) cb.ReturnStr("2026-01-18");
if (dateSerial == 46043) cb.ReturnStr("2026-01-22");
if (dateSerial == 46050) cb.ReturnStr("2026-01-29");
if (dateSerial == 46096) cb.ReturnStr("2026-03-16");
}
int main() {
uCalc uc;
// 1. Define the helper functions in the uCalc engine
uc.DefineFunction("GetCurrentDate()", GetCurrentDate);
uc.DefineFunction("AddDuration(date, num, unit As String)", AddDuration);
uc.DefineFunction("GetNextDayOfWeek(dayName As String)", GetNextDayOfWeek);
uc.DefineFunction("FormatDate(date) As String", FormatDate);
// 2. Create the transformer and define the DSL rules
{
uCalc::Transformer t(uc);
t.Owned(); // Causes t to be released when it goes out of scope
// Set case-insensitivity for all rules
t.DefaultRuleSet().CaseSensitive(false);
// Define the rules
t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}");
t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}");
t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}");
t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}");
// 3. Process the input strings
cout << "Input: 'today' -> Output: " << t.Transform("today") << endl;
cout << "Input: 'tomorrow' -> Output: " << t.Transform("tomorrow") << endl;
cout << "Input: 'next Sunday' -> Output: " << t.Transform("next Sunday") << endl;
cout << "Input: 'in 2 weeks' -> Output: " << t.Transform("in 2 weeks") << endl;
cout << "Input: 'in 60 days' -> Output: " << t.Transform("in 60 days") << endl;
}
}
Input: 'today' -> Output: 2026-01-15
Input: 'tomorrow' -> Output: 2026-01-16
Input: 'next Sunday' -> Output: 2026-01-18
Input: 'in 2 weeks' -> Output: 2026-01-29
Input: 'in 60 days' -> Output: 2026-03-16 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call GetCurrentDate(uCalcBase::Callback cb) { // In a real application, this would return the system's current date. // For this example, we'll use a fixed date for consistent output. // Let's pretend today is January 15, 2026 (a Thursday). cb.Return(46036); // Using Excel-style date serial number for simplicity } void ucalc_call AddDuration(uCalcBase::Callback cb) { auto startDate = cb.Arg(1); auto number = cb.Arg(2); auto unit = cb.ArgStr(3); auto result = startDate; if (unit == "day" || unit == "days") { result = startDate + number; } else if (unit == "week" || unit == "weeks") { result = startDate + (number * 7); } else if (unit == "month" || unit == "months") { result = startDate + (number * 30); // Approximation for example } cb.Return(result); } void ucalc_call GetNextDayOfWeek(uCalcBase::Callback cb) { auto dayName = cb.ArgStr(1); auto today = 46036; // Thursday, Jan 15, 2026 auto todayDayOfWeek = 5; // 1=Sun, 2=Mon, ..., 5=Thu auto targetDay = 0; if (dayName == "Sunday") targetDay = 1; if (dayName == "Monday") targetDay = 2; if (dayName == "Tuesday") targetDay = 3; if (dayName == "Wednesday") targetDay = 4; if (dayName == "Thursday") targetDay = 5; if (dayName == "Friday") targetDay = 6; if (dayName == "Saturday") targetDay = 7; auto daysToAdd = (targetDay - todayDayOfWeek + 7) % 7; // Always get the *next* week's day if (daysToAdd == 0) daysToAdd = 7; cb.Return(today + daysToAdd); } void ucalc_call FormatDate(uCalcBase::Callback cb) { // This is a simplified formatter for the example. // A real implementation would be more robust. auto dateSerial = cb.Arg(1); if (dateSerial == 46036) cb.ReturnStr("2026-01-15"); if (dateSerial == 46037) cb.ReturnStr("2026-01-16"); if (dateSerial == 46039) cb.ReturnStr("2026-01-18"); if (dateSerial == 46043) cb.ReturnStr("2026-01-22"); if (dateSerial == 46050) cb.ReturnStr("2026-01-29"); if (dateSerial == 46096) cb.ReturnStr("2026-03-16"); } int main() { uCalc uc; // 1. Define the helper functions in the uCalc engine uc.DefineFunction("GetCurrentDate()", GetCurrentDate); uc.DefineFunction("AddDuration(date, num, unit As String)", AddDuration); uc.DefineFunction("GetNextDayOfWeek(dayName As String)", GetNextDayOfWeek); uc.DefineFunction("FormatDate(date) As String", FormatDate); // 2. Create the transformer and define the DSL rules { uCalc::Transformer t(uc); t.Owned(); // Causes t to be released when it goes out of scope // Set case-insensitivity for all rules t.DefaultRuleSet().CaseSensitive(false); // Define the rules t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}"); t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}"); t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}"); t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}"); // 3. Process the input strings cout << "Input: 'today' -> Output: " << t.Transform("today") << endl; cout << "Input: 'tomorrow' -> Output: " << t.Transform("tomorrow") << endl; cout << "Input: 'next Sunday' -> Output: " << t.Transform("next Sunday") << endl; cout << "Input: 'in 2 weeks' -> Output: " << t.Transform("in 2 weeks") << endl; cout << "Input: 'in 60 days' -> Output: " << t.Transform("in 60 days") << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub GetCurrentDate(ByVal cb As uCalc.Callback)
'// In a real application, this would return the system's current date.
'// For this example, we'll use a fixed date for consistent output.
'// Let's pretend today is January 15, 2026 (a Thursday).
cb.Return(46036) '// Using Excel-style date serial number for simplicity
End Sub
Public Sub AddDuration(ByVal cb As uCalc.Callback)
Dim startDate = cb.Arg(1)
Dim number = cb.Arg(2)
Dim unit = cb.ArgStr(3)
Dim result = startDate
If unit = "day" Or unit = "days" Then
result = startDate + number
ElseIf unit = "week" Or unit = "weeks" Then
result = startDate + (number * 7)
ElseIf unit = "month" Or unit = "months" Then
result = startDate + (number * 30) '// Approximation for example
End If
cb.Return(result)
End Sub
Public Sub GetNextDayOfWeek(ByVal cb As uCalc.Callback)
Dim dayName = cb.ArgStr(1)
Dim today = 46036 '// Thursday, Jan 15, 2026
Dim todayDayOfWeek = 5 '// 1=Sun, 2=Mon, ..., 5=Thu
Dim targetDay = 0
If dayName = "Sunday" Then targetDay = 1
If dayName = "Monday" Then targetDay = 2
If dayName = "Tuesday" Then targetDay = 3
If dayName = "Wednesday" Then targetDay = 4
If dayName = "Thursday" Then targetDay = 5
If dayName = "Friday" Then targetDay = 6
If dayName = "Saturday" Then targetDay = 7
Dim daysToAdd = (targetDay - todayDayOfWeek + 7) Mod 7
'// Always get the *next* week's day
If daysToAdd = 0 Then daysToAdd = 7
cb.Return(today + daysToAdd)
End Sub
Public Sub FormatDate(ByVal cb As uCalc.Callback)
'// This is a simplified formatter for the example.
'// A real implementation would be more robust.
Dim dateSerial = cb.Arg(1)
If dateSerial = 46036 Then cb.ReturnStr("2026-01-15")
If dateSerial = 46037 Then cb.ReturnStr("2026-01-16")
If dateSerial = 46039 Then cb.ReturnStr("2026-01-18")
If dateSerial = 46043 Then cb.ReturnStr("2026-01-22")
If dateSerial = 46050 Then cb.ReturnStr("2026-01-29")
If dateSerial = 46096 Then cb.ReturnStr("2026-03-16")
End Sub
Public Sub Main()
Dim uc As New uCalc()
'// 1. Define the helper functions in the uCalc engine
uc.DefineFunction("GetCurrentDate()", AddressOf GetCurrentDate)
uc.DefineFunction("AddDuration(date, num, unit As String)", AddressOf AddDuration)
uc.DefineFunction("GetNextDayOfWeek(dayName As String)", AddressOf GetNextDayOfWeek)
uc.DefineFunction("FormatDate(date) As String", AddressOf FormatDate)
'// 2. Create the transformer and define the DSL rules
Using t As New uCalc.Transformer(uc)
'// Set case-insensitivity for all rules
t.DefaultRuleSet.CaseSensitive = false
'// Define the rules
t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}")
t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}")
t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}")
t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}")
'// 3. Process the input strings
Console.WriteLine($"Input: 'today' -> Output: {t.Transform("today")}")
Console.WriteLine($"Input: 'tomorrow' -> Output: {t.Transform("tomorrow")}")
Console.WriteLine($"Input: 'next Sunday' -> Output: {t.Transform("next Sunday")}")
Console.WriteLine($"Input: 'in 2 weeks' -> Output: {t.Transform("in 2 weeks")}")
Console.WriteLine($"Input: 'in 60 days' -> Output: {t.Transform("in 60 days")}")
End Using
End Sub
End Module
Input: 'today' -> Output: 2026-01-15
Input: 'tomorrow' -> Output: 2026-01-16
Input: 'next Sunday' -> Output: 2026-01-18
Input: 'in 2 weeks' -> Output: 2026-01-29
Input: 'in 60 days' -> Output: 2026-03-16 Imports System Imports uCalcSoftware Public Module Program Public Sub GetCurrentDate(ByVal cb As uCalc.Callback) '// In a real application, this would return the system's current date. '// For this example, we'll use a fixed date for consistent output. '// Let's pretend today is January 15, 2026 (a Thursday). cb.Return(46036) '// Using Excel-style date serial number for simplicity End Sub Public Sub AddDuration(ByVal cb As uCalc.Callback) Dim startDate = cb.Arg(1) Dim number = cb.Arg(2) Dim unit = cb.ArgStr(3) Dim result = startDate If unit = "day" Or unit = "days" Then result = startDate + number ElseIf unit = "week" Or unit = "weeks" Then result = startDate + (number * 7) ElseIf unit = "month" Or unit = "months" Then result = startDate + (number * 30) '// Approximation for example End If cb.Return(result) End Sub Public Sub GetNextDayOfWeek(ByVal cb As uCalc.Callback) Dim dayName = cb.ArgStr(1) Dim today = 46036 '// Thursday, Jan 15, 2026 Dim todayDayOfWeek = 5 '// 1=Sun, 2=Mon, ..., 5=Thu Dim targetDay = 0 If dayName = "Sunday" Then targetDay = 1 If dayName = "Monday" Then targetDay = 2 If dayName = "Tuesday" Then targetDay = 3 If dayName = "Wednesday" Then targetDay = 4 If dayName = "Thursday" Then targetDay = 5 If dayName = "Friday" Then targetDay = 6 If dayName = "Saturday" Then targetDay = 7 Dim daysToAdd = (targetDay - todayDayOfWeek + 7) Mod 7 '// Always get the *next* week's day If daysToAdd = 0 Then daysToAdd = 7 cb.Return(today + daysToAdd) End Sub Public Sub FormatDate(ByVal cb As uCalc.Callback) '// This is a simplified formatter for the example. '// A real implementation would be more robust. Dim dateSerial = cb.Arg(1) If dateSerial = 46036 Then cb.ReturnStr("2026-01-15") If dateSerial = 46037 Then cb.ReturnStr("2026-01-16") If dateSerial = 46039 Then cb.ReturnStr("2026-01-18") If dateSerial = 46043 Then cb.ReturnStr("2026-01-22") If dateSerial = 46050 Then cb.ReturnStr("2026-01-29") If dateSerial = 46096 Then cb.ReturnStr("2026-03-16") End Sub Public Sub Main() Dim uc As New uCalc() '// 1. Define the helper functions in the uCalc engine uc.DefineFunction("GetCurrentDate()", AddressOf GetCurrentDate) uc.DefineFunction("AddDuration(date, num, unit As String)", AddressOf AddDuration) uc.DefineFunction("GetNextDayOfWeek(dayName As String)", AddressOf GetNextDayOfWeek) uc.DefineFunction("FormatDate(date) As String", AddressOf FormatDate) '// 2. Create the transformer and define the DSL rules Using t As New uCalc.Transformer(uc) '// Set case-insensitivity for all rules t.DefaultRuleSet.CaseSensitive = false '// Define the rules t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}") t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}") t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}") t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}") '// 3. Process the input strings Console.WriteLine($"Input: 'today' -> Output: {t.Transform("today")}") Console.WriteLine($"Input: 'tomorrow' -> Output: {t.Transform("tomorrow")}") Console.WriteLine($"Input: 'next Sunday' -> Output: {t.Transform("next Sunday")}") Console.WriteLine($"Input: 'in 2 weeks' -> Output: {t.Transform("in 2 weeks")}") Console.WriteLine($"Input: 'in 60 days' -> Output: {t.Transform("in 60 days")}") End Using End Sub End Module
A function that unconditionally raises a custom error.
ID: 482
using uCalcSoftware;
var uc = new uCalc();
static void MyHandler(Handle_uCalc h) {
var uc = new uCalc(h);
// This handler just logs the error and aborts
Console.WriteLine($"Error Handler Caught: {uc.Error.Message}");
}
static void MyFunc(uCalc.Callback cb) {
// This function always fails with a custom message
cb.Error.Raise("Validation failed for input.");
}
uc.Error.AddHandler(MyHandler);
uc.DefineFunction("Validate()", MyFunc);
uc.EvalStr("Validate()"); // This call will trigger the error
Error Handler Caught: Validation failed for input. using uCalcSoftware; var uc = new uCalc(); static void MyHandler(Handle_uCalc h) { var uc = new uCalc(h); // This handler just logs the error and aborts Console.WriteLine($"Error Handler Caught: {uc.Error.Message}"); } static void MyFunc(uCalc.Callback cb) { // This function always fails with a custom message cb.Error.Raise("Validation failed for input."); } uc.Error.AddHandler(MyHandler); uc.DefineFunction("Validate()", MyFunc); uc.EvalStr("Validate()"); // This call will trigger the error
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call MyHandler(Handle_uCalc h) {
auto uc = uCalc(h);
// This handler just logs the error and aborts
cout << "Error Handler Caught: " << uc.Error().Message() << endl;
}
void ucalc_call MyFunc(uCalcBase::Callback cb) {
// This function always fails with a custom message
cb.Error().Raise("Validation failed for input.");
}
int main() {
uCalc uc;
uc.Error().AddHandler(MyHandler);
uc.DefineFunction("Validate()", MyFunc);
uc.EvalStr("Validate()"); // This call will trigger the error
}
Error Handler Caught: Validation failed for input. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call MyHandler(Handle_uCalc h) { auto uc = uCalc(h); // This handler just logs the error and aborts cout << "Error Handler Caught: " << uc.Error().Message() << endl; } void ucalc_call MyFunc(uCalcBase::Callback cb) { // This function always fails with a custom message cb.Error().Raise("Validation failed for input."); } int main() { uCalc uc; uc.Error().AddHandler(MyHandler); uc.DefineFunction("Validate()", MyFunc); uc.EvalStr("Validate()"); // This call will trigger the error }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub MyHandler(ByVal h As Handle_uCalc)
Dim uc As New uCalc(h)
'// This handler just logs the error and aborts
Console.WriteLine($"Error Handler Caught: {uc.Error.Message}")
End Sub
Public Sub MyFunc(ByVal cb As uCalc.Callback)
'// This function always fails with a custom message
cb.Error.Raise("Validation failed for input.")
End Sub
Public Sub Main()
Dim uc As New uCalc()
uc.Error.AddHandler(AddressOf MyHandler)
uc.DefineFunction("Validate()", AddressOf MyFunc)
uc.EvalStr("Validate()") '// This call will trigger the error
End Sub
End Module
Error Handler Caught: Validation failed for input. Imports System Imports uCalcSoftware Public Module Program Public Sub MyHandler(ByVal h As Handle_uCalc) Dim uc As New uCalc(h) '// This handler just logs the error and aborts Console.WriteLine($"Error Handler Caught: {uc.Error.Message}") End Sub Public Sub MyFunc(ByVal cb As uCalc.Callback) '// This function always fails with a custom message cb.Error.Raise("Validation failed for input.") End Sub Public Sub Main() Dim uc As New uCalc() uc.Error.AddHandler(AddressOf MyHandler) uc.DefineFunction("Validate()", AddressOf MyFunc) uc.EvalStr("Validate()") '// This call will trigger the error End Sub End Module
A generic conversion system that uses a single transformer rule and a callback to dynamically look up conversion factors stored in variables.
ID: 1355
using uCalcSoftware;
var uc = new uCalc();
static void ConvertUnits(uCalc.Callback cb) {
var value = cb.Arg(1);
var fromUnit = cb.ArgStr(2);
var toUnit = cb.ArgStr(3);
// Construct the variable names for direct and inverse factors
var factorName = fromUnit + "_to_" + toUnit;
var inverseFactorName = toUnit + "_to_" + fromUnit;
var uc_instance = cb.uCalc;
// Try to find the direct conversion factor
var factorItem = uc_instance.ItemOf(factorName);
if (factorItem.NotEmpty()) {
cb.Return(Math.Round(value * factorItem.Value(), 4));
return;
}
// If not found, try to find the inverse factor and use its reciprocal
var inverseFactorItem = uc_instance.ItemOf(inverseFactorName);
if (inverseFactorItem.NotEmpty()) {
cb.Return(value / inverseFactorItem.Value());
return;
}
// If no factor is found, raise an error
cb.Error.Raise("Conversion factor not found for " + fromUnit + " to " + toUnit);
}
// Define the conversion factors as variables
uc.DefineVariable("in_to_cm = 2.54");
uc.DefineVariable("km_to_miles = 0.621371");
// Define a custom function for temperature, since it's not a simple multiplication
uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0");
// Register our generic conversion callback
uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", ConvertUnits);
// Create generic rules in the expression transformer
var t = uc.ExpressionTransformer;
t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')");
// A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last)
t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})");
Console.WriteLine($"10 in to cm = {uc.Eval("10 in to cm")}");
Console.WriteLine($"100 km to miles = {uc.Eval("100 km to miles")}");
// Test the inverse conversion, which the callback handles automatically
Console.WriteLine($"254 cm to in = {uc.Eval("254 cm to in")}");
Console.WriteLine($"98.6 F to C = {uc.Eval("98.6 F to C")}");
10 in to cm = 25.4
100 km to miles = 62.1371
254 cm to in = 100
98.6 F to C = 37 using uCalcSoftware; var uc = new uCalc(); static void ConvertUnits(uCalc.Callback cb) { var value = cb.Arg(1); var fromUnit = cb.ArgStr(2); var toUnit = cb.ArgStr(3); // Construct the variable names for direct and inverse factors var factorName = fromUnit + "_to_" + toUnit; var inverseFactorName = toUnit + "_to_" + fromUnit; var uc_instance = cb.uCalc; // Try to find the direct conversion factor var factorItem = uc_instance.ItemOf(factorName); if (factorItem.NotEmpty()) { cb.Return(Math.Round(value * factorItem.Value(), 4)); return; } // If not found, try to find the inverse factor and use its reciprocal var inverseFactorItem = uc_instance.ItemOf(inverseFactorName); if (inverseFactorItem.NotEmpty()) { cb.Return(value / inverseFactorItem.Value()); return; } // If no factor is found, raise an error cb.Error.Raise("Conversion factor not found for " + fromUnit + " to " + toUnit); } // Define the conversion factors as variables uc.DefineVariable("in_to_cm = 2.54"); uc.DefineVariable("km_to_miles = 0.621371"); // Define a custom function for temperature, since it's not a simple multiplication uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0"); // Register our generic conversion callback uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", ConvertUnits); // Create generic rules in the expression transformer var t = uc.ExpressionTransformer; t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')"); // A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last) t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})"); Console.WriteLine($"10 in to cm = {uc.Eval("10 in to cm")}"); Console.WriteLine($"100 km to miles = {uc.Eval("100 km to miles")}"); // Test the inverse conversion, which the callback handles automatically Console.WriteLine($"254 cm to in = {uc.Eval("254 cm to in")}"); Console.WriteLine($"98.6 F to C = {uc.Eval("98.6 F to C")}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call ConvertUnits(uCalcBase::Callback cb) {
auto value = cb.Arg(1);
auto fromUnit = cb.ArgStr(2);
auto toUnit = cb.ArgStr(3);
// Construct the variable names for direct and inverse factors
auto factorName = fromUnit + "_to_" + toUnit;
auto inverseFactorName = toUnit + "_to_" + fromUnit;
auto uc_instance = cb.uCalc();
// Try to find the direct conversion factor
auto factorItem = uc_instance.ItemOf(factorName);
if (factorItem.NotEmpty()) {
cb.Return(value * factorItem.Value());
return;
}
// If not found, try to find the inverse factor and use its reciprocal
auto inverseFactorItem = uc_instance.ItemOf(inverseFactorName);
if (inverseFactorItem.NotEmpty()) {
cb.Return(value / inverseFactorItem.Value());
return;
}
// If no factor is found, raise an error
cb.Error().Raise("Conversion factor not found for " + fromUnit + " to " + toUnit);
}
int main() {
uCalc uc;
// Define the conversion factors as variables
uc.DefineVariable("in_to_cm = 2.54");
uc.DefineVariable("km_to_miles = 0.621371");
// Define a custom function for temperature, since it's not a simple multiplication
uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0");
// Register our generic conversion callback
uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", ConvertUnits);
// Create generic rules in the expression transformer
auto t = uc.ExpressionTransformer();
t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')");
// A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last)
t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})");
cout << "10 in to cm = " << uc.Eval("10 in to cm") << endl;
cout << "100 km to miles = " << uc.Eval("100 km to miles") << endl;
// Test the inverse conversion, which the callback handles automatically
cout << "254 cm to in = " << uc.Eval("254 cm to in") << endl;
cout << "98.6 F to C = " << uc.Eval("98.6 F to C") << endl;
}
10 in to cm = 25.4
100 km to miles = 62.1371
254 cm to in = 100
98.6 F to C = 37 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call ConvertUnits(uCalcBase::Callback cb) { auto value = cb.Arg(1); auto fromUnit = cb.ArgStr(2); auto toUnit = cb.ArgStr(3); // Construct the variable names for direct and inverse factors auto factorName = fromUnit + "_to_" + toUnit; auto inverseFactorName = toUnit + "_to_" + fromUnit; auto uc_instance = cb.uCalc(); // Try to find the direct conversion factor auto factorItem = uc_instance.ItemOf(factorName); if (factorItem.NotEmpty()) { cb.Return(value * factorItem.Value()); return; } // If not found, try to find the inverse factor and use its reciprocal auto inverseFactorItem = uc_instance.ItemOf(inverseFactorName); if (inverseFactorItem.NotEmpty()) { cb.Return(value / inverseFactorItem.Value()); return; } // If no factor is found, raise an error cb.Error().Raise("Conversion factor not found for " + fromUnit + " to " + toUnit); } int main() { uCalc uc; // Define the conversion factors as variables uc.DefineVariable("in_to_cm = 2.54"); uc.DefineVariable("km_to_miles = 0.621371"); // Define a custom function for temperature, since it's not a simple multiplication uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0"); // Register our generic conversion callback uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", ConvertUnits); // Create generic rules in the expression transformer auto t = uc.ExpressionTransformer(); t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')"); // A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last) t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})"); cout << "10 in to cm = " << uc.Eval("10 in to cm") << endl; cout << "100 km to miles = " << uc.Eval("100 km to miles") << endl; // Test the inverse conversion, which the callback handles automatically cout << "254 cm to in = " << uc.Eval("254 cm to in") << endl; cout << "98.6 F to C = " << uc.Eval("98.6 F to C") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub ConvertUnits(ByVal cb As uCalc.Callback)
Dim value = cb.Arg(1)
Dim fromUnit = cb.ArgStr(2)
Dim toUnit = cb.ArgStr(3)
'// Construct the variable names for direct and inverse factors
Dim factorName = fromUnit + "_to_" + toUnit
Dim inverseFactorName = toUnit + "_to_" + fromUnit
Dim uc_instance = cb.uCalc
'// Try to find the direct conversion factor
Dim factorItem = uc_instance.ItemOf(factorName)
If factorItem.NotEmpty() Then
cb.Return(Math.Round(value * factorItem.Value(), 4))
return
End If
'// If not found, try to find the inverse factor and use its reciprocal
Dim inverseFactorItem = uc_instance.ItemOf(inverseFactorName)
If inverseFactorItem.NotEmpty() Then
cb.Return(value / inverseFactorItem.Value())
return
End If
'// If no factor is found, raise an error
cb.Error.Raise("Conversion factor not found for " + fromUnit + " to " + toUnit)
End Sub
Public Sub Main()
Dim uc As New uCalc()
'// Define the conversion factors as variables
uc.DefineVariable("in_to_cm = 2.54")
uc.DefineVariable("km_to_miles = 0.621371")
'// Define a custom function for temperature, since it's not a simple multiplication
uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0")
'// Register our generic conversion callback
uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", AddressOf ConvertUnits)
'// Create generic rules in the expression transformer
Dim t = uc.ExpressionTransformer
t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')")
'// A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last)
t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})")
Console.WriteLine($"10 in to cm = {uc.Eval("10 in to cm")}")
Console.WriteLine($"100 km to miles = {uc.Eval("100 km to miles")}")
'// Test the inverse conversion, which the callback handles automatically
Console.WriteLine($"254 cm to in = {uc.Eval("254 cm to in")}")
Console.WriteLine($"98.6 F to C = {uc.Eval("98.6 F to C")}")
End Sub
End Module
10 in to cm = 25.4
100 km to miles = 62.1371
254 cm to in = 100
98.6 F to C = 37 Imports System Imports uCalcSoftware Public Module Program Public Sub ConvertUnits(ByVal cb As uCalc.Callback) Dim value = cb.Arg(1) Dim fromUnit = cb.ArgStr(2) Dim toUnit = cb.ArgStr(3) '// Construct the variable names for direct and inverse factors Dim factorName = fromUnit + "_to_" + toUnit Dim inverseFactorName = toUnit + "_to_" + fromUnit Dim uc_instance = cb.uCalc '// Try to find the direct conversion factor Dim factorItem = uc_instance.ItemOf(factorName) If factorItem.NotEmpty() Then cb.Return(Math.Round(value * factorItem.Value(), 4)) return End If '// If not found, try to find the inverse factor and use its reciprocal Dim inverseFactorItem = uc_instance.ItemOf(inverseFactorName) If inverseFactorItem.NotEmpty() Then cb.Return(value / inverseFactorItem.Value()) return End If '// If no factor is found, raise an error cb.Error.Raise("Conversion factor not found for " + fromUnit + " to " + toUnit) End Sub Public Sub Main() Dim uc As New uCalc() '// Define the conversion factors as variables uc.DefineVariable("in_to_cm = 2.54") uc.DefineVariable("km_to_miles = 0.621371") '// Define a custom function for temperature, since it's not a simple multiplication uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0") '// Register our generic conversion callback uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", AddressOf ConvertUnits) '// Create generic rules in the expression transformer Dim t = uc.ExpressionTransformer t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')") '// A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last) t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})") Console.WriteLine($"10 in to cm = {uc.Eval("10 in to cm")}") Console.WriteLine($"100 km to miles = {uc.Eval("100 km to miles")}") '// Test the inverse conversion, which the callback handles automatically Console.WriteLine($"254 cm to in = {uc.Eval("254 cm to in")}") Console.WriteLine($"98.6 F to C = {uc.Eval("98.6 F to C")}") End Sub End Module
A minimal example defining a function inline to calculate the area of a rectangle.
ID: 296
using uCalcSoftware;
var uc = new uCalc();
uc.DefineVariable("x = 5");
uc.DefineFunction("Area(length, width) = length * width");
Console.WriteLine(uc.Eval("Area(4, x) + 7"));
27 using uCalcSoftware; var uc = new uCalc(); uc.DefineVariable("x = 5"); uc.DefineFunction("Area(length, width) = length * width"); Console.WriteLine(uc.Eval("Area(4, x) + 7"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uc.DefineVariable("x = 5");
uc.DefineFunction("Area(length, width) = length * width");
cout << uc.Eval("Area(4, x) + 7") << endl;
}
27 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uc.DefineVariable("x = 5"); uc.DefineFunction("Area(length, width) = length * width"); cout << uc.Eval("Area(4, x) + 7") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
uc.DefineVariable("x = 5")
uc.DefineFunction("Area(length, width) = length * width")
Console.WriteLine(uc.Eval("Area(4, x) + 7"))
End Sub
End Module
27 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() uc.DefineVariable("x = 5") uc.DefineFunction("Area(length, width) = length * width") Console.WriteLine(uc.Eval("Area(4, x) + 7")) End Sub End Module
A minimal example defining a variable and using it in an expression.
ID: 305
See: DefineVariable
using uCalcSoftware;
var uc = new uCalc();
uc.DefineVariable("x = 10");
Console.WriteLine(uc.Eval("x * 5"));
50 using uCalcSoftware; var uc = new uCalc(); uc.DefineVariable("x = 10"); Console.WriteLine(uc.Eval("x * 5"));
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uc.DefineVariable("x = 10");
cout << uc.Eval("x * 5") << endl;
}
50 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uc.DefineVariable("x = 10"); cout << uc.Eval("x * 5") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
uc.DefineVariable("x = 10")
Console.WriteLine(uc.Eval("x * 5"))
End Sub
End Module
50 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() uc.DefineVariable("x = 10") Console.WriteLine(uc.Eval("x * 5")) End Sub End Module
A minimal example demonstrating the basic 'Parse once, Evaluate many' pattern.
ID: 1192
using uCalcSoftware;
var uc = new uCalc();
// 1. Parse the expression string once to create a reusable object.
//var expr = uc.Parse("5 * 10");
using (var expr = new uCalc.Expression("5 * 10")) {
// 2. Evaluate the pre-parsed object as many times as needed.
Console.WriteLine(expr.Evaluate());
Console.WriteLine(expr.Evaluate());
} // The expression object is automatically released here.
50
50 using uCalcSoftware; var uc = new uCalc(); // 1. Parse the expression string once to create a reusable object. //var expr = uc.Parse("5 * 10"); using (var expr = new uCalc.Expression("5 * 10")) { // 2. Evaluate the pre-parsed object as many times as needed. Console.WriteLine(expr.Evaluate()); Console.WriteLine(expr.Evaluate()); } // The expression object is automatically released here.
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// 1. Parse the expression string once to create a reusable object.
//var expr = uc.Parse("5 * 10");
{
uCalc::Expression expr("5 * 10");
expr.Owned(); // Causes expr to be released when it goes out of scope
// 2. Evaluate the pre-parsed object as many times as needed.
cout << expr.Evaluate() << endl;
cout << expr.Evaluate() << endl;
} // The expression object is automatically released here.
}
50
50 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // 1. Parse the expression string once to create a reusable object. //var expr = uc.Parse("5 * 10"); { uCalc::Expression expr("5 * 10"); expr.Owned(); // Causes expr to be released when it goes out of scope // 2. Evaluate the pre-parsed object as many times as needed. cout << expr.Evaluate() << endl; cout << expr.Evaluate() << endl; } // The expression object is automatically released here. }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// 1. Parse the expression string once to create a reusable object.
'//var expr = uc.Parse("5 * 10");
Using expr As New uCalc.Expression("5 * 10")
'// 2. Evaluate the pre-parsed object as many times as needed.
Console.WriteLine(expr.Evaluate())
Console.WriteLine(expr.Evaluate())
End Using '// The expression object is automatically released here.
End Sub
End Module
50
50 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// 1. Parse the expression string once to create a reusable object. '//var expr = uc.Parse("5 * 10"); Using expr As New uCalc.Expression("5 * 10") '// 2. Evaluate the pre-parsed object as many times as needed. Console.WriteLine(expr.Evaluate()) Console.WriteLine(expr.Evaluate()) End Using '// The expression object is automatically released here. End Sub End Module
A minimal example of a DSL command to move a player piece.
ID: 1385
using uCalcSoftware;
var uc = new uCalc();
uc.DefineVariable("player1_position = 0");
// Define a rule to translate the MOVE command
var t = uc.ExpressionTransformer;
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}");
// Execute a single command
uc.EvalStr("PLAYER 1 MOVES 5 SPACES");
Console.WriteLine($"Player 1 is now at position: {uc.EvalStr("player1_position")}");
Player 1 is now at position: 5 using uCalcSoftware; var uc = new uCalc(); uc.DefineVariable("player1_position = 0"); // Define a rule to translate the MOVE command var t = uc.ExpressionTransformer; t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}"); // Execute a single command uc.EvalStr("PLAYER 1 MOVES 5 SPACES"); Console.WriteLine($"Player 1 is now at position: {uc.EvalStr("player1_position")}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uc.DefineVariable("player1_position = 0");
// Define a rule to translate the MOVE command
auto t = uc.ExpressionTransformer();
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}");
// Execute a single command
uc.EvalStr("PLAYER 1 MOVES 5 SPACES");
cout << "Player 1 is now at position: " << uc.EvalStr("player1_position") << endl;
}
Player 1 is now at position: 5 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uc.DefineVariable("player1_position = 0"); // Define a rule to translate the MOVE command auto t = uc.ExpressionTransformer(); t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}"); // Execute a single command uc.EvalStr("PLAYER 1 MOVES 5 SPACES"); cout << "Player 1 is now at position: " << uc.EvalStr("player1_position") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
uc.DefineVariable("player1_position = 0")
'// Define a rule to translate the MOVE command
Dim t = uc.ExpressionTransformer
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}")
'// Execute a single command
uc.EvalStr("PLAYER 1 MOVES 5 SPACES")
Console.WriteLine($"Player 1 is now at position: {uc.EvalStr("player1_position")}")
End Sub
End Module
Player 1 is now at position: 5 Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() uc.DefineVariable("player1_position = 0") '// Define a rule to translate the MOVE command Dim t = uc.ExpressionTransformer t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}") '// Execute a single command uc.EvalStr("PLAYER 1 MOVES 5 SPACES") Console.WriteLine($"Player 1 is now at position: {uc.EvalStr("player1_position")}") End Sub End Module
A practical debugging example that identifies which pattern string generated each match.
ID: 964
See: Pattern = [string]
using uCalcSoftware;
var uc = new uCalc();
var t = uc.NewTransformer();
t.Text = "An apple and a car.";
// Define two separate rules
t.FromTo("apple", "[FRUIT]");
t.FromTo("car", "[VEHICLE]");
t.Find();
var matches = t.Matches;
Console.WriteLine($"Found {matches.Count()} matches:");
foreach(var match in matches) {
var rule = match.Rule;
Console.WriteLine($"- Matched '{match.Text}' using pattern: '{rule.Pattern}'");
}
Found 2 matches:
- Matched 'apple' using pattern: 'apple'
- Matched 'car' using pattern: 'car' using uCalcSoftware; var uc = new uCalc(); var t = uc.NewTransformer(); t.Text = "An apple and a car."; // Define two separate rules t.FromTo("apple", "[FRUIT]"); t.FromTo("car", "[VEHICLE]"); t.Find(); var matches = t.Matches; Console.WriteLine($"Found {matches.Count()} matches:"); foreach(var match in matches) { var rule = match.Rule; Console.WriteLine($"- Matched '{match.Text}' using pattern: '{rule.Pattern}'"); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
auto t = uc.NewTransformer();
t.Text("An apple and a car.");
// Define two separate rules
t.FromTo("apple", "[FRUIT]");
t.FromTo("car", "[VEHICLE]");
t.Find();
auto matches = t.Matches();
cout << "Found " << matches.Count() << " matches:" << endl;
for(auto match : matches) {
auto rule = match.Rule();
cout << "- Matched '" << match.Text() << "' using pattern: '" << rule.Pattern() << "'" << endl;
}
}
Found 2 matches:
- Matched 'apple' using pattern: 'apple'
- Matched 'car' using pattern: 'car' #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; auto t = uc.NewTransformer(); t.Text("An apple and a car."); // Define two separate rules t.FromTo("apple", "[FRUIT]"); t.FromTo("car", "[VEHICLE]"); t.Find(); auto matches = t.Matches(); cout << "Found " << matches.Count() << " matches:" << endl; for(auto match : matches) { auto rule = match.Rule(); cout << "- Matched '" << match.Text() << "' using pattern: '" << rule.Pattern() << "'" << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t = uc.NewTransformer()
t.Text = "An apple and a car."
'// Define two separate rules
t.FromTo("apple", "[FRUIT]")
t.FromTo("car", "[VEHICLE]")
t.Find()
Dim matches = t.Matches
Console.WriteLine($"Found {matches.Count()} matches:")
For Each match In matches
Dim rule = match.Rule
Console.WriteLine($"- Matched '{match.Text}' using pattern: '{rule.Pattern}'")
Next
End Sub
End Module
Found 2 matches:
- Matched 'apple' using pattern: 'apple'
- Matched 'car' using pattern: 'car' Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t = uc.NewTransformer() t.Text = "An apple and a car." '// Define two separate rules t.FromTo("apple", "[FRUIT]") t.FromTo("car", "[VEHICLE]") t.Find() Dim matches = t.Matches Console.WriteLine($"Found {matches.Count()} matches:") For Each match In matches Dim rule = match.Rule Console.WriteLine($"- Matched '{match.Text}' using pattern: '{rule.Pattern}'") Next End Sub End Module
A practical example demonstrating all four related floating-point error configuration methods.
ID: 410
using uCalcSoftware;
var uc = new uCalc();
Console.WriteLine($"Divide by Zero (Default): {uc.EvalStr("1/0")}");
uc.Error.TrapOnDivideByZero = true;
Console.WriteLine($"Divide by Zero (Error Enabled): {uc.EvalStr("1/0")}");
Console.WriteLine("");
Console.WriteLine($"Invalid Operation (Default): {uc.EvalStr("Sqrt(-1)")}");
uc.Error.TrapOnInvalid = true;
Console.WriteLine($"Invalid Operation (Error Enabled): {uc.EvalStr("Sqrt(-1)")}");
Console.WriteLine("");
Console.WriteLine($"Overflow (Default): {uc.EvalStr("5*10^308")}");
uc.Error.TrapOnOverflow = true;
Console.WriteLine($"Overflow (Error Enabled): {uc.EvalStr("5*10^308")}");
Console.WriteLine("");
Console.WriteLine($"Underflow (Default): {uc.EvalStr("10^-308/10000")}");
uc.Error.TrapOnUnderflow = true;
Console.WriteLine($"Underflow (Error Enabled): {uc.EvalStr("10^-308/10000")}");
Divide by Zero (Default): inf
Divide by Zero (Error Enabled): Division by 0
Invalid Operation (Default): nan
Invalid Operation (Error Enabled): Invalid operation
Overflow (Default): inf
Overflow (Error Enabled): Floating point overflow
Underflow (Default): 0
Underflow (Error Enabled): Floating point underflow using uCalcSoftware; var uc = new uCalc(); Console.WriteLine($"Divide by Zero (Default): {uc.EvalStr("1/0")}"); uc.Error.TrapOnDivideByZero = true; Console.WriteLine($"Divide by Zero (Error Enabled): {uc.EvalStr("1/0")}"); Console.WriteLine(""); Console.WriteLine($"Invalid Operation (Default): {uc.EvalStr("Sqrt(-1)")}"); uc.Error.TrapOnInvalid = true; Console.WriteLine($"Invalid Operation (Error Enabled): {uc.EvalStr("Sqrt(-1)")}"); Console.WriteLine(""); Console.WriteLine($"Overflow (Default): {uc.EvalStr("5*10^308")}"); uc.Error.TrapOnOverflow = true; Console.WriteLine($"Overflow (Error Enabled): {uc.EvalStr("5*10^308")}"); Console.WriteLine(""); Console.WriteLine($"Underflow (Default): {uc.EvalStr("10^-308/10000")}"); uc.Error.TrapOnUnderflow = true; Console.WriteLine($"Underflow (Error Enabled): {uc.EvalStr("10^-308/10000")}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
cout << "Divide by Zero (Default): " << uc.EvalStr("1/0") << endl;
uc.Error().TrapOnDivideByZero(true);
cout << "Divide by Zero (Error Enabled): " << uc.EvalStr("1/0") << endl;
cout << "" << endl;
cout << "Invalid Operation (Default): " << uc.EvalStr("Sqrt(-1)") << endl;
uc.Error().TrapOnInvalid(true);
cout << "Invalid Operation (Error Enabled): " << uc.EvalStr("Sqrt(-1)") << endl;
cout << "" << endl;
cout << "Overflow (Default): " << uc.EvalStr("5*10^308") << endl;
uc.Error().TrapOnOverflow(true);
cout << "Overflow (Error Enabled): " << uc.EvalStr("5*10^308") << endl;
cout << "" << endl;
cout << "Underflow (Default): " << uc.EvalStr("10^-308/10000") << endl;
uc.Error().TrapOnUnderflow(true);
cout << "Underflow (Error Enabled): " << uc.EvalStr("10^-308/10000") << endl;
}
Divide by Zero (Default): inf
Divide by Zero (Error Enabled): Division by 0
Invalid Operation (Default): nan
Invalid Operation (Error Enabled): Invalid operation
Overflow (Default): inf
Overflow (Error Enabled): Floating point overflow
Underflow (Default): 0
Underflow (Error Enabled): Floating point underflow #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; cout << "Divide by Zero (Default): " << uc.EvalStr("1/0") << endl; uc.Error().TrapOnDivideByZero(true); cout << "Divide by Zero (Error Enabled): " << uc.EvalStr("1/0") << endl; cout << "" << endl; cout << "Invalid Operation (Default): " << uc.EvalStr("Sqrt(-1)") << endl; uc.Error().TrapOnInvalid(true); cout << "Invalid Operation (Error Enabled): " << uc.EvalStr("Sqrt(-1)") << endl; cout << "" << endl; cout << "Overflow (Default): " << uc.EvalStr("5*10^308") << endl; uc.Error().TrapOnOverflow(true); cout << "Overflow (Error Enabled): " << uc.EvalStr("5*10^308") << endl; cout << "" << endl; cout << "Underflow (Default): " << uc.EvalStr("10^-308/10000") << endl; uc.Error().TrapOnUnderflow(true); cout << "Underflow (Error Enabled): " << uc.EvalStr("10^-308/10000") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Console.WriteLine($"Divide by Zero (Default): {uc.EvalStr("1/0")}")
uc.Error.TrapOnDivideByZero = true
Console.WriteLine($"Divide by Zero (Error Enabled): {uc.EvalStr("1/0")}")
Console.WriteLine("")
Console.WriteLine($"Invalid Operation (Default): {uc.EvalStr("Sqrt(-1)")}")
uc.Error.TrapOnInvalid = true
Console.WriteLine($"Invalid Operation (Error Enabled): {uc.EvalStr("Sqrt(-1)")}")
Console.WriteLine("")
Console.WriteLine($"Overflow (Default): {uc.EvalStr("5*10^308")}")
uc.Error.TrapOnOverflow = true
Console.WriteLine($"Overflow (Error Enabled): {uc.EvalStr("5*10^308")}")
Console.WriteLine("")
Console.WriteLine($"Underflow (Default): {uc.EvalStr("10^-308/10000")}")
uc.Error.TrapOnUnderflow = true
Console.WriteLine($"Underflow (Error Enabled): {uc.EvalStr("10^-308/10000")}")
End Sub
End Module
Divide by Zero (Default): inf
Divide by Zero (Error Enabled): Division by 0
Invalid Operation (Default): nan
Invalid Operation (Error Enabled): Invalid operation
Overflow (Default): inf
Overflow (Error Enabled): Floating point overflow
Underflow (Default): 0
Underflow (Error Enabled): Floating point underflow Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Console.WriteLine($"Divide by Zero (Default): {uc.EvalStr("1/0")}") uc.Error.TrapOnDivideByZero = true Console.WriteLine($"Divide by Zero (Error Enabled): {uc.EvalStr("1/0")}") Console.WriteLine("") Console.WriteLine($"Invalid Operation (Default): {uc.EvalStr("Sqrt(-1)")}") uc.Error.TrapOnInvalid = true Console.WriteLine($"Invalid Operation (Error Enabled): {uc.EvalStr("Sqrt(-1)")}") Console.WriteLine("") Console.WriteLine($"Overflow (Default): {uc.EvalStr("5*10^308")}") uc.Error.TrapOnOverflow = true Console.WriteLine($"Overflow (Error Enabled): {uc.EvalStr("5*10^308")}") Console.WriteLine("") Console.WriteLine($"Underflow (Default): {uc.EvalStr("10^-308/10000")}") uc.Error.TrapOnUnderflow = true Console.WriteLine($"Underflow (Error Enabled): {uc.EvalStr("10^-308/10000")}") End Sub End Module
A practical example demonstrating how to extract an error message from a log entry and then chain another operation on the result.
ID: 1164
See: After
using uCalcSoftware;
var uc = new uCalc();
using (var log = new uCalc.String("INFO: Task complete. ERROR: File not found.")) {
// Chain After() to isolate the error, then Replace() to modify it.
var errorDetails = log.After("ERROR: ").Replace("File", "Resource");
Console.WriteLine($"Original log: {log}"); // The original string is modified in-place
Console.WriteLine($"Modified details:{errorDetails}"); // The view reflects the change
}
Original log: INFO: Task complete. ERROR: Resource not found.
Modified details: Resource not found. using uCalcSoftware; var uc = new uCalc(); using (var log = new uCalc.String("INFO: Task complete. ERROR: File not found.")) { // Chain After() to isolate the error, then Replace() to modify it. var errorDetails = log.After("ERROR: ").Replace("File", "Resource"); Console.WriteLine($"Original log: {log}"); // The original string is modified in-place Console.WriteLine($"Modified details:{errorDetails}"); // The view reflects the change }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::String log("INFO: Task complete. ERROR: File not found.");
log.Owned(); // Causes log to be released when it goes out of scope
// Chain After() to isolate the error, then Replace() to modify it.
auto errorDetails = log.After("ERROR: ").Replace("File", "Resource");
cout << "Original log: " << log << endl; // The original string is modified in-place
cout << "Modified details:" << errorDetails << endl; // The view reflects the change
}
}
Original log: INFO: Task complete. ERROR: Resource not found.
Modified details: Resource not found. #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::String log("INFO: Task complete. ERROR: File not found."); log.Owned(); // Causes log to be released when it goes out of scope // Chain After() to isolate the error, then Replace() to modify it. auto errorDetails = log.After("ERROR: ").Replace("File", "Resource"); cout << "Original log: " << log << endl; // The original string is modified in-place cout << "Modified details:" << errorDetails << endl; // The view reflects the change } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using log As New uCalc.String("INFO: Task complete. ERROR: File not found.")
'// Chain After() to isolate the error, then Replace() to modify it.
Dim errorDetails = log.After("ERROR: ").Replace("File", "Resource")
Console.WriteLine($"Original log: {log}") '// The original string is modified in-place
Console.WriteLine($"Modified details:{errorDetails}") '// The view reflects the change
End Using
End Sub
End Module
Original log: INFO: Task complete. ERROR: Resource not found.
Modified details: Resource not found. Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using log As New uCalc.String("INFO: Task complete. ERROR: File not found.") '// Chain After() to isolate the error, then Replace() to modify it. Dim errorDetails = log.After("ERROR: ").Replace("File", "Resource") Console.WriteLine($"Original log: {log}") '// The original string is modified in-place Console.WriteLine($"Modified details:{errorDetails}") '// The view reflects the change End Using End Sub End Module
A practical example of `ByHandle` to create a `TypeOf` function that introspects an argument and returns its data type name as a string.
ID: 1250
using uCalcSoftware;
var uc = new uCalc();
static void GetTypeOf(uCalc.Callback cb) {
// Get the Item object for the argument
var item = cb.ArgItem(1);
// Get the item's DataType, then its name, and return it as a string
cb.ReturnStr(item.DataType.Name);
}
// The ByHandle modifier passes the argument's metadata (Item) instead of its value
uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", GetTypeOf);
uc.DefineVariable("myInt As Int = 10");
uc.DefineVariable("myStr As String = 'hello'");
uc.DefineVariable("myDbl = 3.14"); // Type is inferred as double
Console.WriteLine($"Type of myInt: {uc.EvalStr("TypeOf(myInt)")}");
Console.WriteLine($"Type of myStr: {uc.EvalStr("TypeOf(myStr)")}");
Console.WriteLine($"Type of myDbl: {uc.EvalStr("TypeOf(myDbl)")}");
Type of myInt: int
Type of myStr: string
Type of myDbl: double using uCalcSoftware; var uc = new uCalc(); static void GetTypeOf(uCalc.Callback cb) { // Get the Item object for the argument var item = cb.ArgItem(1); // Get the item's DataType, then its name, and return it as a string cb.ReturnStr(item.DataType.Name); } // The ByHandle modifier passes the argument's metadata (Item) instead of its value uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", GetTypeOf); uc.DefineVariable("myInt As Int = 10"); uc.DefineVariable("myStr As String = 'hello'"); uc.DefineVariable("myDbl = 3.14"); // Type is inferred as double Console.WriteLine($"Type of myInt: {uc.EvalStr("TypeOf(myInt)")}"); Console.WriteLine($"Type of myStr: {uc.EvalStr("TypeOf(myStr)")}"); Console.WriteLine($"Type of myDbl: {uc.EvalStr("TypeOf(myDbl)")}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call GetTypeOf(uCalcBase::Callback cb) {
// Get the Item object for the argument
auto item = cb.ArgItem(1);
// Get the item's DataType, then its name, and return it as a string
cb.ReturnStr(item.DataType().Name());
}
int main() {
uCalc uc;
// The ByHandle modifier passes the argument's metadata (Item) instead of its value
uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", GetTypeOf);
uc.DefineVariable("myInt As Int = 10");
uc.DefineVariable("myStr As String = 'hello'");
uc.DefineVariable("myDbl = 3.14"); // Type is inferred as double
cout << "Type of myInt: " << uc.EvalStr("TypeOf(myInt)") << endl;
cout << "Type of myStr: " << uc.EvalStr("TypeOf(myStr)") << endl;
cout << "Type of myDbl: " << uc.EvalStr("TypeOf(myDbl)") << endl;
}
Type of myInt: int
Type of myStr: string
Type of myDbl: double #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call GetTypeOf(uCalcBase::Callback cb) { // Get the Item object for the argument auto item = cb.ArgItem(1); // Get the item's DataType, then its name, and return it as a string cb.ReturnStr(item.DataType().Name()); } int main() { uCalc uc; // The ByHandle modifier passes the argument's metadata (Item) instead of its value uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", GetTypeOf); uc.DefineVariable("myInt As Int = 10"); uc.DefineVariable("myStr As String = 'hello'"); uc.DefineVariable("myDbl = 3.14"); // Type is inferred as double cout << "Type of myInt: " << uc.EvalStr("TypeOf(myInt)") << endl; cout << "Type of myStr: " << uc.EvalStr("TypeOf(myStr)") << endl; cout << "Type of myDbl: " << uc.EvalStr("TypeOf(myDbl)") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub GetTypeOf(ByVal cb As uCalc.Callback)
'// Get the Item object for the argument
Dim item = cb.ArgItem(1)
'// Get the item's DataType, then its name, and return it as a string
cb.ReturnStr(item.DataType.Name)
End Sub
Public Sub Main()
Dim uc As New uCalc()
'// The ByHandle modifier passes the argument's metadata (Item) instead of its value
uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", AddressOf GetTypeOf)
uc.DefineVariable("myInt As Int = 10")
uc.DefineVariable("myStr As String = 'hello'")
uc.DefineVariable("myDbl = 3.14") '// Type is inferred as double
Console.WriteLine($"Type of myInt: {uc.EvalStr("TypeOf(myInt)")}")
Console.WriteLine($"Type of myStr: {uc.EvalStr("TypeOf(myStr)")}")
Console.WriteLine($"Type of myDbl: {uc.EvalStr("TypeOf(myDbl)")}")
End Sub
End Module
Type of myInt: int
Type of myStr: string
Type of myDbl: double Imports System Imports uCalcSoftware Public Module Program Public Sub GetTypeOf(ByVal cb As uCalc.Callback) '// Get the Item object for the argument Dim item = cb.ArgItem(1) '// Get the item's DataType, then its name, and return it as a string cb.ReturnStr(item.DataType.Name) End Sub Public Sub Main() Dim uc As New uCalc() '// The ByHandle modifier passes the argument's metadata (Item) instead of its value uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", AddressOf GetTypeOf) uc.DefineVariable("myInt As Int = 10") uc.DefineVariable("myStr As String = 'hello'") uc.DefineVariable("myDbl = 3.14") '// Type is inferred as double Console.WriteLine($"Type of myInt: {uc.EvalStr("TypeOf(myInt)")}") Console.WriteLine($"Type of myStr: {uc.EvalStr("TypeOf(myStr)")}") Console.WriteLine($"Type of myDbl: {uc.EvalStr("TypeOf(myDbl)")}") End Sub End Module
A practical example of `ByRef` to create a classic `Swap` function that modifies its arguments in the caller's scope.
ID: 1248
using uCalcSoftware;
var uc = new uCalc();
static void SwapValues(uCalc.Callback cb) {
// Get the item handles for the two variables passed by reference
var item1 = cb.ArgItem(1);
var item2 = cb.ArgItem(2);
// Use the item's DataType object to perform a highly efficient, pointer-based swap
item1.DataType.SwapScalarValues(item1.ValueAddr(), item2.ValueAddr());
}
// Define the Swap function with ByRef parameters
uc.DefineFunction("Swap(ByHandle a, ByHandle b)", SwapValues);
// Define the variables to be swapped
uc.DefineVariable("x = 100");
uc.DefineVariable("y = 200");
Console.WriteLine($"Before: x = {uc.Eval("x")}, y = {uc.Eval("y")}");
// Call the swap function
uc.Eval("Swap(x, y)");
Console.WriteLine($"After: x = {uc.Eval("x")}, y = {uc.Eval("y")}");
Before: x = 100, y = 200
After: x = 200, y = 100 using uCalcSoftware; var uc = new uCalc(); static void SwapValues(uCalc.Callback cb) { // Get the item handles for the two variables passed by reference var item1 = cb.ArgItem(1); var item2 = cb.ArgItem(2); // Use the item's DataType object to perform a highly efficient, pointer-based swap item1.DataType.SwapScalarValues(item1.ValueAddr(), item2.ValueAddr()); } // Define the Swap function with ByRef parameters uc.DefineFunction("Swap(ByHandle a, ByHandle b)", SwapValues); // Define the variables to be swapped uc.DefineVariable("x = 100"); uc.DefineVariable("y = 200"); Console.WriteLine($"Before: x = {uc.Eval("x")}, y = {uc.Eval("y")}"); // Call the swap function uc.Eval("Swap(x, y)"); Console.WriteLine($"After: x = {uc.Eval("x")}, y = {uc.Eval("y")}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
void ucalc_call SwapValues(uCalcBase::Callback cb) {
// Get the item handles for the two variables passed by reference
auto item1 = cb.ArgItem(1);
auto item2 = cb.ArgItem(2);
// Use the item's DataType object to perform a highly efficient, pointer-based swap
item1.DataType().SwapScalarValues(item1.ValueAddr(), item2.ValueAddr());
}
int main() {
uCalc uc;
// Define the Swap function with ByRef parameters
uc.DefineFunction("Swap(ByHandle a, ByHandle b)", SwapValues);
// Define the variables to be swapped
uc.DefineVariable("x = 100");
uc.DefineVariable("y = 200");
cout << "Before: x = " << uc.Eval("x") << ", y = " << uc.Eval("y") << endl;
// Call the swap function
uc.Eval("Swap(x, y)");
cout << "After: x = " << uc.Eval("x") << ", y = " << uc.Eval("y") << endl;
}
Before: x = 100, y = 200
After: x = 200, y = 100 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; void ucalc_call SwapValues(uCalcBase::Callback cb) { // Get the item handles for the two variables passed by reference auto item1 = cb.ArgItem(1); auto item2 = cb.ArgItem(2); // Use the item's DataType object to perform a highly efficient, pointer-based swap item1.DataType().SwapScalarValues(item1.ValueAddr(), item2.ValueAddr()); } int main() { uCalc uc; // Define the Swap function with ByRef parameters uc.DefineFunction("Swap(ByHandle a, ByHandle b)", SwapValues); // Define the variables to be swapped uc.DefineVariable("x = 100"); uc.DefineVariable("y = 200"); cout << "Before: x = " << uc.Eval("x") << ", y = " << uc.Eval("y") << endl; // Call the swap function uc.Eval("Swap(x, y)"); cout << "After: x = " << uc.Eval("x") << ", y = " << uc.Eval("y") << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub SwapValues(ByVal cb As uCalc.Callback)
'// Get the item handles for the two variables passed by reference
Dim item1 = cb.ArgItem(1)
Dim item2 = cb.ArgItem(2)
'// Use the item's DataType object to perform a highly efficient, pointer-based swap
item1.DataType.SwapScalarValues(item1.ValueAddr(), item2.ValueAddr())
End Sub
Public Sub Main()
Dim uc As New uCalc()
'// Define the Swap function with ByRef parameters
uc.DefineFunction("Swap(ByHandle a, ByHandle b)", AddressOf SwapValues)
'// Define the variables to be swapped
uc.DefineVariable("x = 100")
uc.DefineVariable("y = 200")
Console.WriteLine($"Before: x = {uc.Eval("x")}, y = {uc.Eval("y")}")
'// Call the swap function
uc.Eval("Swap(x, y)")
Console.WriteLine($"After: x = {uc.Eval("x")}, y = {uc.Eval("y")}")
End Sub
End Module
Before: x = 100, y = 200
After: x = 200, y = 100 Imports System Imports uCalcSoftware Public Module Program Public Sub SwapValues(ByVal cb As uCalc.Callback) '// Get the item handles for the two variables passed by reference Dim item1 = cb.ArgItem(1) Dim item2 = cb.ArgItem(2) '// Use the item's DataType object to perform a highly efficient, pointer-based swap item1.DataType.SwapScalarValues(item1.ValueAddr(), item2.ValueAddr()) End Sub Public Sub Main() Dim uc As New uCalc() '// Define the Swap function with ByRef parameters uc.DefineFunction("Swap(ByHandle a, ByHandle b)", AddressOf SwapValues) '// Define the variables to be swapped uc.DefineVariable("x = 100") uc.DefineVariable("y = 200") Console.WriteLine($"Before: x = {uc.Eval("x")}, y = {uc.Eval("y")}") '// Call the swap function uc.Eval("Swap(x, y)") Console.WriteLine($"After: x = {uc.Eval("x")}, y = {uc.Eval("y")}") End Sub End Module
A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.
ID: 1190
See: AddHandler, Error = [ErrorInfo], Error handling and control flow, ErrorCode, ErrorHandlerResponse, Handling Errors, Response = [ErrorHandlerResponse]
using uCalcSoftware;
var uc = new uCalc();
// This handler automatically defines variables when they are first used.
static void AutoDefineHandler(Handle_uCalc h) {
var uc = new uCalc(h);
// Check if the error is specifically an undefined identifier
if (uc.Error.Code == ErrorCode.Undefined_Identifier) {
Console.WriteLine($"Handler: '{uc.Error.Symbol}' is undefined. Defining it now.");
uc.DefineVariable(uc.Error.Symbol);
// Tell the engine to resume the operation
uc.Error.Response = ErrorHandlerResponse.Resume;
}
}
uc.Error.AddHandler(AutoDefineHandler);
// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");
Console.WriteLine($"Final result: {result}");
Handler: 'my_var' is undefined. Defining it now.
Final result: 200 using uCalcSoftware; var uc = new uCalc(); // This handler automatically defines variables when they are first used. static void AutoDefineHandler(Handle_uCalc h) { var uc = new uCalc(h); // Check if the error is specifically an undefined identifier if (uc.Error.Code == ErrorCode.Undefined_Identifier) { Console.WriteLine($"Handler: '{uc.Error.Symbol}' is undefined. Defining it now."); uc.DefineVariable(uc.Error.Symbol); // Tell the engine to resume the operation uc.Error.Response = ErrorHandlerResponse.Resume; } } uc.Error.AddHandler(AutoDefineHandler); // 'my_var' doesn't exist yet, but the handler will create it. var result = uc.EvalStr("my_var = 100; my_var = my_var * 2"); Console.WriteLine($"Final result: {result}");
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
// This handler automatically defines variables when they are first used.
void ucalc_call AutoDefineHandler(Handle_uCalc h) {
auto uc = uCalc(h);
// Check if the error is specifically an undefined identifier
if (uc.Error().Code() == ErrorCode::Undefined_Identifier) {
cout << "Handler: '" << uc.Error().Symbol() << "' is undefined. Defining it now." << endl;
uc.DefineVariable(uc.Error().Symbol());
// Tell the engine to resume the operation
uc.Error().Response(ErrorHandlerResponse::Resume);
}
}
int main() {
uCalc uc;
uc.Error().AddHandler(AutoDefineHandler);
// 'my_var' doesn't exist yet, but the handler will create it.
auto result = uc.EvalStr("my_var = 100; my_var = my_var * 2");
cout << "Final result: " << result << endl;
}
Handler: 'my_var' is undefined. Defining it now.
Final result: 200 #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; // This handler automatically defines variables when they are first used. void ucalc_call AutoDefineHandler(Handle_uCalc h) { auto uc = uCalc(h); // Check if the error is specifically an undefined identifier if (uc.Error().Code() == ErrorCode::Undefined_Identifier) { cout << "Handler: '" << uc.Error().Symbol() << "' is undefined. Defining it now." << endl; uc.DefineVariable(uc.Error().Symbol()); // Tell the engine to resume the operation uc.Error().Response(ErrorHandlerResponse::Resume); } } int main() { uCalc uc; uc.Error().AddHandler(AutoDefineHandler); // 'my_var' doesn't exist yet, but the handler will create it. auto result = uc.EvalStr("my_var = 100; my_var = my_var * 2"); cout << "Final result: " << result << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
'// This handler automatically defines variables when they are first used.
Public Sub AutoDefineHandler(ByVal h As Handle_uCalc)
Dim uc As New uCalc(h)
'// Check if the error is specifically an undefined identifier
If uc.Error.Code = ErrorCode.Undefined_Identifier Then
Console.WriteLine($"Handler: '{uc.Error.Symbol}' is undefined. Defining it now.")
uc.DefineVariable(uc.Error.Symbol)
'// Tell the engine to resume the operation
uc.Error.Response = ErrorHandlerResponse.Resume
End If
End Sub
Public Sub Main()
Dim uc As New uCalc()
uc.Error.AddHandler(AddressOf AutoDefineHandler)
'// 'my_var' doesn't exist yet, but the handler will create it.
Dim result = uc.EvalStr("my_var = 100; my_var = my_var * 2")
Console.WriteLine($"Final result: {result}")
End Sub
End Module
Handler: 'my_var' is undefined. Defining it now.
Final result: 200 Imports System Imports uCalcSoftware Public Module Program '// This handler automatically defines variables when they are first used. Public Sub AutoDefineHandler(ByVal h As Handle_uCalc) Dim uc As New uCalc(h) '// Check if the error is specifically an undefined identifier If uc.Error.Code = ErrorCode.Undefined_Identifier Then Console.WriteLine($"Handler: '{uc.Error.Symbol}' is undefined. Defining it now.") uc.DefineVariable(uc.Error.Symbol) '// Tell the engine to resume the operation uc.Error.Response = ErrorHandlerResponse.Resume End If End Sub Public Sub Main() Dim uc As New uCalc() uc.Error.AddHandler(AddressOf AutoDefineHandler) '// 'my_var' doesn't exist yet, but the handler will create it. Dim result = uc.EvalStr("my_var = 100; my_var = my_var * 2") Console.WriteLine($"Final result: {result}") End Sub End Module
A practical example of a router with multiple rules, demonstrating LIFO precedence and handling of a '404 Not Found' case.
ID: 1436
using uCalcSoftware;
var uc = new uCalc();
using (var router = new uCalc.Transformer()) {
// --- Define Routes ---
// General rules first (lower precedence)
router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}");
router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");
// Specific rule last (higher precedence)
router.FromTo("/users/new", "Handler: CreateUserPage");
// --- Simulate Requests ---
string[] urls = {"/users/123", "/users/new", "/products/electronics/567", "/contact"};
foreach(var url in urls) {
var originalUrl = url;
var result = router.Transform(url);
if (result.Text == originalUrl) {
Console.WriteLine($"URL: {originalUrl} -> 404 Not Found");
} else {
Console.WriteLine($"URL: {originalUrl} -> {result}");
}
}
}
URL: /users/123 -> Handler: UserProfile, id: 123
URL: /users/new -> Handler: CreateUserPage
URL: /products/electronics/567 -> Handler: ProductDetail, category: electronics, id: 567
URL: /contact -> 404 Not Found using uCalcSoftware; var uc = new uCalc(); using (var router = new uCalc.Transformer()) { // --- Define Routes --- // General rules first (lower precedence) router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}"); router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}"); // Specific rule last (higher precedence) router.FromTo("/users/new", "Handler: CreateUserPage"); // --- Simulate Requests --- string[] urls = {"/users/123", "/users/new", "/products/electronics/567", "/contact"}; foreach(var url in urls) { var originalUrl = url; var result = router.Transform(url); if (result.Text == originalUrl) { Console.WriteLine($"URL: {originalUrl} -> 404 Not Found"); } else { Console.WriteLine($"URL: {originalUrl} -> {result}"); } } }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::Transformer router;
router.Owned(); // Causes router to be released when it goes out of scope
// --- Define Routes ---
// General rules first (lower precedence)
router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}");
router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");
// Specific rule last (higher precedence)
router.FromTo("/users/new", "Handler: CreateUserPage");
// --- Simulate Requests ---
vector urls = {"/users/123", "/users/new", "/products/electronics/567", "/contact"};
for(auto url : urls) {
auto originalUrl = url;
auto result = router.Transform(url);
if (result.Text() == originalUrl) {
cout << "URL: " << originalUrl << " -> 404 Not Found" << endl;
} else {
cout << "URL: " << originalUrl << " -> " << result << endl;
}
}
}
}
URL: /users/123 -> Handler: UserProfile, id: 123
URL: /users/new -> Handler: CreateUserPage
URL: /products/electronics/567 -> Handler: ProductDetail, category: electronics, id: 567
URL: /contact -> 404 Not Found #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::Transformer router; router.Owned(); // Causes router to be released when it goes out of scope // --- Define Routes --- // General rules first (lower precedence) router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}"); router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}"); // Specific rule last (higher precedence) router.FromTo("/users/new", "Handler: CreateUserPage"); // --- Simulate Requests --- vector<string> urls = {"/users/123", "/users/new", "/products/electronics/567", "/contact"}; for(auto url : urls) { auto originalUrl = url; auto result = router.Transform(url); if (result.Text() == originalUrl) { cout << "URL: " << originalUrl << " -> 404 Not Found" << endl; } else { cout << "URL: " << originalUrl << " -> " << result << endl; } } } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using router As New uCalc.Transformer()
'// --- Define Routes ---
'// General rules first (lower precedence)
router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}")
router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}")
'// Specific rule last (higher precedence)
router.FromTo("/users/new", "Handler: CreateUserPage")
'// --- Simulate Requests ---
Dim urls() As String = {"/users/123", "/users/new", "/products/electronics/567", "/contact"}
For Each url In urls
Dim originalUrl = url
Dim result = router.Transform(url)
If result.Text = originalUrl Then
Console.WriteLine($"URL: {originalUrl} -> 404 Not Found")
Else
Console.WriteLine($"URL: {originalUrl} -> {result}")
End If
Next
End Using
End Sub
End Module
URL: /users/123 -> Handler: UserProfile, id: 123
URL: /users/new -> Handler: CreateUserPage
URL: /products/electronics/567 -> Handler: ProductDetail, category: electronics, id: 567
URL: /contact -> 404 Not Found Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using router As New uCalc.Transformer() '// --- Define Routes --- '// General rules first (lower precedence) router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}") router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}") '// Specific rule last (higher precedence) router.FromTo("/users/new", "Handler: CreateUserPage") '// --- Simulate Requests --- Dim urls() As String = {"/users/123", "/users/new", "/products/electronics/567", "/contact"} For Each url In urls Dim originalUrl = url Dim result = router.Transform(url) If result.Text = originalUrl Then Console.WriteLine($"URL: {originalUrl} -> 404 Not Found") Else Console.WriteLine($"URL: {originalUrl} -> {result}") End If Next End Using End Sub End Module
A practical example of extracting a complete HTML tag and its content from a string.
ID: 1276
See: BetweenInclusive
using uCalcSoftware;
var uc = new uCalc();
using (var s = new uCalc.String("Some text This is a paragraph.
more text.")) {
// Extract the entire paragraph tag, including its start and end tags.
var p_tag = s.BetweenInclusive("", "
");
Console.WriteLine(p_tag);
}
<p>This is a paragraph.</p> using uCalcSoftware; var uc = new uCalc(); using (var s = new uCalc.String("Some text <p>This is a paragraph.</p> more text.")) { // Extract the entire paragraph tag, including its start and end tags. var p_tag = s.BetweenInclusive("<p>", "</p>"); Console.WriteLine(p_tag); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
{
uCalc::String s("Some text This is a paragraph.
more text.");
s.Owned(); // Causes s to be released when it goes out of scope
// Extract the entire paragraph tag, including its start and end tags.
auto p_tag = s.BetweenInclusive("", "
");
cout << p_tag << endl;
}
}
<p>This is a paragraph.</p> #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; { uCalc::String s("Some text <p>This is a paragraph.</p> more text."); s.Owned(); // Causes s to be released when it goes out of scope // Extract the entire paragraph tag, including its start and end tags. auto p_tag = s.BetweenInclusive("<p>", "</p>"); cout << p_tag << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Using s As New uCalc.String("Some text This is a paragraph.
more text.")
'// Extract the entire paragraph tag, including its start and end tags.
Dim p_tag = s.BetweenInclusive("", "
")
Console.WriteLine(p_tag)
End Using
End Sub
End Module
<p>This is a paragraph.</p> Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Using s As New uCalc.String("Some text <p>This is a paragraph.</p> more text.") '// Extract the entire paragraph tag, including its start and end tags. Dim p_tag = s.BetweenInclusive("<p>", "</p>") Console.WriteLine(p_tag) End Using End Sub End Module
A practical example of iterating through all token definitions in a collection using Count as the loop boundary.
ID: 1031
See: Count = [int]
using uCalcSoftware;
var uc = new uCalc();
var t = new uCalc.Transformer();
var tokens = t.Tokens;
Console.WriteLine($"Total token definitions: {tokens.Count}");
Console.WriteLine("--- Token List ---");
var i = 0;
for ( i = 0; i <= tokens.Count - 1; i++) {
var tokenItem = tokens.At(i);
Console.WriteLine($"{i}: {tokenItem.Name}");
}
Total token definitions: 27
--- Token List ---
0: _token_line
1: _token_catchall
2: _token_catchall_utf8_other
3: _token_punctuation
4: _token_quotechar
5: _token_quotechar_single
6: _token_quotechar_double
7: _token_quotechar_tripledouble
8: _token_memberaccess
9: _token_variableargs
10: _token_reducible2
11: _token_parenthesis
12: _token_parenthesis_close
13: _token_curlybrace
14: _token_curlybrace_close
15: _token_squarebracket
16: _token_squarebracket_close
17: _token_argseparator
18: _token_newline
19: _token_semicolon
20: _token_string_singlequoted
21: _token_string_doublequoted
22: _token_string_tripledoublequoted
23: _token_whitespace
24: _token_reducible
25: _token_floatnumber
26: _token_alphanumeric using uCalcSoftware; var uc = new uCalc(); var t = new uCalc.Transformer(); var tokens = t.Tokens; Console.WriteLine($"Total token definitions: {tokens.Count}"); Console.WriteLine("--- Token List ---"); var i = 0; for ( i = 0; i <= tokens.Count - 1; i++) { var tokenItem = tokens.At(i); Console.WriteLine($"{i}: {tokenItem.Name}"); }
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
uCalc::Transformer t;
auto tokens = t.Tokens();
cout << "Total token definitions: " << tokens.Count() << endl;
cout << "--- Token List ---" << endl;
auto i = 0;
for ( i = 0; i <= tokens.Count() - 1; i++) {
auto tokenItem = tokens.At(i);
cout << i << ": " << tokenItem.Name() << endl;
}
}
Total token definitions: 27
--- Token List ---
0: _token_line
1: _token_catchall
2: _token_catchall_utf8_other
3: _token_punctuation
4: _token_quotechar
5: _token_quotechar_single
6: _token_quotechar_double
7: _token_quotechar_tripledouble
8: _token_memberaccess
9: _token_variableargs
10: _token_reducible2
11: _token_parenthesis
12: _token_parenthesis_close
13: _token_curlybrace
14: _token_curlybrace_close
15: _token_squarebracket
16: _token_squarebracket_close
17: _token_argseparator
18: _token_newline
19: _token_semicolon
20: _token_string_singlequoted
21: _token_string_doublequoted
22: _token_string_tripledoublequoted
23: _token_whitespace
24: _token_reducible
25: _token_floatnumber
26: _token_alphanumeric #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; uCalc::Transformer t; auto tokens = t.Tokens(); cout << "Total token definitions: " << tokens.Count() << endl; cout << "--- Token List ---" << endl; auto i = 0; for ( i = 0; i <= tokens.Count() - 1; i++) { auto tokenItem = tokens.At(i); cout << i << ": " << tokenItem.Name() << endl; } }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
Dim t As New uCalc.Transformer()
Dim tokens = t.Tokens
Console.WriteLine($"Total token definitions: {tokens.Count}")
Console.WriteLine("--- Token List ---")
Dim i = 0
For i = 0 To tokens.Count - 1
Dim tokenItem = tokens.At(i)
Console.WriteLine($"{i}: {tokenItem.Name}")
Next
End Sub
End Module
Total token definitions: 27
--- Token List ---
0: _token_line
1: _token_catchall
2: _token_catchall_utf8_other
3: _token_punctuation
4: _token_quotechar
5: _token_quotechar_single
6: _token_quotechar_double
7: _token_quotechar_tripledouble
8: _token_memberaccess
9: _token_variableargs
10: _token_reducible2
11: _token_parenthesis
12: _token_parenthesis_close
13: _token_curlybrace
14: _token_curlybrace_close
15: _token_squarebracket
16: _token_squarebracket_close
17: _token_argseparator
18: _token_newline
19: _token_semicolon
20: _token_string_singlequoted
21: _token_string_doublequoted
22: _token_string_tripledoublequoted
23: _token_whitespace
24: _token_reducible
25: _token_floatnumber
26: _token_alphanumeric Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() Dim t As New uCalc.Transformer() Dim tokens = t.Tokens Console.WriteLine($"Total token definitions: {tokens.Count}") Console.WriteLine("--- Token List ---") Dim i = 0 For i = 0 To tokens.Count - 1 Dim tokenItem = tokens.At(i) Console.WriteLine($"{i}: {tokenItem.Name}") Next End Sub End Module
A practical example of parsing a specific HTML section and applying transformations only to the elements within it.
ID: 940
using uCalcSoftware;
var uc = new uCalc();
// Note the change in section/div/h2
var t = uc.NewTransformer();
// The parent rule will find the block and make its content available to a local transformer.
// StatementSensitive(false) is needed so the multiline content is captured.
var parentRule = t.Pattern("{body} ");
parentRule.StatementSensitive = false;
// Get the local transformer for the block.
var section_t = parentRule.LocalTransformer;
// These rules will ONLY run on the content inside the tag.
section_t.FromTo("{text}
", "====> {@Eval: UCase(text)} <====
");
section_t.FromTo("{text}
", "SELECTED: {text}
");
var sourceHtml =
"""
Article One
This is NOT in the section.
Article Two
This one IS inside the section.
""";
t.Text = sourceHtml;
t.Transform();
Console.WriteLine(t.Text);
<div>
<h2>Article One</h2>
<p>This is NOT in the section.</p>
</div>
<section>
<div>
<h1>====> ARTICLE TWO <====</h1>
<p>SELECTED: This one IS inside the section.</p>
</div>
</section> using uCalcSoftware; var uc = new uCalc(); // Note the change in section/div/h2 var t = uc.NewTransformer(); // The parent rule will find the <section> block and make its content available to a local transformer. // StatementSensitive(false) is needed so the multiline content is captured. var parentRule = t.Pattern("<section>{body}</section>"); parentRule.StatementSensitive = false; // Get the local transformer for the <section> block. var section_t = parentRule.LocalTransformer; // These rules will ONLY run on the content inside the <section> tag. section_t.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>"); section_t.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>"); var sourceHtml = """ <div> <h2>Article One</h2> <p>This is NOT in the section.</p> </div> <section> <div> <h2>Article Two</h2> <p>This one IS inside the section.</p> </div> </section> """; t.Text = sourceHtml; t.Transform(); Console.WriteLine(t.Text);
#include
#include "uCalc.h"
using namespace std;
using namespace uCalcSoftware;
int main() {
uCalc uc;
// Note the change in section/div/h2
auto t = uc.NewTransformer();
// The parent rule will find the block and make its content available to a local transformer.
// StatementSensitive(false) is needed so the multiline content is captured.
auto parentRule = t.Pattern("{body} ");
parentRule.StatementSensitive(false);
// Get the local transformer for the block.
auto section_t = parentRule.LocalTransformer();
// These rules will ONLY run on the content inside the tag.
section_t.FromTo("{text}
", "====> {@Eval: UCase(text)} <====
");
section_t.FromTo("{text}
", "SELECTED: {text}
");
auto sourceHtml =
R"(
Article One
This is NOT in the section.
Article Two
This one IS inside the section.
)";
t.Text(sourceHtml);
t.Transform();
cout << t.Text() << endl;
}
<div>
<h2>Article One</h2>
<p>This is NOT in the section.</p>
</div>
<section>
<div>
<h1>====> ARTICLE TWO <====</h1>
<p>SELECTED: This one IS inside the section.</p>
</div>
</section> #include <iostream> #include "uCalc.h" using namespace std; using namespace uCalcSoftware; int main() { uCalc uc; // Note the change in section/div/h2 auto t = uc.NewTransformer(); // The parent rule will find the <section> block and make its content available to a local transformer. // StatementSensitive(false) is needed so the multiline content is captured. auto parentRule = t.Pattern("<section>{body}</section>"); parentRule.StatementSensitive(false); // Get the local transformer for the <section> block. auto section_t = parentRule.LocalTransformer(); // These rules will ONLY run on the content inside the <section> tag. section_t.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>"); section_t.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>"); auto sourceHtml = R"( <div> <h2>Article One</h2> <p>This is NOT in the section.</p> </div> <section> <div> <h2>Article Two</h2> <p>This one IS inside the section.</p> </div> </section> )"; t.Text(sourceHtml); t.Transform(); cout << t.Text() << endl; }
Imports System
Imports uCalcSoftware
Public Module Program
Public Sub Main()
Dim uc As New uCalc()
'// Note the change in section/div/h2
Dim t = uc.NewTransformer()
'// The parent rule will find the block and make its content available to a local transformer.
'// StatementSensitive(false) is needed so the multiline content is captured.
Dim parentRule = t.Pattern("{body} ")
parentRule.StatementSensitive = false
'// Get the local transformer for the block.
Dim section_t = parentRule.LocalTransformer
'// These rules will ONLY run on the content inside the tag.
section_t.FromTo("{text}
", "====> {@Eval: UCase(text)} <====
")
section_t.FromTo("{text}
", "SELECTED: {text}
")
Dim sourceHtml =
"
Article One
This is NOT in the section.
Article Two
This one IS inside the section.
"
t.Text = sourceHtml
t.Transform()
Console.WriteLine(t.Text)
End Sub
End Module
<div>
<h2>Article One</h2>
<p>This is NOT in the section.</p>
</div>
<section>
<div>
<h1>====> ARTICLE TWO <====</h1>
<p>SELECTED: This one IS inside the section.</p>
</div>
</section> Imports System Imports uCalcSoftware Public Module Program Public Sub Main() Dim uc As New uCalc() '// Note the change in section/div/h2 Dim t = uc.NewTransformer() '// The parent rule will find the <section> block and make its content available to a local transformer. '// StatementSensitive(false) is needed so the multiline content is captured. Dim parentRule = t.Pattern("<section>{body}</section>") parentRule.StatementSensitive = false '// Get the local transformer for the <section> block. Dim section_t = parentRule.LocalTransformer '// These rules will ONLY run on the content inside the <section> tag. section_t.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>") section_t.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>") Dim sourceHtml = " <div> <h2>Article One</h2> <p>This is NOT in the section.</p> </div> <section> <div> <h2>Article Two</h2> <p>This one IS inside the section.</p> </div> </section> " t.Text = sourceHtml t.Transform() Console.WriteLine(t.Text) End Sub End Module