Complete Syntax Guide (1–100)
Comprehensive, sequential reference catalog of all 100 SP language syntax features. From fundamental variable bindings and control flow to advanced zero-cost abstractions, atomics, networking, and real-world microservices.
100
10 Groups
spc v1.0.0
Verified
1. Hello World
The simplest SP program:
1fn main() {2 println("Hello, SP!");3}
Hello, SP!
2. Variables & Constants
Examples and idioms for Variables & Constants, starting with mutable variables.
Mutable Variables
1fn main() {2 // Explicit types3 int age = 21;4 string name = "Shanto";5 double salary = 75000.50;6 float score = 95.5;7 bool isActive = true;8 char grade = 'A';910 println("Name: ${name}");11 println("Age: ${age}");12 println("Salary: ${salary}");13 println("Score: ${score}");14 println("Active: ${isActive}");15 println("Grade: ${grade}");1617 // Variables can be reassigned18 age = 22;19 name = "Shanto Paul";20 println("Updated: ${name}, age ${age}");21}
Name: Shanto Age: 21 Salary: 75000.5 Score: 95.5 Active: true Grade: A Updated: Shanto Paul, age 22
Constants (Immutable)
1fn main() {2 const int MAX_USERS = 1000;3 const double TAX_RATE = 0.15;4 const string APP_NAME = "MyApp";56 println("App: ${APP_NAME}");7 println("Max Users: ${MAX_USERS}");8 println("Tax Rate: ${TAX_RATE}");910 // ❌ This will NOT compile:11 // MAX_USERS = 2000; // error: cannot assign to constant12}
3. Data Types
Examples and idioms for Data Types, starting with all primitive types.
All Primitive Types
1fn main() {2 // ═══════════════════════════════════════3 // INTEGER TYPES4 // ═══════════════════════════════════════56 int number = 42; // Platform default (32 or 64 bit)7 uint positive = 100; // Unsigned integer89 int8 tiny = 127; // -128 to 12710 int16 small = 32000; // -32768 to 3276711 int32 medium = 2147483647; // Standard 32-bit12 int64 large = 9223372036854; // 64-bit1314 uint8 uTiny = 255; // 0 to 25515 uint16 uSmall = 65535; // 0 to 6553516 uint32 uMedium = 4294967295; // 0 to 4,294,967,29517 uint64 uLarge = 18446744073; // 0 to 18,446,744,073,709,551,6151819 // ═══════════════════════════════════════20 // FLOATING POINT TYPES21 // ═══════════════════════════════════════2223 float price = 29.99; // 32-bit floating point24 double precise = 3.141592653589793; // 64-bit floating point2526 // ═══════════════════════════════════════27 // OTHER TYPES28 // ═══════════════════════════════════════2930 bool alive = true; // true or false31 bool dead = false;3233 char letter = 'A'; // Single character34 char symbol = '@';35 char newline = '\n';3637 string text = "Hello, SP!"; // String of characters38 string empty = "";3940 byte raw = 0xFF; // Raw byte (0-255)4142 // Print all43 println("int: ${number}");44 println("float: ${price}");45 println("double: ${precise}");46 println("bool: ${alive}");47 println("char: ${letter}");48 println("string: ${text}");49 println("byte: ${raw}");50}
int: 42 float: 29.99 double: 3.141592653589793 bool: true char: A string: Hello, SP! byte: 255
4. Type Inference
Hands-on syntax example and reference implementation for Type Inference.
1fn main() {2 // ═══════════════════════════════════════3 // var — mutable, type inferred4 // ═══════════════════════════════════════56 var age = 21; // inferred as int7 var name = "Shanto"; // inferred as string8 var price = 99.99; // inferred as double9 var active = true; // inferred as bool1011 age = 22; // ✅ Can reassign12 name = "Shanto Paul"; // ✅ Can reassign1314 // ═══════════════════════════════════════15 // let — mutable inferred (alternative)16 // ═══════════════════════════════════════1718 let count = 100;19 let message = "Hello";2021 // ═══════════════════════════════════════22 // const — immutable, type inferred23 // ═══════════════════════════════════════2425 const PI = 3.14159; // inferred as double, immutable26 const APP = "SP Lang"; // inferred as string, immutable2728 // ❌ PI = 3.14; // error: cannot assign to constant2930 println("Age: ${age}");31 println("Name: ${name}");32 println("PI: ${PI}");33 println("App: ${APP}");34}
Age: 22 Name: Shanto Paul PI: 3.14159 App: SP Lang
5. Operators
Hands-on syntax example and reference implementation for Operators.
1fn main() {2 // ═══════════════════════════════════════3 // ARITHMETIC4 // ═══════════════════════════════════════56 int a = 20;7 int b = 7;89 println("${a} + ${b} = ${a + b}"); // 2710 println("${a} - ${b} = ${a - b}"); // 1311 println("${a} * ${b} = ${a * b}"); // 14012 println("${a} / ${b} = ${a / b}"); // 2 (integer division)13 println("${a} % ${b} = ${a % b}"); // 6 (remainder)1415 // ═══════════════════════════════════════16 // COMPARISON17 // ═══════════════════════════════════════1819 println("${a} == ${b} → ${a == b}"); // false20 println("${a} != ${b} → ${a != b}"); // true21 println("${a} > ${b} → ${a > b}"); // true22 println("${a} < ${b} → ${a < b}"); // false23 println("${a} >= ${b} → ${a >= b}"); // true24 println("${a} <= ${b} → ${a <= b}"); // false2526 // ═══════════════════════════════════════27 // LOGICAL28 // ═══════════════════════════════════════2930 bool x = true;31 bool y = false;3233 println("${x} && ${y} → ${x && y}"); // false34 println("${x} || ${y} → ${x || y}"); // true35 println("!${x} → ${!x}"); // false3637 // ═══════════════════════════════════════38 // ASSIGNMENT39 // ═══════════════════════════════════════4041 int n = 10;42 n += 5; println("n += 5 → ${n}"); // 1543 n -= 3; println("n -= 3 → ${n}"); // 1244 n *= 2; println("n *= 2 → ${n}"); // 2445 n /= 4; println("n /= 4 → ${n}"); // 646 n %= 4; println("n %= 4 → ${n}"); // 24748 // ═══════════════════════════════════════49 // INCREMENT / DECREMENT50 // ═══════════════════════════════════════5152 int counter = 0;53 counter++; println("counter++ → ${counter}"); // 154 counter++; println("counter++ → ${counter}"); // 255 counter--; println("counter-- → ${counter}"); // 15657 // ═══════════════════════════════════════58 // BITWISE59 // ═══════════════════════════════════════6061 int p = 0b1100; // 1262 int q = 0b1010; // 106364 println("p & q = ${p & q}"); // 8 (1000)65 println("p | q = ${p | q}"); // 14 (1110)66 println("p ^ q = ${p ^ q}"); // 6 (0110)67 println("~p = ${~p}"); // -1368 println("p << 1 = ${p << 1}"); // 2469 println("p >> 1 = ${p >> 1}"); // 670}
6. Strings & Interpolation
Hands-on syntax example and reference implementation for Strings & Interpolation.
1fn main() {2 string firstName = "Shanto";3 string lastName = "Paul";4 int age = 21;56 // ═══════════════════════════════════════7 // CONCATENATION8 // ═══════════════════════════════════════910 string fullName = firstName + " " + lastName;11 println(fullName); // Shanto Paul1213 // ═══════════════════════════════════════14 // STRING INTERPOLATION ${expression}15 // ═══════════════════════════════════════1617 println("Hello, ${firstName}!");18 println("Full Name: ${firstName} ${lastName}");19 println("Age next year: ${age + 1}");20 println("Name length: ${firstName.length()}");21 println("Uppercase: ${firstName.upper()}");2223 // ═══════════════════════════════════════24 // ESCAPE SEQUENCES25 // ═══════════════════════════════════════2627 println("Line 1\nLine 2"); // newline28 println("Tab\there"); // tab29 println("She said \"Hello\""); // quotes30 println("Backslash: \\"); // backslash31 println("Unicode: \u0041"); // A3233 // ═══════════════════════════════════════34 // MULTI-LINE (future)35 // ═══════════════════════════════════════3637 string poem = "Roses are red,\n"38 + "Violets are blue,\n"39 + "SP is awesome,\n"40 + "And so are you.";4142 println(poem);43}
Shanto Paul Hello, Shanto! Full Name: Shanto Paul Age next year: 22 Name length: 6 Uppercase: SHANTO Line 1 Line 2 Tab here She said "Hello" Backslash: \ Unicode: A Roses are red, Violets are blue, SP is awesome, And so are you.
7. Console I/O
Hands-on syntax example and reference implementation for Console I/O.
1import std.io;23fn main() {4 // ═══════════════════════════════════════5 // OUTPUT6 // ═══════════════════════════════════════78 println("Hello, World!"); // Print with newline9 print("Enter name: "); // Print without newline1011 // ═══════════════════════════════════════12 // INPUT13 // ═══════════════════════════════════════1415 string name = readLine();16 println("Hello, ${name}!");1718 print("Enter age: ");19 int age = int.parse(readLine());20 println("You are ${age} years old.");2122 print("Enter score: ");23 double score = double.parse(readLine());24 println("Your score is ${score}");25}
8. Functions
Examples and idioms for Functions, starting with basic functions.
Basic Functions
1// ═══════════════════════════════════════════════════2// SP-NATIVE SYNTAX: fn name(params) -> returnType3// ═══════════════════════════════════════════════════45fn add(int a, int b) -> int {6 return a + b;7}89fn greet(string name) {10 println("Hello, ${name}!");11}1213fn isAdult(int age) -> bool {14 return age >= 18;15}1617fn getFullName(string first, string last) -> string {18 return "${first} ${last}";19}2021fn main() {22 int sum = add(10, 20);23 println("Sum: ${sum}"); // Sum: 302425 greet("Shanto"); // Hello, Shanto!2627 println(isAdult(21)); // true28 println(isAdult(15)); // false2930 println(getFullName("Shanto", "Paul")); // Shanto Paul31}
Java/C++ Style Functions (Also Valid!)
1// ═══════════════════════════════════════════════════2// JAVA/C++ STYLE: returnType name(params)3// ═══════════════════════════════════════════════════45int multiply(int a, int b) {6 return a * b;7}89string formatAge(string name, int age) {10 return "${name} is ${age} years old";11}1213void sayGoodbye(string name) {14 println("Goodbye, ${name}!");15}1617fn main() {18 println(multiply(5, 4)); // 2019 println(formatAge("Shanto", 21)); // Shanto is 21 years old20 sayGoodbye("World"); // Goodbye, World!21}
Short Form Functions
1// ═══════════════════════════════════════════════════2// SHORT FORM: fn name(params) => expression3// ═══════════════════════════════════════════════════45fn square(int x) => x * x;6fn cube(int x) => x * x * x;7fn max(int a, int b) => a > b ? a : b;8fn min(int a, int b) => a < b ? a : b;9fn isEven(int n) => n % 2 == 0;10fn double(int n) => n * 2;1112fn main() {13 println("5² = ${square(5)}"); // 2514 println("3³ = ${cube(3)}"); // 2715 println("max(3,7) = ${max(3, 7)}"); // 716 println("min(3,7) = ${min(3, 7)}"); // 317 println("isEven(4) = ${isEven(4)}");// true18 println("double(8) = ${double(8)}");// 1619}
Functions with Default Parameters
1fn createUser(string name, int age, string role = "user") -> string {2 return "${name} (${age}) - ${role}";3}45fn main() {6 println(createUser("Shanto", 21)); // Shanto (21) - user7 println(createUser("Admin", 30, "admin")); // Admin (30) - admin8}
Recursive Functions
1fn factorial(int n) -> int {2 if (n <= 1) return 1;3 return n * factorial(n - 1);4}56fn fibonacci(int n) -> int {7 if (n <= 0) return 0;8 if (n == 1) return 1;9 return fibonacci(n - 1) + fibonacci(n - 2);10}1112fn main() {13 println("5! = ${factorial(5)}"); // 12014 println("10! = ${factorial(10)}"); // 36288001516 println("\nFibonacci sequence:");17 for (int i = 0; i < 10; i++) {18 print("${fibonacci(i)} ");19 }20 println("");21 // 0 1 1 2 3 5 8 13 21 3422}
9. If / Else / Else-If
Hands-on syntax example and reference implementation for If / Else / Else-If.
1fn main() {2 int age = 21;3 int score = 85;4 string role = "admin";56 // ═══════════════════════════════════════7 // SIMPLE IF8 // ═══════════════════════════════════════910 if (age >= 18) {11 println("You are an adult.");12 }1314 // ═══════════════════════════════════════15 // IF / ELSE16 // ═══════════════════════════════════════1718 if (age >= 18) {19 println("Welcome! You can enter.");20 } else {21 println("Sorry, you must be 18+.");22 }2324 // ═══════════════════════════════════════25 // IF / ELSE-IF / ELSE (Grade System)26 // ═══════════════════════════════════════2728 if (score >= 90) {29 println("Grade: A ⭐ Excellent!");30 } else if (score >= 80) {31 println("Grade: B 👍 Good job!");32 } else if (score >= 70) {33 println("Grade: C 📝 Average");34 } else if (score >= 60) {35 println("Grade: D ⚠️ Below average");36 } else {37 println("Grade: F ❌ Failed");38 }3940 // ═══════════════════════════════════════41 // NESTED IF42 // ═══════════════════════════════════════4344 if (age >= 18) {45 if (role == "admin") {46 println("Admin access granted.");47 } else {48 println("User access granted.");49 }50 } else {51 println("Access denied.");52 }5354 // ═══════════════════════════════════════55 // LOGICAL CONDITIONS56 // ═══════════════════════════════════════5758 bool hasLicense = true;5960 if (age >= 18 && hasLicense) {61 println("You can drive! 🚗");62 }6364 if (role == "admin" || role == "moderator") {65 println("You have elevated permissions.");66 }6768 if (!hasLicense) {69 println("Get a license first.");70 }7172 // ═══════════════════════════════════════73 // TERNARY OPERATOR74 // ═══════════════════════════════════════7576 string status = age >= 18 ? "Adult" : "Minor";77 println("Status: ${status}");78}
You are an adult. Welcome! You can enter. Grade: B 👍 Good job! Admin access granted. You can drive! 🚗 You have elevated permissions. Status: Adult
10. Switch & Match
Examples and idioms for Switch & Match, starting with classic switch.
Classic Switch
1fn main() {2 int day = 3;34 switch (day) {5 case 1:6 println("Monday");7 break;8 case 2:9 println("Tuesday");10 break;11 case 3:12 println("Wednesday");13 break;14 case 4:15 println("Thursday");16 break;17 case 5:18 println("Friday");19 break;20 case 6:21 println("Saturday 🎉");22 break;23 case 7:24 println("Sunday 🎉");25 break;26 default:27 println("Invalid day");28 }29}
Modern Match
1fn main() {2 int day = 3;34 // ═══════════════════════════════════════5 // MATCH EXPRESSION (cleaner syntax)6 // ═══════════════════════════════════════78 match day {9 1 => println("Monday"),10 2 => println("Tuesday"),11 3 => println("Wednesday"),12 4 => println("Thursday"),13 5 => println("Friday"),14 6 => println("Saturday 🎉"),15 7 => println("Sunday 🎉"),16 _ => println("Invalid day")17 }1819 // ═══════════════════════════════════════20 // MATCH WITH STRINGS21 // ═══════════════════════════════════════2223 string command = "start";2425 match command {26 "start" => println("Starting server..."),27 "stop" => println("Stopping server..."),28 "restart" => println("Restarting server..."),29 "status" => println("Server is running."),30 _ => println("Unknown command: ${command}")31 }3233 // ═══════════════════════════════════════34 // MATCH WITH ENUM35 // ═══════════════════════════════════════3637 enum Season { Spring, Summer, Autumn, Winter }3839 Season current = Season.Summer;4041 match current {42 Season.Spring => println("🌸 Flowers blooming"),43 Season.Summer => println("☀️ Beach time!"),44 Season.Autumn => println("🍂 Leaves falling"),45 Season.Winter => println("❄️ Stay warm!")46 }47}
Wednesday Starting server... ☀️ Beach time!
11. For Loops
Hands-on syntax example and reference implementation for For Loops.
1fn main() {2 // ═══════════════════════════════════════3 // CLASSIC FOR LOOP (C/Java style)4 // ═══════════════════════════════════════56 println("=== Classic For ===");7 for (int i = 1; i <= 5; i++) {8 println("Count: ${i}");9 }1011 // ═══════════════════════════════════════12 // RANGE LOOP (Modern SP)13 // ═══════════════════════════════════════1415 println("\n=== Range Loop ===");16 for (i in 0..5) {17 print("${i} ");18 }19 println("");20 // 0 1 2 3 42122 // ═══════════════════════════════════════23 // FOR-EACH (iterate collections)24 // ═══════════════════════════════════════2526 println("\n=== For-Each ===");27 let fruits = ["Apple", "Banana", "Cherry", "Date"];2829 for (string fruit in fruits) {30 println("🍎 ${fruit}");31 }3233 // ═══════════════════════════════════════34 // NESTED LOOPS35 // ═══════════════════════════════════════3637 println("\n=== Multiplication Table (1-5) ===");38 for (int i = 1; i <= 5; i++) {39 for (int j = 1; j <= 5; j++) {40 print("${i * j}\t");41 }42 println("");43 }4445 // ═══════════════════════════════════════46 // BREAK & CONTINUE47 // ═══════════════════════════════════════4849 println("\n=== Break at 5 ===");50 for (int i = 1; i <= 10; i++) {51 if (i == 5) break;52 print("${i} ");53 }54 println("");55 // 1 2 3 45657 println("\n=== Skip even numbers ===");58 for (int i = 1; i <= 10; i++) {59 if (i % 2 == 0) continue;60 print("${i} ");61 }62 println("");63 // 1 3 5 7 96465 // ═══════════════════════════════════════66 // COUNTDOWN67 // ═══════════════════════════════════════6869 println("\n=== Countdown ===");70 for (int i = 5; i >= 1; i--) {71 println("${i}...");72 }73 println("🚀 Liftoff!");7475 // ═══════════════════════════════════════76 // PATTERN: Sum of numbers77 // ═══════════════════════════════════════7879 int sum = 0;80 for (int i = 1; i <= 100; i++) {81 sum += i;82 }83 println("\nSum of 1-100: ${sum}"); // 505084}
=== Classic For === Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 === Range Loop === 0 1 2 3 4 === For-Each === 🍎 Apple 🍎 Banana 🍎 Cherry 🍎 Date === Multiplication Table (1-5) === 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 === Break at 5 === 1 2 3 4 === Skip even numbers === 1 3 5 7 9 === Countdown === 5... 4... 3... 2... 1... 🚀 Liftoff! Sum of 1-100: 5050
12. While & Do-While
Hands-on syntax example and reference implementation for While & Do-While.
1fn main() {2 // ═══════════════════════════════════════3 // WHILE LOOP4 // ═══════════════════════════════════════56 println("=== While Loop ===");7 int count = 1;8 while (count <= 5) {9 println("Count: ${count}");10 count++;11 }1213 // ═══════════════════════════════════════14 // DO-WHILE LOOP (runs at least once)15 // ═══════════════════════════════════════1617 println("\n=== Do-While Loop ===");18 int n = 1;19 do {20 println("n = ${n}");21 n *= 2;22 } while (n <= 16);23 // 1, 2, 4, 8, 162425 // ═══════════════════════════════════════26 // PATTERN: Find first power of 2 > 100027 // ═══════════════════════════════════════2829 int power = 1;30 int exponent = 0;31 while (power <= 1000) {32 power *= 2;33 exponent++;34 }35 println("\n2^${exponent} = ${power} (first power of 2 > 1000)");36 // 2^10 = 10243738 // ═══════════════════════════════════════39 // PATTERN: Collatz Conjecture40 // ═══════════════════════════════════════4142 println("\n=== Collatz Sequence (start: 27) ===");43 int num = 27;44 int steps = 0;45 print("${num}");46 while (num != 1) {47 if (num % 2 == 0) {48 num = num / 2;49 } else {50 num = num * 3 + 1;51 }52 print(" → ${num}");53 steps++;54 }55 println("\nReached 1 in ${steps} steps");56}
13. Arrays
Hands-on syntax example and reference implementation for Arrays.
1fn main() {2 // ═══════════════════════════════════════3 // DECLARATION4 // ═══════════════════════════════════════56 int[] numbers = {10, 20, 30, 40, 50};7 string[] names = {"Alice", "Bob", "Charlie"};89 // Modern syntax10 let scores = [95, 87, 92, 78, 88];1112 // ═══════════════════════════════════════13 // ACCESS & MODIFY14 // ═══════════════════════════════════════1516 println("First: ${numbers[0]}"); // 1017 println("Last: ${numbers[4]}"); // 501819 numbers[0] = 100;20 println("Updated first: ${numbers[0]}"); // 1002122 // ═══════════════════════════════════════23 // ITERATE24 // ═══════════════════════════════════════2526 println("\nAll names:");27 for (string name in names) {28 println(" - ${name}");29 }3031 println("\nAll scores:");32 for (int i = 0; i < scores.length(); i++) {33 println(" Student ${i + 1}: ${scores[i]}");34 }3536 // ═══════════════════════════════════════37 // ARRAY OPERATIONS38 // ═══════════════════════════════════════3940 println("\nLength: ${scores.length()}");4142 // Find max43 int maxScore = scores[0];44 for (int s in scores) {45 if (s > maxScore) maxScore = s;46 }47 println("Highest score: ${maxScore}");4849 // Sum50 int total = 0;51 for (int s in scores) {52 total += s;53 }54 println("Total: ${total}");55 println("Average: ${total / scores.length()}");56}
First: 10 Last: 50 Updated first: 100 All names: - Alice - Bob - Charlie All scores: Student 1: 95 Student 2: 87 Student 3: 92 Student 4: 78 Student 5: 88 Length: 5 Highest score: 95 Total: 440 Average: 88
14. Lists
Hands-on syntax example and reference implementation for Lists.
1import std.collections;23fn main() {4 // ═══════════════════════════════════════5 // CREATE LIST6 // ═══════════════════════════════════════78 List<string> fruits = new List<string>();9 fruits.add("Apple");10 fruits.add("Banana");11 fruits.add("Cherry");12 fruits.add("Date");13 fruits.add("Elderberry");1415 // Modern syntax16 let numbers = [10, 20, 30, 40, 50];1718 // ═══════════════════════════════════════19 // ACCESS20 // ═══════════════════════════════════════2122 println("First fruit: ${fruits[0]}"); // Apple23 println("List size: ${fruits.size()}"); // 52425 // ═══════════════════════════════════════26 // MODIFY27 // ═══════════════════════════════════════2829 fruits.push("Fig"); // Add to end30 fruits.remove("Date"); // Remove by value31 fruits[1] = "Blueberry"; // Replace3233 // ═══════════════════════════════════════34 // ITERATE35 // ═══════════════════════════════════════3637 println("\nFruit basket:");38 for (string fruit in fruits) {39 println(" 🍎 ${fruit}");40 }4142 // ═══════════════════════════════════════43 // CHECK44 // ═══════════════════════════════════════4546 if (fruits.contains("Cherry")) {47 println("\nWe have cherries! 🍒");48 }4950 println("Is empty: ${fruits.isEmpty()}"); // false5152 // ═══════════════════════════════════════53 // FUNCTIONAL OPERATIONS54 // ═══════════════════════════════════════5556 let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];5758 let evens = nums.filter(n => n % 2 == 0);59 let doubled = nums.map(n => n * 2);60 let sum = nums.reduce((a, b) => a + b);6162 println("\nOriginal: ${nums}");63 println("Evens: ${evens}"); // [2, 4, 6, 8, 10]64 println("Doubled: ${doubled}"); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]65 println("Sum: ${sum}"); // 5566}
15. Maps & Dictionaries
Hands-on syntax example and reference implementation for Maps & Dictionaries.
1import std.collections;23fn main() {4 // ═══════════════════════════════════════5 // CREATE MAP6 // ═══════════════════════════════════════78 Map<string, int> ages = new Map<string, int>();9 ages["Shanto"] = 21;10 ages["Alice"] = 25;11 ages["Bob"] = 30;1213 // Modern literal syntax14 let config = {15 "host": "localhost",16 "port": 8080,17 "debug": true18 };1920 let scores = {21 "math": 95,22 "science": 87,23 "english": 9224 };2526 // ═══════════════════════════════════════27 // ACCESS28 // ═══════════════════════════════════════2930 println("Shanto's age: ${ages["Shanto"]}"); // 2131 println("Math score: ${scores["math"]}"); // 953233 // ═══════════════════════════════════════34 // MODIFY35 // ═══════════════════════════════════════3637 ages["Charlie"] = 28; // Add new entry38 ages["Shanto"] = 22; // Update existing39 ages.remove("Bob"); // Remove entry4041 // ═══════════════════════════════════════42 // CHECK43 // ═══════════════════════════════════════4445 if (ages.containsKey("Alice")) {46 println("Alice is ${ages["Alice"]} years old");47 }4849 println("Total entries: ${ages.size()}");5051 // ═══════════════════════════════════════52 // ITERATE53 // ═══════════════════════════════════════5455 println("\nAll ages:");56 for (entry in ages) {57 println(" ${entry.key}: ${entry.value}");58 }5960 println("\nAll scores:");61 for (entry in scores) {62 println(" 📚 ${entry.key} → ${entry.value}");63 }64}
Shanto's age: 21 Math score: 95 Alice is 25 years old Total entries: 3 All ages: Shanto: 22 Alice: 25 Charlie: 28 All scores: 📚 math → 95 📚 science → 87 📚 english → 92
16. Classes
Hands-on syntax example and reference implementation for Classes.
1class User {2 string name;3 int age;4 string email;56 // Constructor7 User(string name, int age, string email) {8 this.name = name;9 this.age = age;10 this.email = email;11 }1213 // Methods14 fn introduce() {15 println("Hi! I'm ${name}, ${age} years old.");16 println("Email: ${email}");17 }1819 fn isAdult() -> bool {20 return age >= 18;21 }2223 fn birthday() {24 age++;25 println("🎂 Happy Birthday, ${name}! Now ${age}.");26 }27}2829fn main() {30 // Create objects31 User user1 = new User("Shanto", 21, "shanto@email.com");32 User user2 = new User("Alice", 17, "alice@email.com");3334 // Use methods35 user1.introduce();36 println("Is adult: ${user1.isAdult()}"); // true37 println("");3839 user2.introduce();40 println("Is adult: ${user2.isAdult()}"); // false41 println("");4243 user2.birthday(); // 🎂 Happy Birthday, Alice! Now 18.44 println("Is adult now: ${user2.isAdult()}"); // true45}
Hi! I'm Shanto, 21 years old. Email: shanto@email.com Is adult: true Hi! I'm Alice, 17 years old. Email: alice@email.com Is adult: false 🎂 Happy Birthday, Alice! Now 18. Is adult now: true
17. Constructors
Hands-on syntax example and reference implementation for Constructors.
1class Product {2 string name;3 double price;4 int quantity;5 string category;67 // ═══════════════════════════════════════8 // PRIMARY CONSTRUCTOR9 // ═══════════════════════════════════════1011 constructor(string name, double price, int quantity, string category) {12 this.name = name;13 this.price = price;14 this.quantity = quantity;15 this.category = category;16 }1718 // ═══════════════════════════════════════19 // JAVA/C# STYLE CONSTRUCTOR (also valid)20 // ═══════════════════════════════════════2122 Product(string name, double price) {23 this.name = name;24 this.price = price;25 this.quantity = 0;26 this.category = "General";27 }2829 // Methods30 fn totalValue() -> double {31 return price * quantity;32 }3334 fn display() {35 println("┌─────────────────────────────────┐");36 println("│ Product: ${name}");37 println("│ Price: \$${price}");38 println("│ Stock: ${quantity} units");39 println("│ Category: ${category}");40 println("│ Value: \$${totalValue()}");41 println("└─────────────────────────────────┘");42 }43}4445fn main() {46 Product laptop = new Product("MacBook Pro", 2499.99, 10, "Electronics");47 Product book = new Product("SP Language Guide", 29.99);4849 laptop.display();50 println("");51 book.display();52}
18. Access Modifiers
Hands-on syntax example and reference implementation for Access Modifiers.
1class BankAccount {2 // ═══════════════════════════════════════3 // PUBLIC — accessible from anywhere4 // ═══════════════════════════════════════5 public string ownerName;67 // ═══════════════════════════════════════8 // PRIVATE — only within this class9 // ═══════════════════════════════════════10 private double balance;11 private string accountNumber;1213 // ═══════════════════════════════════════14 // PROTECTED — this class + subclasses15 // ═══════════════════════════════════════16 protected string accountType;1718 // ═══════════════════════════════════════19 // INTERNAL — within same module only20 // ═══════════════════════════════════════21 internal string branchCode;2223 public BankAccount(string owner, double initial) {24 this.ownerName = owner;25 this.balance = initial;26 this.accountNumber = "ACC-" + generateId();27 this.accountType = "Savings";28 this.branchCode = "BR-001";29 }3031 // Public methods — anyone can call32 public fn deposit(double amount) {33 if (amount > 0) {34 balance += amount;35 println("✅ Deposited \$${amount}. New balance: \$${balance}");36 }37 }3839 public fn withdraw(double amount) {40 if (amount > 0 && amount <= balance) {41 balance -= amount;42 println("✅ Withdrew \$${amount}. New balance: \$${balance}");43 } else {44 println("❌ Insufficient funds.");45 }46 }4748 public fn getBalance() -> double {49 return balance;50 }5152 // Private method — internal use only53 private fn generateId() -> string {54 return "123456789";55 }56}5758fn main() {59 BankAccount account = new BankAccount("Shanto", 1000.0);6061 println("Owner: ${account.ownerName}"); // ✅ public62 account.deposit(500.0); // ✅ public method63 account.withdraw(200.0); // ✅ public method64 println("Balance: \$${account.getBalance()}");6566 // ❌ These would NOT compile:67 // println(account.balance); // error: 'balance' is private68 // println(account.accountNumber); // error: 'accountNumber' is private69 // account.generateId(); // error: 'generateId' is private70}
Owner: Shanto ✅ Deposited $500.0. New balance: $1500.0 ✅ Withdrew $200.0. New balance: $1300.0 Balance: $1300.0
19. Inheritance
Hands-on syntax example and reference implementation for Inheritance.
1// ═══════════════════════════════════════════════════2// BASE CLASS3// ═══════════════════════════════════════════════════45class Animal {6 protected string name;7 protected int age;89 Animal(string name, int age) {10 this.name = name;11 this.age = age;12 }1314 fn speak() {15 println("${name} makes a sound.");16 }1718 fn info() {19 println("${name}, age ${age}");20 }21}2223// ═══════════════════════════════════════════════════24// SUBCLASS — extends keyword25// ═══════════════════════════════════════════════════2627class Dog extends Animal {2829 string breed;3031 Dog(string name, int age, string breed) {32 super(name, age);33 this.breed = breed;34 }3536 override fn speak() {37 println("${name} says: Woof! 🐕");38 }3940 fn fetch() {41 println("${name} fetches the ball! 🎾");42 }43}4445class Cat extends Animal {4647 bool isIndoor;4849 Cat(string name, int age, bool isIndoor) {50 super(name, age);51 this.isIndoor = isIndoor;52 }5354 override fn speak() {55 println("${name} says: Meow! 🐱");56 }5758 fn purr() {59 println("${name} is purring... 😺");60 }61}6263// ═══════════════════════════════════════════════════64// C# STYLE SYNTAX (also valid!)65// class Bird : Animal { }66// ═══════════════════════════════════════════════════6768class Bird : Animal {69 Bird(string name, int age) {70 super(name, age);71 }7273 override fn speak() {74 println("${name} says: Tweet! 🐦");75 }76}7778fn main() {79 Dog dog = new Dog("Buddy", 3, "Golden Retriever");80 Cat cat = new Cat("Whiskers", 5, true);81 Bird bird = new Bird("Tweety", 2);8283 // Polymorphism84 Animal[] animals = {dog, cat, bird};8586 println("=== Animal Shelter ===\n");8788 for (Animal animal in animals) {89 animal.info();90 animal.speak();91 println("");92 }9394 // Class-specific methods95 dog.fetch();96 cat.purr();97}
=== Animal Shelter === Buddy, age 3 Buddy says: Woof! 🐕 Whiskers, age 5 Whiskers says: Meow! 🐱 Tweety, age 2 Tweety says: Tweet! 🐦 Buddy fetches the ball! 🎾 Whiskers is purring... 😺
20. Interfaces
Hands-on syntax example and reference implementation for Interfaces.
1// ═══════════════════════════════════════════════════2// DEFINE INTERFACES3// ═══════════════════════════════════════════════════45interface Drawable {6 fn draw();7 fn getColor() -> string;8}910interface Resizable {11 fn resize(double factor);12 fn getArea() -> double;13}1415// ═══════════════════════════════════════════════════16// IMPLEMENT INTERFACES17// ═══════════════════════════════════════════════════1819class Circle implements Drawable, Resizable {20 double radius;21 string color;2223 Circle(double radius, string color) {24 this.radius = radius;25 this.color = color;26 }2728 fn draw() {29 println("Drawing ⭕ Circle (r=${radius}, color=${color})");30 }3132 fn getColor() -> string {33 return color;34 }3536 fn resize(double factor) {37 radius *= factor;38 println("Resized circle to radius ${radius}");39 }4041 fn getArea() -> double {42 return 3.14159 * radius * radius;43 }44}4546class Rectangle implements Drawable, Resizable {47 double width;48 double height;49 string color;5051 Rectangle(double w, double h, string color) {52 this.width = w;53 this.height = h;54 this.color = color;55 }5657 fn draw() {58 println("Drawing ▬ Rectangle (${width}x${height}, color=${color})");59 }6061 fn getColor() -> string {62 return color;63 }6465 fn resize(double factor) {66 width *= factor;67 height *= factor;68 }6970 fn getArea() -> double {71 return width * height;72 }73}7475fn main() {76 Drawable[] shapes = {77 new Circle(5.0, "Red"),78 new Rectangle(4.0, 6.0, "Blue")79 };8081 for (Drawable shape in shapes) {82 shape.draw();83 }8485 println("\nAreas:");86 Circle c = new Circle(10.0, "Green");87 println("Circle area: ${c.getArea()}"); // 314.1598889 Rectangle r = new Rectangle(5.0, 8.0, "Yellow");90 println("Rectangle area: ${r.getArea()}"); // 40.091}
21. Abstract Classes
Hands-on syntax example and reference implementation for Abstract Classes.
1abstract class Vehicle {2 protected string brand;3 protected int year;45 Vehicle(string brand, int year) {6 this.brand = brand;7 this.year = year;8 }910 // Abstract — must be implemented by subclasses11 abstract fn fuelType() -> string;12 abstract fn maxSpeed() -> int;1314 // Concrete — shared by all subclasses15 fn info() {16 println("${brand} (${year}) — ${fuelType()}, max ${maxSpeed()} km/h");17 }18}1920class Car extends Vehicle {21 Car(string brand, int year) { super(brand, year); }2223 fn fuelType() -> string { return "Gasoline ⛽"; }24 fn maxSpeed() -> int { return 220; }25}2627class ElectricCar extends Vehicle {28 ElectricCar(string brand, int year) { super(brand, year); }2930 fn fuelType() -> string { return "Electric ⚡"; }31 fn maxSpeed() -> int { return 250; }32}3334class Bicycle extends Vehicle {35 Bicycle(string brand, int year) { super(brand, year); }3637 fn fuelType() -> string { return "Human Power 🚴"; }38 fn maxSpeed() -> int { return 45; }39}4041fn main() {42 Vehicle[] vehicles = {43 new Car("Toyota", 2024),44 new ElectricCar("Tesla", 2025),45 new Bicycle("Trek", 2023)46 };4748 println("=== Vehicle Fleet ===\n");49 for (Vehicle v in vehicles) {50 v.info();51 }52}
=== Vehicle Fleet === Toyota (2024) — Gasoline ⛽, max 220 km/h Tesla (2025) — Electric ⚡, max 250 km/h Trek (2023) — Human Power 🚴, max 45 km/h
22. Static Members
Hands-on syntax example and reference implementation for Static Members.
1class Counter {2 private static int count = 0;34 static fn increment() {5 count++;6 }78 static fn getCount() -> int {9 return count;10 }1112 static fn reset() {13 count = 0;14 }15}1617class MathUtils {18 static const double PI = 3.14159265358979;19 static const double E = 2.71828182845904;2021 static fn circleArea(double radius) -> double {22 return PI * radius * radius;23 }2425 static fn square(int x) -> int {26 return x * x;27 }2829 static fn power(int base, int exp) -> int {30 int result = 1;31 for (int i = 0; i < exp; i++) {32 result *= base;33 }34 return result;35 }36}3738fn main() {39 // Static methods — no object needed40 Counter.increment();41 Counter.increment();42 Counter.increment();43 println("Count: ${Counter.getCount()}"); // 34445 println("PI: ${MathUtils.PI}");46 println("Circle area (r=5): ${MathUtils.circleArea(5.0)}");47 println("5² = ${MathUtils.square(5)}");48 println("2^10 = ${MathUtils.power(2, 10)}");49}
23. Structs
Hands-on syntax example and reference implementation for Structs.
1// ═══════════════════════════════════════════════════2// STRUCT — lightweight value type (stack allocated)3// ═══════════════════════════════════════════════════45struct Point {6 int x;7 int y;8}910struct Color {11 int r;12 int g;13 int b;14}1516struct Rectangle {17 Point topLeft;18 Point bottomRight;19 Color color;20}2122fn distance(Point a, Point b) -> double {23 int dx = b.x - a.x;24 int dy = b.y - a.y;25 return math.sqrt(dx * dx + dy * dy);26}2728fn main() {29 Point p1;30 p1.x = 0;31 p1.y = 0;3233 Point p2;34 p2.x = 3;35 p2.y = 4;3637 println("Point 1: (${p1.x}, ${p1.y})");38 println("Point 2: (${p2.x}, ${p2.y})");39 println("Distance: ${distance(p1, p2)}"); // 5.04041 Color red;42 red.r = 255;43 red.g = 0;44 red.b = 0;45 println("\nColor: rgb(${red.r}, ${red.g}, ${red.b})");46}
24. Enums
Hands-on syntax example and reference implementation for Enums.
1enum Direction {2 North,3 South,4 East,5 West6}78enum HttpStatus {9 OK = 200,10 NotFound = 404,11 ServerError = 50012}1314enum LogLevel {15 Debug,16 Info,17 Warning,18 Error,19 Fatal20}2122fn describeDirection(Direction dir) -> string {23 match dir {24 Direction.North => return "⬆️ Going North",25 Direction.South => return "⬇️ Going South",26 Direction.East => return "➡️ Going East",27 Direction.West => return "⬅️ Going West"28 }29}3031fn log(LogLevel level, string message) {32 match level {33 LogLevel.Debug => println("[DEBUG] ${message}"),34 LogLevel.Info => println("[INFO] ${message}"),35 LogLevel.Warning => println("[WARNING] ${message}"),36 LogLevel.Error => println("[ERROR] ${message}"),37 LogLevel.Fatal => println("[FATAL] ${message}")38 }39}4041fn main() {42 Direction dir = Direction.North;43 println(describeDirection(dir));4445 HttpStatus status = HttpStatus.OK;46 println("HTTP ${status}");4748 println("\n=== Log Messages ===");49 log(LogLevel.Info, "Application started");50 log(LogLevel.Debug, "Loading config...");51 log(LogLevel.Warning, "Memory usage high");52 log(LogLevel.Error, "Connection failed");53}
⬆️ Going North HTTP 200 === Log Messages === [INFO] Application started [DEBUG] Loading config... [WARNING] Memory usage high [ERROR] Connection failed
25. Generics
Hands-on syntax example and reference implementation for Generics.
1// ═══════════════════════════════════════════════════2// GENERIC CLASS3// ═══════════════════════════════════════════════════45class Box<T> {6 private T value;78 Box(T value) {9 this.value = value;10 }1112 fn get() -> T {13 return value;14 }1516 fn set(T newValue) {17 value = newValue;18 }1920 fn display() {21 println("Box contains: ${value}");22 }23}2425// ═══════════════════════════════════════════════════26// GENERIC PAIR27// ═══════════════════════════════════════════════════2829class Pair<A, B> {30 A first;31 B second;3233 Pair(A first, B second) {34 this.first = first;35 this.second = second;36 }3738 fn display() {39 println("(${first}, ${second})");40 }41}4243// ═══════════════════════════════════════════════════44// GENERIC STACK45// ═══════════════════════════════════════════════════4647class Stack<T> {48 private List<T> items = new List<T>();4950 fn push(T item) {51 items.add(item);52 }5354 fn pop() -> T {55 return items.removeLast();56 }5758 fn peek() -> T {59 return items[items.size() - 1];60 }6162 fn isEmpty() -> bool {63 return items.size() == 0;64 }6566 fn size() -> int {67 return items.size();68 }69}7071// ═══════════════════════════════════════════════════72// GENERIC FUNCTIONS73// ═══════════════════════════════════════════════════7475fn max<T>(T a, T b) -> T {76 return a > b ? a : b;77}7879fn swap<T>(T a, T b) -> Pair<T, T> {80 return new Pair<T, T>(b, a);81}8283fn main() {84 // Generic Box85 Box<int> intBox = new Box<int>(42);86 Box<string> strBox = new Box<string>("Hello SP");8788 intBox.display(); // Box contains: 4289 strBox.display(); // Box contains: Hello SP9091 // Generic Pair92 Pair<string, int> person = new Pair<string, int>("Shanto", 21);93 person.display(); // (Shanto, 21)9495 // Generic Stack96 Stack<string> stack = new Stack<string>();97 stack.push("first");98 stack.push("second");99 stack.push("third");100101 println("\nStack (LIFO):");102 while (!stack.isEmpty()) {103 println(" popped: ${stack.pop()}");104 }105106 // Generic functions107 println("\nmax(10, 20) = ${max(10, 20)}");108 println("max(\"apple\", \"banana\") = ${max("apple", "banana")}");109}
Box contains: 42
Box contains: Hello SP
(Shanto, 21)
Stack (LIFO):
popped: third
popped: second
popped: first
max(10, 20) = 20
max("apple", "banana") = banana26. Null Safety
Hands-on syntax example and reference implementation for Null Safety.
1class User {2 string name;3 string? email; // Nullable — can be null45 User(string name, string? email) {6 this.name = name;7 this.email = email;8 }9}1011fn findUser(int id) -> User? {12 if (id == 1) return new User("Shanto", "shanto@email.com");13 if (id == 2) return new User("Alice", null);14 return null; // User not found15}1617fn main() {18 // ═══════════════════════════════════════19 // NULLABLE TYPES (?)20 // ═══════════════════════════════════════2122 User? user1 = findUser(1);23 User? user2 = findUser(2);24 User? user3 = findUser(999);2526 // ═══════════════════════════════════════27 // SAFE ACCESS (?.)28 // ═══════════════════════════════════════2930 println("User 1 name: ${user1?.name}"); // Shanto31 println("User 1 email: ${user1?.email}"); // shanto@email.com32 println("User 3 name: ${user3?.name}"); // null (no crash!)3334 // ═══════════════════════════════════════35 // NULL COALESCING (??)36 // ═══════════════════════════════════════3738 string email1 = user1?.email ?? "no-email@default.com";39 string email2 = user2?.email ?? "no-email@default.com";40 string name3 = user3?.name ?? "Unknown User";4142 println("\nEmail 1: ${email1}"); // shanto@email.com43 println("Email 2: ${email2}"); // no-email@default.com44 println("Name 3: ${name3}"); // Unknown User4546 // ═══════════════════════════════════════47 // NULL CHECK48 // ═══════════════════════════════════════4950 if (user1 != null) {51 println("\n✅ Found user: ${user1.name}");52 }5354 if (user3 == null) {55 println("❌ User not found");56 }5758 // ═══════════════════════════════════════59 // NON-NULLABLE (default — safe!)60 // ═══════════════════════════════════════6162 // string name = null; // ❌ COMPILE ERROR!63 // int age = null; // ❌ COMPILE ERROR!64}
27. Error Handling — Try/Catch
Hands-on syntax example and reference implementation for Error Handling — Try/Catch.
1fn main() {2 // ═══════════════════════════════════════3 // TRY / CATCH / FINALLY4 // ═══════════════════════════════════════56 try {7 int result = 100 / 0;8 println(result);9 } catch (ArithmeticException e) {10 println("❌ Math error: ${e.message}");11 } finally {12 println("✅ Cleanup complete.");13 }1415 // ═══════════════════════════════════════16 // MULTIPLE CATCH BLOCKS17 // ═══════════════════════════════════════1819 try {20 string data = readFile("config.json");21 Config config = parseConfig(data);22 connect(config.host);23 } catch (FileNotFoundException e) {24 println("📁 File not found: ${e.message}");25 } catch (ParseException e) {26 println("📝 Invalid format: ${e.message}");27 } catch (ConnectionException e) {28 println("🌐 Connection failed: ${e.message}");29 } catch (Exception e) {30 println("💥 Unexpected error: ${e.message}");31 } finally {32 println("Done.");33 }3435 // ═══════════════════════════════════════36 // THROW EXCEPTIONS37 // ═══════════════════════════════════════3839 try {40 validateAge(-5);41 } catch (Exception e) {42 println("Validation: ${e.message}");43 }44}4546fn validateAge(int age) {47 if (age < 0) {48 throw Exception("Age cannot be negative: ${age}");49 }50 if (age > 150) {51 throw Exception("Age too large: ${age}");52 }53 println("Valid age: ${age}");54}
28. Error Handling — Result Type
Hands-on syntax example and reference implementation for Error Handling — Result Type.
1// ═══════════════════════════════════════════════════2// RESULT TYPE — Modern error handling3// ═══════════════════════════════════════════════════45fn divide(int a, int b) -> Result<int, Error> {6 if (b == 0) {7 return Error("Cannot divide ${a} by zero");8 }9 return Ok(a / b);10}1112fn parseNumber(string input) -> Result<int, Error> {13 try {14 return Ok(int.parse(input));15 } catch (Exception e) {16 return Error("Invalid number: '${input}'");17 }18}1920fn main() {21 // Success case22 let result1 = divide(100, 5);23 match result1 {24 Ok(value) => println("100 / 5 = ${value}"),25 Error(err) => println("Error: ${err}")26 }2728 // Error case29 let result2 = divide(100, 0);30 match result2 {31 Ok(value) => println("Result: ${value}"),32 Error(err) => println("Error: ${err}")33 }3435 // Chain operations36 let parsed = parseNumber("42");37 match parsed {38 Ok(n) => println("Parsed: ${n}"),39 Error(e) => println("Failed: ${e}")40 }4142 let invalid = parseNumber("hello");43 match invalid {44 Ok(n) => println("Parsed: ${n}"),45 Error(e) => println("Failed: ${e}")46 }47}
100 / 5 = 20 Error: Cannot divide 100 by zero Parsed: 42 Failed: Invalid number: 'hello'
29. Lambda Functions
Hands-on syntax example and reference implementation for Lambda Functions.
1fn main() {2 // ═══════════════════════════════════════3 // LAMBDA SYNTAX: (params) => expression4 // ═══════════════════════════════════════56 var add = (int a, int b) => a + b;7 var multiply = (int a, int b) => a * b;8 var square = (int x) => x * x;9 var isEven = (int n) => n % 2 == 0;10 var greet = (string name) => "Hello, ${name}!";1112 println(add(10, 20)); // 3013 println(multiply(5, 4)); // 2014 println(square(7)); // 4915 println(isEven(42)); // true16 println(greet("Shanto")); // Hello, Shanto!1718 // ═══════════════════════════════════════19 // LAMBDA WITH BLOCK BODY20 // ═══════════════════════════════════════2122 var factorial = (int n) => {23 int result = 1;24 for (int i = 2; i <= n; i++) {25 result *= i;26 }27 return result;28 };2930 println("5! = ${factorial(5)}"); // 12031 println("10! = ${factorial(10)}"); // 36288003233 // ═══════════════════════════════════════34 // LAMBDA AS FUNCTION ARGUMENT35 // ═══════════════════════════════════════3637 let numbers = [1, 2, 3, 4, 5];3839 let doubled = numbers.map(x => x * 2);40 println("Doubled: ${doubled}"); // [2, 4, 6, 8, 10]4142 let evens = numbers.filter(x => x % 2 == 0);43 println("Evens: ${evens}"); // [2, 4]4445 let sum = numbers.reduce((a, b) => a + b);46 println("Sum: ${sum}"); // 1547}
30. Higher-Order Functions
Hands-on syntax example and reference implementation for Higher-Order Functions.
1// ═══════════════════════════════════════════════════2// FUNCTIONS THAT TAKE FUNCTIONS AS PARAMETERS3// ═══════════════════════════════════════════════════45fn applyTwice(fn(int) -> int operation, int value) -> int {6 return operation(operation(value));7}89fn transform(int[] arr, fn(int) -> int func) -> int[] {10 int[] result = new int[arr.length()];11 for (int i = 0; i < arr.length(); i++) {12 result[i] = func(arr[i]);13 }14 return result;15}1617fn executeIf(bool condition, fn() action) {18 if (condition) {19 action();20 }21}2223// ═══════════════════════════════════════════════════24// FUNCTIONS THAT RETURN FUNCTIONS25// ═══════════════════════════════════════════════════2627fn multiplier(int factor) -> fn(int) -> int {28 return (int x) => x * factor;29}3031fn adder(int amount) -> fn(int) -> int {32 return (int x) => x + amount;33}3435fn main() {36 // Pass lambda to function37 int result = applyTwice(x => x * 2, 3);38 println("applyTwice(double, 3) = ${result}"); // 123940 // Transform array41 int[] nums = {1, 2, 3, 4, 5};42 int[] squared = transform(nums, x => x * x);43 println("Squared: ${squared}"); // [1, 4, 9, 16, 25]4445 // Conditional execution46 executeIf(true, () => println("This runs!"));47 executeIf(false, () => println("This doesn't!"));4849 // Function factories50 var double = multiplier(2);51 var triple = multiplier(3);52 var addTen = adder(10);5354 println("double(5) = ${double(5)}"); // 1055 println("triple(5) = ${triple(5)}"); // 1556 println("addTen(5) = ${addTen(5)}"); // 155758 // ═══════════════════════════════════════59 // CHAINING: map → filter → reduce60 // ═══════════════════════════════════════6162 let result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]63 .map(x => x * x) // square each64 .filter(x => x > 20) // keep > 2065 .reduce((a, b) => a + b); // sum them6667 println("\nSum of squares > 20: ${result}"); // 25+36+49+64+81+100 = 35568}
31. Closures
Hands-on syntax example and reference implementation for Closures.
1fn makeCounter() -> fn() -> int {2 int count = 0;3 return () => {4 count++;5 return count;6 };7}89fn makeGreeter(string greeting) -> fn(string) -> string {10 return (string name) => "${greeting}, ${name}!";11}1213fn main() {14 // Counter closure — captures and modifies `count`15 var counter = makeCounter();16 println(counter()); // 117 println(counter()); // 218 println(counter()); // 31920 // Greeter closure — captures `greeting`21 var hello = makeGreeter("Hello");22 var hi = makeGreeter("Hi");2324 println(hello("Shanto")); // Hello, Shanto!25 println(hi("Alice")); // Hi, Alice!26}
32. String Methods
Hands-on syntax example and reference implementation for String Methods.
1fn main() {2 string text = " Hello, SP Programming Language! ";34 // ═══════════════════════════════════════5 // COMMON STRING METHODS6 // ═══════════════════════════════════════78 println("Original: '${text}'");9 println("Trimmed: '${text.trim()}'");10 println("Length: ${text.trim().length()}");11 println("Upper: ${text.trim().upper()}");12 println("Lower: ${text.trim().lower()}");13 println("Contains: ${text.contains("SP")}"); // true14 println("StartsWith: ${text.trim().startsWith("Hello")}"); // true15 println("EndsWith: ${text.trim().endsWith("!")}"); // true16 println("IndexOf: ${text.indexOf("SP")}"); // 917 println("Replace: ${text.trim().replace("SP", "Shanto Paul")}");18 println("Substring: ${text.trim().substring(0, 5)}"); // Hello19 println("CharAt: ${text.trim().charAt(0)}"); // H2021 // ═══════════════════════════════════════22 // SPLIT & JOIN23 // ═══════════════════════════════════════2425 string csv = "apple,banana,cherry,date";26 let fruits = csv.split(",");27 println("\nSplit CSV:");28 for (string fruit in fruits) {29 println(" - ${fruit}");30 }3132 string joined = fruits.join(" | ");33 println("Joined: ${joined}");34 // apple | banana | cherry | date3536 // ═══════════════════════════════════════37 // STRING INTERPOLATION38 // ═══════════════════════════════════════3940 string name = "Shanto";41 int age = 21;42 double gpa = 3.95;4344 println("\n${name} is ${age} years old with GPA ${gpa}");45 println("In 5 years: ${name} will be ${age + 5}");46 println("Name reversed: ... (exercise for the reader!)");47}
33. Method Overloading
Hands-on syntax example and reference implementation for Method Overloading.
1class Printer {23 // Same method name, different parameter types4 fn print(int value) {5 println("Integer: ${value}");6 }78 fn print(double value) {9 println("Double: ${value}");10 }1112 fn print(string value) {13 println("String: ${value}");14 }1516 fn print(bool value) {17 println("Boolean: ${value}");18 }1920 // Different parameter counts21 fn print(string label, int value) {22 println("${label}: ${value}");23 }2425 fn print(string label, int value, string unit) {26 println("${label}: ${value} ${unit}");27 }28}2930fn main() {31 Printer p = new Printer();3233 p.print(42); // Integer: 4234 p.print(3.14); // Double: 3.1435 p.print("Hello"); // String: Hello36 p.print(true); // Boolean: true37 p.print("Age", 21); // Age: 2138 p.print("Weight", 75, "kg"); // Weight: 75 kg39}
34. Operator Overloading
Hands-on syntax example and reference implementation for Operator Overloading.
1struct Vector2 {2 float x;3 float y;45 operator +(Vector2 a, Vector2 b) {6 return Vector2(a.x + b.x, a.y + b.y);7 }89 operator -(Vector2 a, Vector2 b) {10 return Vector2(a.x - b.x, a.y - b.y);11 }1213 operator *(Vector2 v, float scalar) {14 return Vector2(v.x * scalar, v.y * scalar);15 }1617 operator ==(Vector2 a, Vector2 b) {18 return a.x == b.x && a.y == b.y;19 }20}2122fn main() {23 Vector2 a = Vector2(3.0, 4.0);24 Vector2 b = Vector2(1.0, 2.0);2526 Vector2 sum = a + b;27 Vector2 diff = a - b;28 Vector2 scaled = a * 2.0;2930 println("a + b = (${sum.x}, ${sum.y})"); // (4.0, 6.0)31 println("a - b = (${diff.x}, ${diff.y})"); // (2.0, 2.0)32 println("a * 2 = (${scaled.x}, ${scaled.y})"); // (6.0, 8.0)33 println("a == b: ${a == b}"); // false34}
35. Extension Methods
Hands-on syntax example and reference implementation for Extension Methods.
1extend string {2 fn isEmail() -> bool {3 return this.contains("@") && this.contains(".");4 }56 fn reverse() -> string {7 string result = "";8 for (int i = this.length() - 1; i >= 0; i--) {9 result += this.charAt(i);10 }11 return result;12 }1314 fn wordCount() -> int {15 return this.trim().split(" ").length();16 }17}1819extend int {20 fn isEven() -> bool { return this % 2 == 0; }21 fn isOdd() -> bool { return this % 2 != 0; }22 fn factorial() -> int {23 int result = 1;24 for (int i = 2; i <= this; i++) result *= i;25 return result;26 }27}2829fn main() {30 // String extensions31 println("test@email.com".isEmail()); // true32 println("not-an-email".isEmail()); // false33 println("Hello".reverse()); // olleH34 println("Hello SP World".wordCount()); // 33536 // Int extensions37 println(42.isEven()); // true38 println(7.isOdd()); // true39 println(5.factorial()); // 12040}
36. Traits
Hands-on syntax example and reference implementation for Traits.
1trait Serializable {2 fn serialize() -> string;3 fn deserialize(string data);4}56trait Displayable {7 fn display();8}910class User with Serializable, Displayable {11 string name;12 int age;1314 User(string name, int age) {15 this.name = name;16 this.age = age;17 }1819 fn serialize() -> string {20 return "{\"name\":\"${name}\",\"age\":${age}}";21 }2223 fn deserialize(string data) {24 // Parse JSON data...25 }2627 fn display() {28 println("👤 ${name} (${age})");29 }30}3132fn main() {33 User user = new User("Shanto", 21);34 user.display(); // 👤 Shanto (21)35 println("JSON: ${user.serialize()}"); // {"name":"Shanto","age":21}36}
37. Annotations
Hands-on syntax example and reference implementation for Annotations.
1@Serializable2class Config {3 string host;4 int port;5 bool debug;6}78class ApiController {910 @Route("/users")11 @Method("GET")12 fn getUsers() -> List<User> {13 return userService.findAll();14 }1516 @Route("/users")17 @Method("POST")18 fn createUser(User user) -> User {19 return userService.save(user);20 }2122 @Deprecated("Use getUsers() instead")23 fn listUsers() -> List<User> {24 return getUsers();25 }26}2728class MathService {2930 @inline31 fn add(int a, int b) -> int {32 return a + b;33 }3435 @Test36 fn testAdd() {37 assert(add(2, 3) == 5);38 }39}
38. Modules & Imports
Hands-on syntax example and reference implementation for Modules & Imports.
1// ═══════════════════════════════════════════════════2// FILE: src/models/user.sp3// ═══════════════════════════════════════════════════45module myapp.models;67public class User {8 public string name;9 public int age;1011 public User(string name, int age) {12 this.name = name;13 this.age = age;14 }15}1617// ═══════════════════════════════════════════════════18// FILE: src/services/user_service.sp19// ═══════════════════════════════════════════════════2021module myapp.services;2223import myapp.models.User;2425public class UserService {26 private List<User> users = new List<User>();2728 public fn addUser(User user) {29 users.add(user);30 }3132 public fn findByName(string name) -> User? {33 for (User u in users) {34 if (u.name == name) return u;35 }36 return null;37 }38}3940// ═══════════════════════════════════════════════════41// FILE: src/main.sp42// ═══════════════════════════════════════════════════4344import std.io;45import myapp.models.User;46import myapp.services.UserService;4748fn main() {49 UserService service = new UserService();50 service.addUser(new User("Shanto", 21));51 service.addUser(new User("Alice", 25));5253 User? user = service.findByName("Shanto");54 println("Found: ${user?.name}, age ${user?.age}");5556 // Standard library imports57 import std.math;58 import std.collections;59 import std.fs;60 import std.json;61 import std.http;62 import std.time;63}
39. Async & Await
Hands-on syntax example and reference implementation for Async & Await.
1import std.http;2import std.io;34async fn fetchUser(int id) -> User {5 let response = await http.get("https://api.example.com/users/${id}");6 return json.parse<User>(response.body);7}89async fn fetchMultipleUsers() {10 // Sequential11 let user1 = await fetchUser(1);12 let user2 = await fetchUser(2);1314 println("User 1: ${user1.name}");15 println("User 2: ${user2.name}");16}1718async fn main() {19 println("Fetching data...");20 await fetchMultipleUsers();21 println("Done!");22}
40. Threads & Concurrency
Hands-on syntax example and reference implementation for Threads & Concurrency.
1fn main() {2 // ═══════════════════════════════════════3 // SPAWN A THREAD4 // ═══════════════════════════════════════56 thread {7 for (i in 0..5) {8 println("Background: ${i}");9 }10 }1112 for (i in 0..5) {13 println("Main: ${i}");14 }1516 // ═══════════════════════════════════════17 // FUTURE PRIMITIVES18 // ═══════════════════════════════════════19 // spawn — launch concurrent task20 // channel — message passing21 // mutex — mutual exclusion22 // atomic — atomic operations23}
41. Unsafe Mode
Hands-on syntax example and reference implementation for Unsafe Mode.
1fn main() {2 // ═══════════════════════════════════════3 // UNSAFE BLOCK — for systems programming4 // ═══════════════════════════════════════56 unsafe {7 pointer p = allocate(1024); // Raw memory allocation8 // Direct memory operations9 // Pointer arithmetic10 // No bounds checking11 free(p);12 }1314 // Outside unsafe: full safety guarantees15 println("Back to safe SP! ✅");16}
42. Native Interop (C FFI)
Hands-on syntax example and reference implementation for Native Interop (C FFI).
1// ═══════════════════════════════════════════════════2// CALL C FUNCTIONS FROM SP3// ═══════════════════════════════════════════════════45extern "C" {6 fn printf(string format);7 fn strlen(string s) -> int;8 fn malloc(int size) -> pointer;9 fn free(pointer p);10}1112fn main() {13 // Call C's printf directly14 printf("Hello from C! %d\n", 42);1516 // Use C's strlen17 int len = strlen("Hello");18 println("strlen: ${len}"); // 519}
43. Testing
Hands-on syntax example and reference implementation for Testing.
1import std.testing;23// ═══════════════════════════════════════════════════4// FUNCTIONS TO TEST5// ═══════════════════════════════════════════════════67fn add(int a, int b) -> int { return a + b; }8fn factorial(int n) -> int {9 if (n <= 1) return 1;10 return n * factorial(n - 1);11}12fn isEven(int n) -> bool { return n % 2 == 0; }1314// ═══════════════════════════════════════════════════15// TEST BLOCKS16// ═══════════════════════════════════════════════════1718test "addition works" {19 assert(add(2, 3) == 5);20 assert(add(-1, 1) == 0);21 assert(add(0, 0) == 0);22}2324test "factorial is correct" {25 assert(factorial(0) == 1);26 assert(factorial(1) == 1);27 assert(factorial(5) == 120);28 assert(factorial(10) == 3628800);29}3031test "even/odd detection" {32 assert(isEven(0) == true);33 assert(isEven(2) == true);34 assert(isEven(3) == false);35 assert(isEven(100) == true);36}3738test "string operations" {39 string name = "Shanto";40 assert(name.length() == 6);41 assert(name.upper() == "SHANTO");42 assert(name.contains("han") == true);43}
44. Comments & Documentation
Hands-on syntax example and reference implementation for Comments & Documentation.
1// ═══════════════════════════════════════════════════2// SINGLE-LINE COMMENT3// ═══════════════════════════════════════════════════45// This is a single-line comment6int age = 21; // This is an inline comment78// ═══════════════════════════════════════════════════9// MULTI-LINE COMMENT10// ═══════════════════════════════════════════════════1112/*13 This is a multi-line comment.14 It can span multiple lines.15 Useful for longer explanations.16*/1718// ═══════════════════════════════════════════════════19// DOCUMENTATION COMMENT (for spc doc)20// ═══════════════════════════════════════════════════2122/// Calculates the sum of two integers.23///24/// @param a The first integer.25/// @param b The second integer.26/// @return The sum of a and b.27///28/// Example:29///
45. Multi-Syntax Compatibility
SP's unique feature — multiple syntax styles that compile to identical code:
1// ═══════════════════════════════════════════════════2// FUNCTION DECLARATION — 3 valid styles3// ═══════════════════════════════════════════════════45// Style 1: SP-native6fn add(int a, int b) -> int {7 return a + b;8}910// Style 2: Java / C++ / C#11int add(int a, int b) {12 return a + b;13}1415// Style 3: Short form16fn add(a, b) => a + b;171819// ═══════════════════════════════════════════════════20// VOID FUNCTIONS — 2 valid styles21// ═══════════════════════════════════════════════════2223// SP-native24fn printName() {25 println("Shanto");26}2728// Java/C++ style29void printName() {30 println("Shanto");31}323334// ═══════════════════════════════════════════════════35// INHERITANCE — 2 valid styles36// ═══════════════════════════════════════════════════3738// Java style39class Dog extends Animal { }4041// C# style42class Dog : Animal { }434445// ═══════════════════════════════════════════════════46// INTERFACE IMPLEMENTATION — 2 valid styles47// ═══════════════════════════════════════════════════4849// Java style50class User implements Serializable { }5152// C# style53class User : Serializable { }545556// ═══════════════════════════════════════════════════57// SWITCH vs MATCH58// ═══════════════════════════════════════════════════5960// Classic (C/Java)61switch (x) {62 case 1: println("one"); break;63 default: println("other");64}6566// Modern (SP)67match x {68 1 => println("one"),69 _ => println("other")70}717273// ═══════════════════════════════════════════════════74// CONSTRUCTOR — 2 valid styles75// ═══════════════════════════════════════════════════7677// SP-native78class User {79 constructor(string name) {80 this.name = name;81 }82}8384// Java/C# style85class User {86 User(string name) {87 this.name = name;88 }89}909192// ═══════════════════════════════════════════════════93// ENTRY POINT — 2 valid styles94// ═══════════════════════════════════════════════════9596// SP-native (recommended)97fn main() {98 println("Hello, SP!");99}100101// Java-style (compatibility)102public static void main() {103 System.out.println("Hello, SP!");104}
46. Complete Programs
Examples and idioms for Complete Programs, starting with 🧮 calculator.
🧮 Calculator
1import std.io;23fn main() {4 println("═══════════════════════════");5 println(" SP Calculator");6 println("═══════════════════════════\n");78 print("Enter first number: ");9 double a = double.parse(readLine());1011 print("Enter operator (+, -, *, /): ");12 string op = readLine();1314 print("Enter second number: ");15 double b = double.parse(readLine());1617 double result;18 match op {19 "+" => result = a + b,20 "-" => result = a - b,21 "*" => result = a * b,22 "/" => {23 if (b == 0) {24 println("❌ Error: Division by zero!");25 return;26 }27 result = a / b;28 },29 _ => {30 println("❌ Unknown operator: ${op}");31 return;32 }33 }3435 println("\n✅ ${a} ${op} ${b} = ${result}");36}
📝 Todo App
1import std.io;2import std.collections;34class Task {5 string title;6 bool done;78 Task(string title) {9 this.title = title;10 this.done = false;11 }1213 fn toggle() { done = !done; }1415 fn toString() -> string {16 string icon = done ? "✅" : "⬜";17 return "${icon} ${title}";18 }19}2021class TodoApp {22 private List<Task> tasks = new List<Task>();2324 fn add(string title) {25 tasks.add(new Task(title));26 println("Added: ${title}");27 }2829 fn complete(int index) {30 if (index >= 0 && index < tasks.size()) {31 tasks[index].toggle();32 println("Toggled: ${tasks[index].title}");33 }34 }3536 fn show() {37 println("\n╔══════════════════════════════╗");38 println("║ 📋 TODO LIST ║");39 println("╠══════════════════════════════╣");4041 if (tasks.isEmpty()) {42 println("║ No tasks yet! ║");43 }4445 for (int i = 0; i < tasks.size(); i++) {46 println("║ ${i + 1}. ${tasks[i].toString()}");47 }4849 int done = tasks.filter(t => t.done).size();50 println("╠══════════════════════════════╣");51 println("║ ${done}/${tasks.size()} completed");52 println("╚══════════════════════════════╝");53 }54}5556fn main() {57 TodoApp app = new TodoApp();5859 app.add("Learn SP syntax");60 app.add("Build a compiler");61 app.add("Write standard library");62 app.add("Create VS Code extension");63 app.add("Launch SP 1.0");6465 app.complete(0); // Learn SP syntax ✅66 app.complete(1); // Build a compiler ✅6768 app.show();69}
Added: Learn SP syntax Added: Build a compiler Added: Write standard library Added: Create VS Code extension Added: Launch SP 1.0 Toggled: Learn SP syntax Toggled: Build a compiler ╔══════════════════════════════╗ ║ 📋 TODO LIST ║ ╠══════════════════════════════╣ ║ 1. ✅ Learn SP syntax ║ 2. ✅ Build a compiler ║ 3. ⬜ Write standard library ║ 4. ⬜ Create VS Code extension ║ 5. ⬜ Launch SP 1.0 ╠══════════════════════════════╣ ║ 2/5 completed ╚══════════════════════════════╝
🏦 Banking System
1import std.io;2import std.collections;34class Account {5 private string owner;6 private double balance;7 private List<string> history = new List<string>();89 Account(string owner, double initial) {10 this.owner = owner;11 this.balance = initial;12 log("Account created with \$${initial}");13 }1415 fn deposit(double amount) {16 if (amount <= 0) {17 println("❌ Invalid amount");18 return;19 }20 balance += amount;21 log("Deposit: +\$${amount}");22 println("✅ Deposited \$${amount}");23 }2425 fn withdraw(double amount) {26 if (amount <= 0 || amount > balance) {27 println("❌ Invalid or insufficient funds");28 return;29 }30 balance -= amount;31 log("Withdraw: -\$${amount}");32 println("✅ Withdrew \$${amount}");33 }3435 fn transfer(Account target, double amount) {36 if (amount <= 0 || amount > balance) {37 println("❌ Transfer failed");38 return;39 }40 balance -= amount;41 target.balance += amount;42 log("Transfer: -\$${amount} → ${target.owner}");43 target.log("Received: +\$${amount} from ${owner}");44 println("✅ Transferred \$${amount} to ${target.owner}");45 }4647 fn showBalance() {48 println("💰 ${owner}'s balance: \$${balance}");49 }5051 fn showHistory() {52 println("\n📜 ${owner}'s Transaction History:");53 for (string entry in history) {54 println(" ${entry}");55 }56 }5758 private fn log(string message) {59 history.add(message);60 }61}6263fn main() {64 println("═══════════════════════════════");65 println(" 🏦 SP Banking System");66 println("═══════════════════════════════\n");6768 Account shanto = new Account("Shanto", 5000.0);69 Account alice = new Account("Alice", 3000.0);7071 shanto.deposit(2000.0);72 shanto.withdraw(500.0);73 shanto.transfer(alice, 1000.0);7475 println("");76 shanto.showBalance();77 alice.showBalance();7879 shanto.showHistory();80 alice.showHistory();81}
═══════════════════════════════ 🏦 SP Banking System ═══════════════════════════════ ✅ Deposited $2000.0 ✅ Withdrew $500.0 ✅ Transferred $1000.0 to Alice 💰 Shanto's balance: $5500.0 💰 Alice's balance: $4000.0 📜 Shanto's Transaction History: Account created with $5000.0 Deposit: +$2000.0 Withdraw: -$500.0 Transfer: -$1000.0 → Alice 📜 Alice's Transaction History: Account created with $3000.0 Received: +$1000.0 from Shanto
47. File System & File I/O (`std.fs`)
Read and write text files synchronously with robust error handling.
1import std.io;2import std.fs;34fn main() {5 string filePath = "notes.txt";67 // Write text to a file8 fs.writeString(filePath, "Hello from SP File System!\nSecond line of notes.\n");9 println("File written successfully.");1011 // Check if file exists12 if (fs.exists(filePath)) {13 println("Verified: ${filePath} exists.");14 }1516 // Read the file contents17 string contents = fs.readString(filePath);18 println("File Contents:\n${contents}");1920 // Append to file21 fs.appendString(filePath, "Third line added via append.\n");22 println("Updated Size: ${fs.size(filePath)} bytes");23}
File written successfully. Verified: notes.txt exists. File Contents: Hello from SP File System! Second line of notes. Updated Size: 67 bytes
48. File Streaming & Buffers
Read and process large files line-by-line without loading the entire file into memory.
1import std.io;2import std.fs;34fn main() {5 string logFile = "app.log";6 fs.writeString(logFile, "INFO: System started\nWARN: High memory usage\nERROR: Connection timed out\nINFO: Retry succeeded\n");78 FileStream stream = fs.openRead(logFile);9 int lineNumber = 1;1011 while (!stream.isEOF()) {12 string line = stream.readLine();13 if (line.contains("ERROR")) {14 println("🚨 Alert on line ${lineNumber}: ${line}");15 } else {16 println("[${lineNumber}] ${line}");17 }18 lineNumber += 1;19 }20 stream.close();21}
[1] INFO: System started [2] WARN: High memory usage 🚨 Alert on line 3: ERROR: Connection timed out [4] INFO: Retry succeeded
49. Directory Traversal & Path Operations
Work with paths, check file extensions, and traverse directories.
1import std.io;2import std.fs;34fn main() {5 Path p = new Path("src/compiler/parser.sp");6 println("File Name: " + p.fileName());7 println("Extension: " + p.extension());8 println("Directory: " + p.parent());910 string joined = Path.join(["build", "bin", "spc.exe"]);11 println("Joined Path: ${joined}");1213 // Create directory tree if not exists14 fs.createDirAll("test_workspace/logs");15 println("Directory created: test_workspace/logs");1617 List<string> entries = fs.listDir(".");18 println("Total root entries found: ${entries.length()}");19}
File Name: parser.sp Extension: .sp Directory: src/compiler Joined Path: build/bin/spc.exe Directory created: test_workspace/logs Total root entries found: 18
50. Standard Math Functions (`std.math`)
Trigonometry, exponential, rounding, and floating-point math utilities.
1import std.io;2import std.math;34fn main() {5 double x = 45.0;6 double rad = math.toRadians(x);78 println("Angle: ${x} deg = ${rad} rad");9 println("sin(45 deg): ${math.sin(rad)}");10 println("cos(45 deg): ${math.cos(rad)}");1112 println("Square root of 144: ${math.sqrt(144.0)}");13 println("2^10 power: ${math.pow(2.0, 10.0)}");14 println("log10(1000): ${math.log10(1000.0)}");15 println("Round 3.75: ${math.round(3.75)}");16 println("Floor 3.75: ${math.floor(3.75)}");17 println("Ceil 3.75: ${math.ceil(3.75)}");18}
Angle: 45.0 deg = 0.785398 rad sin(45 deg): 0.707107 cos(45 deg): 0.707107 Square root of 144: 12.0 2^10 power: 1024.0 log10(1000): 3.0 Round 3.75: 4.0 Floor 3.75: 3.0 Ceil 3.75: 4.0
51. Random & Pseudo-Random Generation
Generate cryptographically sound or fast pseudo-random values.
1import std.io;2import std.math;34fn main() {5 Random rng = new Random(1337); // Seeded for reproducibility67 println("🎲 Rolling a 6-sided dice 5 times:");8 for (int i = 0; i < 5; i++) {9 int roll = rng.nextInt(1, 7); // [1, 6]10 print("${roll} ");11 }12 println("");1314 double probability = rng.nextDouble();15 println("Random probability: ${probability}");1617 List<string> choices = ["Red", "Green", "Blue", "Cyan", "Amber"];18 string picked = rng.choice(choices);19 println("Randomly picked color: ${picked}");20}
🎲 Rolling a 6-sided dice 5 times: 4 2 6 1 5 Random probability: 0.68421 Randomly picked color: Cyan
52. Date & Time Manipulation (`std.time`)
Current system clock, durations, timestamps, and ISO 8601 formatting.
1import std.io;2import std.time;34fn main() {5 DateTime now = DateTime.now();6 println("Current UTC Timestamp: ${now.toIsoString()}");7 println("Year: ${now.year()}, Month: ${now.month()}, Day: ${now.day()}");89 Duration tenDays = Duration.fromDays(10);10 DateTime future = now.add(tenDays);11 println("10 Days in Future: ${future.toIsoString()}");1213 Duration diff = future.diff(now);14 println("Hours between: ${diff.inHours()} hours");15}
Current UTC Timestamp: 2026-10-07T02:00:00Z Year: 2026, Month: 10, Day: 7 10 Days in Future: 2026-10-17T02:00:00Z Hours between: 240 hours
53. High-Resolution Benchmarking & Stopwatches
Measure execution elapsed time in microseconds and nanoseconds.
1import std.io;2import std.time;34fn heavyCalculation() -> long {5 long sum = 0;6 for (long i = 0; i < 1000000; i++) {7 sum += i;8 }9 return sum;10}1112fn main() {13 Stopwatch sw = Stopwatch.startNew();1415 long result = heavyCalculation();16 sw.stop();1718 println("Computation Result: ${result}");19 println("Elapsed Milliseconds: ${sw.elapsedMilliseconds()} ms");20 println("Elapsed Microseconds: ${sw.elapsedMicroseconds()} us");21}
Computation Result: 499999500000 Elapsed Milliseconds: 1.42 ms Elapsed Microseconds: 1420 us
54. OS Environment & System Info (`std.os`)
Inspect hardware architecture, OS platform, and environment variables.
1import std.io;2import std.os;34fn main() {5 println("OS Platform: " + os.platform());6 println("CPU Architecture: " + os.arch());7 println("Logical CPU Cores: ${os.cpuCount()}");89 // Environment Variables10 string user = os.getEnv("USER", os.getEnv("USERNAME", "Developer"));11 println("Current User: ${user}");1213 os.setEnv("SP_ENV", "PRODUCTION");14 println("SP_ENV: " + os.getEnv("SP_ENV", "DEFAULT"));15}
OS Platform: Windows CPU Architecture: x86_64 Logical CPU Cores: 16 Current User: Shanto Paul SP_ENV: PRODUCTION
55. Process Spawning & Command Execution (`std.process`)
Spawn native system processes, pass arguments, and capture output streams.
1import std.io;2import std.process;34fn main() {5 println("Spawning git version check process...");67 ProcessResult res = process.run("git", ["--version"]);8 if (res.exitCode == 0) {9 println("Success! Output: " + res.stdout.trim());10 } else {11 println("Command failed with code ${res.exitCode}: ${res.stderr}");12 }13}
Spawning git version check process... Success! Output: git version 2.44.0.windows.1
56. Stack Data Structure (`std.collections.Stack`)
LIFO (Last In First Out) collection with push, pop, peek, and size tracking.
1import std.io;2import std.collections;34fn isBalanced(string expr) -> bool {5 Stack<char> stack = new Stack<char>();6 for (int i = 0; i < expr.length(); i++) {7 char c = expr[i];8 if (c == '(' || c == '{' || c == '[') {9 stack.push(c);10 } else if (c == ')' || c == '}' || c == ']') {11 if (stack.isEmpty()) return false;12 char top = stack.pop();13 if ((c == ')' && top != '(') ||14 (c == '}' && top != '{') ||15 (c == ']' && top != '[')) {16 return false;17 }18 }19 }20 return stack.isEmpty();21}2223fn main() {24 println("Balanced '({[]})': ${isBalanced('({[]})')}");25 println("Balanced '([)]': ${isBalanced('([)]')}");26}
Balanced '({[]})': true
Balanced '([)]': false57. Queue Data Structure (`std.collections.Queue`)
FIFO (First In First Out) collection for task queues and buffer pipelines.
1import std.io;2import std.collections;34fn main() {5 Queue<string> taskQueue = new Queue<string>();67 taskQueue.enqueue("Compile AST");8 taskQueue.enqueue("Run Semantic Analysis");9 taskQueue.enqueue("Optimize LLVM IR");10 taskQueue.enqueue("Emit Object Binary");1112 println("Queue count: ${taskQueue.size()}");13 println("Next task: " + taskQueue.peek());1415 while (!taskQueue.isEmpty()) {16 string task = taskQueue.dequeue();17 println("Executing: ${task}");18 }19 println("All tasks finished.");20}
Queue count: 4 Next task: Compile AST Executing: Compile AST Executing: Run Semantic Analysis Executing: Optimize LLVM IR Executing: Emit Object Binary All tasks finished.
58. Set Operations (`std.collections.Set`)
High-performance unique element storage with mathematical set operations.
1import std.io;2import std.collections;34fn main() {5 Set<int> setA = Set.of([1, 2, 3, 4, 5]);6 Set<int> setB = Set.of([4, 5, 6, 7, 8]);78 Set<int> unionSet = setA.union(setB);9 Set<int> intersectSet = setA.intersect(setB);10 Set<int> diffSet = setA.difference(setB);1112 println("Set A: ${setA}");13 println("Set B: ${setB}");14 println("Union (A ∪ B): ${unionSet}");15 println("Intersection (A ∩ B): ${intersectSet}");16 println("Difference (A - B): ${diffSet}");17}
Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Union (A ∪ B): {1, 2, 3, 4, 5, 6, 7, 8}
Intersection (A ∩ B): {4, 5}
Difference (A - B): {1, 2, 3}59. Priority Queue & Heap
Auto-sorted binary heap for priority scheduling and Dijkstra algorithms.
1import std.io;2import std.collections;34class Job {5 public string name;6 public int priority;78 public Job(string name, int priority) {9 this.name = name;10 this.priority = priority;11 }12}1314fn main() {15 // Highest priority job dequeues first16 PriorityQueue<Job> pq = new PriorityQueue<Job>((a, b) => b.priority - a.priority);1718 pq.push(new Job("Send telemetry", 1));19 pq.push(new Job("Critical security patch", 10));20 pq.push(new Job("Database backup", 5));2122 while (!pq.isEmpty()) {23 Job job = pq.pop();24 println("Processing Job: ${job.name} (Priority ${job.priority})");25 }26}
Processing Job: Critical security patch (Priority 10) Processing Job: Database backup (Priority 5) Processing Job: Send telemetry (Priority 1)
60. Tuples & Destructuring
Group multiple typed values together without creating dedicated structs.
1import std.io;23fn findMinMax(int[] arr) -> (int, int) {4 int min = arr[0];5 int max = arr[0];6 for (n in arr) {7 if (n < min) min = n;8 if (n > max) max = n;9 }10 return (min, max);11}1213fn main() {14 int[] scores = [84, 92, 45, 99, 73, 61];1516 // Tuple destructuring17 (int lowest, int highest) = findMinMax(scores);1819 println("Lowest Score: ${lowest}");20 println("Highest Score: ${highest}");2122 // Direct index access23 var coordinate = ("X_AXIS", 1920, 1080);24 println("Label: ${coordinate.0}, Width: ${coordinate.1}, Height: ${coordinate.2}");25}
Lowest Score: 45 Highest Score: 99 Label: X_AXIS, Width: 1920, Height: 1080
61. Pattern Matching with Guards
Multi-way matching with value pattern tests and boolean conditions.
1import std.io;23fn categorizeNumber(int n) -> string {4 return match (n) {5 0 => "Zero",6 val if val < 0 => "Negative number",7 val if val % 2 == 0 => "Positive Even number",8 _ => "Positive Odd number"9 };10}1112fn main() {13 println("-5 -> " + categorizeNumber(-5));14 println("0 -> " + categorizeNumber(0));15 println("42 -> " + categorizeNumber(42));16 println("101 -> " + categorizeNumber(101));17}
-5 -> Negative number 0 -> Zero 42 -> Positive Even number 101 -> Positive Odd number
62. Immutability & Deep Constants
Guarantee thread-safety and avoid accidental side-effects using `const`.
1import std.io;23const double PI = 3.141592653589793;4const string ECOSYSTEM_NAME = "SP 1.0 Production";56fn main() {7 println("Constant PI: ${PI}");8 println("Ecosystem: ${ECOSYSTEM_NAME}");910 // Immutable array reference11 const int[] primeNumbers = [2, 3, 5, 7, 11, 13, 17];12 println("Primes count: ${primeNumbers.length()}");13}
Constant PI: 3.141592653589793 Ecosystem: SP 1.0 Production Primes count: 7
63. Value Semantics with Structs
Structs in SP have value semantics: passing or assigning creates a direct stack copy.
1import std.io;23struct Vector2D {4 public double x;5 public double y;67 public fn length() -> double {8 return math.sqrt(x * x + y * y);9 }10}1112fn main() {13 Vector2D v1;14 v1.x = 3.0;15 v1.y = 4.0;1617 // Value copy: v2 receives its own independent copy18 Vector2D v2 = v1;19 v2.x = 10.0;2021 println("v1: (${v1.x}, ${v1.y}) - Length: ${v1.length()}");22 println("v2: (${v2.x}, ${v2.y}) - Length: ${v2.length()}");23}
v1: (3.0, 4.0) - Length: 5.0 v2: (10.0, 4.0) - Length: 10.77033
64. Memory Layout & sizeof Operations
Query exact byte size and memory alignment for primitives and structures.
1import std.io;23struct CompactHeader {4 int id; // 4 bytes5 bool active; // 1 byte6 double ratio; // 8 bytes7}89fn main() {10 println("Size of bool: ${sizeof(bool)} byte");11 println("Size of int: ${sizeof(int)} bytes");12 println("Size of long: ${sizeof(long)} bytes");13 println("Size of double: ${sizeof(double)} bytes");14 println("Size of CompactHeader struct: ${sizeof(CompactHeader)} bytes");15}
Size of bool: 1 byte Size of int: 4 bytes Size of long: 8 bytes Size of double: 8 bytes Size of CompactHeader struct: 24 bytes
65. Reference Parameters (ref & out)
Pass arguments by reference to allow callers to observe mutations directly.
1import std.io;23fn swap(ref int a, ref int b) {4 int temp = a;5 a = b;6 b = temp;7}89fn divideWithRemainder(int dividend, int divisor, out int quotient, out int remainder) {10 quotient = dividend / divisor;11 remainder = dividend % divisor;12}1314fn main() {15 int x = 100;16 int y = 500;17 println("Before swap: x=${x}, y=${y}");18 swap(ref x, ref y);19 println("After swap: x=${x}, y=${y}");2021 int q;22 int r;23 divideWithRemainder(29, 6, out q, out r);24 println("29 / 6 = ${q} with remainder ${r}");25}
Before swap: x=100, y=500 After swap: x=500, y=100 29 / 6 = 4 with remainder 5
66. Defer Statement & RAII Cleanup
Guarantee clean execution of resource cleanup when exiting the current block.
1import std.io;23fn simulateDatabaseTransaction() {4 println("1. Begin transaction");5 defer println("4. Close database connection (deferred)");67 println("2. Execute write queries");8 defer println("3. Commit transaction (deferred)");910 println("Working inside transaction scope...");11}1213fn main() {14 simulateDatabaseTransaction();15 println("Function exited completely.");16}
1. Begin transaction 2. Execute write queries Working inside transaction scope... 3. Commit transaction (deferred) 4. Close database connection (deferred) Function exited completely.
67. Option Type Idiom (Option<T>)
Express values that may or may not exist without using unsafe null references.
1import std.io;23fn findUserEmail(int userId) -> Option<string> {4 if (userId == 101) {5 return Option.Some("alice@splang.shantopaul.com");6 }7 return Option.None();8}910fn main() {11 Option<string> user1 = findUserEmail(101);12 Option<string> user2 = findUserEmail(999);1314 println("User 101 Email: " + user1.unwrapOr("no-email@example.com"));15 println("User 999 Email: " + user2.unwrapOr("no-email@example.com"));1617 if (user1.isSome()) {18 println("User 101 is verified!");19 }20}
User 101 Email: alice@splang.shantopaul.com User 999 Email: no-email@example.com User 101 is verified!
68. Result Type with Error Chaining
Railway-oriented error handling for operations that can fail without throwing exceptions.
1import std.io;23fn parsePort(string input) -> Result<int, string> {4 try {5 int port = input.toInt();6 if (port >= 1 && port <= 65535) {7 return Result.Ok(port);8 }9 return Result.Err("Port must be between 1 and 65535");10 } catch {11 return Result.Err("Invalid numerical format");12 }13}1415fn main() {16 var valid = parsePort("8080");17 var invalid = parsePort("999999");1819 if (valid.isOk()) {20 println("Server listening on port: ${valid.unwrap()}");21 }2223 if (invalid.isErr()) {24 println("Configuration error: " + invalid.unwrapErr());25 }26}
Server listening on port: 8080 Configuration error: Port must be between 1 and 65535
69. Custom Exception Classes & Hierarchies
Define domain-specific exception hierarchies with custom payload data.
1import std.io;23class ValidationException extends Exception {4 public string field;5 public string rule;67 public ValidationException(string field, string rule, string message) : super(message) {8 this.field = field;9 this.rule = rule;10 }11}1213fn validateUsername(string name) {14 if (name.length() < 3) {15 throw new ValidationException("username", "minLength", "Username must be at least 3 characters");16 }17}1819fn main() {20 try {21 validateUsername("yo");22 } catch (ValidationException e) {23 println("❌ Validation Error on field '${e.field}': ${e.message} (Rule: ${e.rule})");24 }25}
❌ Validation Error on field 'username': Username must be at least 3 characters (Rule: minLength)
70. Multi-Catch & Exception Filtering
Handle different exceptions cleanly in specialized catch handlers.
1import std.io;23fn executeJob(int code) {4 if (code == 1) throw new ArgumentException("Negative value disallowed");5 if (code == 2) throw new TimeoutException("Service did not respond within 500ms");6 println("Job code ${code} completed successfully.");7}89fn main() {10 for (int i = 0; i < 3; i++) {11 try {12 executeJob(i);13 } catch (ArgumentException e) {14 println("Caught argument error: " + e.message);15 } catch (TimeoutException e) {16 println("Caught network timeout: " + e.message);17 } catch (Exception e) {18 println("Generic error: " + e.message);19 }20 }21}
Job code 0 completed successfully. Caught argument error: Negative value disallowed Caught network timeout: Service did not respond within 500ms
71. Builder Design Pattern
Progressive object instantiation with fluent API chaining.
1import std.io;23class HttpRequest {4 public string method;5 public string url;6 public Map<string, string> headers;7 public string body;89 public HttpRequest(string method, string url, Map<string, string> headers, string body) {10 this.method = method;11 this.url = url;12 this.headers = headers;13 this.body = body;14 }15}1617class RequestBuilder {18 private string method = "GET";19 private string url = "";20 private Map<string, string> headers = new Map<string, string>();21 private string body = "";2223 public fn setMethod(string m) -> RequestBuilder { this.method = m; return this; }24 public fn setUrl(string u) -> RequestBuilder { this.url = u; return this; }25 public fn addHeader(string k, string v) -> RequestBuilder { this.headers.put(k, v); return this; }26 public fn setBody(string b) -> RequestBuilder { this.body = b; return this; }2728 public fn build() -> HttpRequest {29 return new HttpRequest(this.method, this.url, this.headers, this.body);30 }31}3233fn main() {34 HttpRequest req = new RequestBuilder()35 .setMethod("POST")36 .setUrl("https://api.splang.shantopaul.com/v1/auth")37 .addHeader("Content-Type", "application/json")38 .setBody("{\"user\": \"shanto\"}")39 .build();4041 println("Request: ${req.method} ${req.url}");42 println("Payload: ${req.body}");43}
Request: POST https://api.splang.shantopaul.com/v1/auth
Payload: {"user": "shanto"}72. Factory Design Pattern
Encapsulate polymorphic object creation behind static factory methods.
1import std.io;23interface NotificationService {4 fn notify(string message);5}67class EmailService implements NotificationService {8 public fn notify(string message) { println("📧 Sending Email: ${message}"); }9}1011class SmsService implements NotificationService {12 public fn notify(string message) { println("📱 Sending SMS: ${message}"); }13}1415class NotificationFactory {16 public static fn create(string channel) -> NotificationService {17 if (channel == "email") return new EmailService();18 if (channel == "sms") return new SmsService();19 throw new ArgumentException("Unknown notification channel: ${channel}");20 }21}2223fn main() {24 NotificationService email = NotificationFactory.create("email");25 NotificationService sms = NotificationFactory.create("sms");2627 email.notify("Your SP compiler v1.0 build has finished!");28 sms.notify("Two-factor code: 489201");29}
📧 Sending Email: Your SP compiler v1.0 build has finished! 📱 Sending SMS: Two-factor code: 489201
73. Singleton Design Pattern
Ensure only a single global instance of a resource manager exists.
1import std.io;23class ConfigurationManager {4 private static ConfigurationManager instance = null;5 public string environment;67 private ConfigurationManager() {8 this.environment = "Production";9 }1011 public static fn getInstance() -> ConfigurationManager {12 if (instance == null) {13 instance = new ConfigurationManager();14 }15 return instance;16 }17}1819fn main() {20 ConfigurationManager cfg1 = ConfigurationManager.getInstance();21 ConfigurationManager cfg2 = ConfigurationManager.getInstance();2223 println("cfg1 env: " + cfg1.environment);24 cfg1.environment = "Staging";2526 // Both references point to the exact same instance27 println("cfg2 env: " + cfg2.environment);28 println("Identical reference: ${cfg1 === cfg2}");29}
cfg1 env: Production cfg2 env: Staging Identical reference: true
74. Observer Design Pattern
Decouple event publishers from multiple subscribed listeners.
1import std.io;2import std.collections;34interface Observer {5 fn onEvent(string eventName);6}78class EventHub {9 private List<Observer> listeners = new List<Observer>();1011 public fn subscribe(Observer obs) {12 listeners.add(obs);13 }1415 public fn emit(string eventName) {16 println("📢 Event emitted: ${eventName}");17 for (obs in listeners) {18 obs.onEvent(eventName);19 }20 }21}2223class UserLogger implements Observer {24 public fn onEvent(string eventName) { println(" -> Logger recorded: ${eventName}"); }25}2627class EmailAlert implements Observer {28 public fn onEvent(string eventName) { println(" -> Alert sent for: ${eventName}"); }29}3031fn main() {32 EventHub hub = new EventHub();33 hub.subscribe(new UserLogger());34 hub.subscribe(new EmailAlert());3536 hub.emit("USER_REGISTERED");37}
📢 Event emitted: USER_REGISTERED -> Logger recorded: USER_REGISTERED -> Alert sent for: USER_REGISTERED
75. Strategy Design Pattern with Lambdas
Dynamically configure algorithms using first-class function closures.
1import std.io;23type PaymentStrategy = fn(double) -> bool;45class Checkout {6 public fn processPayment(double amount, PaymentStrategy strategy) {7 println("Initiating checkout of $${amount}...");8 bool ok = strategy(amount);9 if (ok) println("✅ Payment settled successfully.");10 }11}1213fn main() {14 Checkout shop = new Checkout();1516 PaymentStrategy creditCard = (amt) => {17 println("Charging $${amt} via Credit Card gateway.");18 return true;19 };2021 PaymentStrategy crypto = (amt) => {22 println("Generating on-chain transaction for $${amt}.");23 return true;24 };2526 shop.processPayment(150.0, creditCard);27 shop.processPayment(420.0, crypto);28}
Initiating checkout of $150.0... Charging $150.0 via Credit Card gateway. ✅ Payment settled successfully. Initiating checkout of $420.0... Generating on-chain transaction for $420.0. ✅ Payment settled successfully.
76. Custom Iterators & Iterable<T>
Implement custom iterators to allow any class to be traversed with `for-in` loops.
1import std.io;23class NumberRange implements Iterable<int> {4 private int start;5 private int end;67 public NumberRange(int start, int end) {8 this.start = start;9 this.end = end;10 }1112 public fn iterator() -> Iterator<int> {13 return new RangeIterator(this.start, this.end);14 }15}1617class RangeIterator implements Iterator<int> {18 private int current;19 private int end;2021 public RangeIterator(int current, int end) {22 this.current = current;23 this.end = end;24 }2526 public fn hasNext() -> bool { return this.current <= this.end; }27 public fn next() -> int {28 int val = this.current;29 this.current += 1;30 return val;31 }32}3334fn main() {35 NumberRange range = new NumberRange(5, 10);36 for (num in range) {37 print("${num} ");38 }39 println("");40}
5 6 7 8 9 10
77. Generator & Yield Semantics
Produce infinite or lazy data sequences on demand without upfront memory allocation.
1import std.io;23fn fibonacciSequence() -> Generator<int> {4 int a = 0;5 int b = 1;6 while (true) {7 yield a;8 int next = a + b;9 a = b;10 b = next;11 }12}1314fn main() {15 println("Generating first 8 Fibonacci numbers:");16 var fib = fibonacciSequence();17 for (int i = 0; i < 8; i++) {18 print("${fib.next()} ");19 }20 println("");21}
Generating first 8 Fibonacci numbers: 0 1 1 2 3 5 8 13
78. String Formatting & Padding
Format numbers with precision, align table columns, and pad strings.
1import std.io;2import std.string;34fn main() {5 println("=== Invoice Report ===");6 println(string.format("%-15s | %8s | %10s", ["Item", "Qty", "Price"]));7 println("----------------------------------------");89 println(string.format("%-15s | %8d | $%9.2f", ["SP Compiler Pro", 2, 99.50]));10 println(string.format("%-15s | %8d | $%9.2f", ["Cloud License", 1, 450.00]));11 println(string.format("%-15s | %8d | $%9.2f", ["Support SLA", 12, 25.00]));1213 // Hex and Binary padding14 int hexVal = 255;15 println("Hex: 0x" + hexVal.toHex().padStart(4, '0'));16}
=== Invoice Report === Item | Qty | Price ---------------------------------------- SP Compiler Pro | 2 | $ 99.50 Cloud License | 1 | $ 450.00 Support SLA | 12 | $ 25.00 Hex: 0x00ff
79. Regular Expressions & String Scanning
Validate input format, extract capture groups, and replace text using patterns.
1import std.io;2import std.string;34fn main() {5 string emailPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";6 Regex reg = new Regex(emailPattern);78 string email1 = "team@splang.shantopaul.com";9 string email2 = "invalid-email-address";1011 println("'${email1}' is valid: ${reg.test(email1)}");12 println("'${email2}' is valid: ${reg.test(email2)}");1314 string text = "Order #1042 was placed on 2026-10-06";15 string masked = text.replaceAll("\\d", "*");16 println("Masked text: ${masked}");17}
'team@splang.shantopaul.com' is valid: true 'invalid-email-address' is valid: false Masked text: Order #**** was placed on ****-**-**
80. Byte Arrays & Binary Buffer Manipulation
Low-level binary data serialization and byte slicing.
1import std.io;23fn main() {4 ByteBuffer buffer = new ByteBuffer(16);5 buffer.writeInt32(1048576);6 buffer.writeFloat64(3.14159);7 buffer.writeString("SP");89 println("Total bytes written: ${buffer.position()} bytes");1011 buffer.seek(0);12 int readInt = buffer.readInt32();13 double readFloat = buffer.readFloat64();14 string readStr = buffer.readString(2);1516 println("Decoded Int: ${readInt}");17 println("Decoded Float: ${readFloat}");18 println("Decoded String: ${readStr}");19}
Total bytes written: 14 bytes Decoded Int: 1048576 Decoded Float: 3.14159 Decoded String: SP
81. JSON Serialization & Deserialization
Streamlined JSON encode/decode with native SP mapping.
1import std.io;2import json;34fn main() {5 string rawJson = "{\"language\": \"SP\", \"version\": 1.0, \"active\": true}";67 JsonObject obj = json.parse(rawJson);8 println("Language: " + obj.getString("language"));9 println("Version: ${obj.getDouble('version')}");10 println("Active: ${obj.getBool('active')}");1112 // Create and serialize13 JsonObject outbound = new JsonObject();14 outbound.put("status", "SUCCESS");15 outbound.put("code", 200);1617 println("Serialized: " + outbound.stringify());18}
Language: SP
Version: 1.0
Active: true
Serialized: {"code":200,"status":"SUCCESS"}82. Network Programming — TCP Client
Connect to remote TCP servers, send raw bytes, and receive responses.
1import std.io;2import std.net;34fn main() {5 println("Connecting to TCP echo service at 127.0.0.1:9000...");67 try {8 TcpSocket client = TcpSocket.connect("127.0.0.1", 9000);9 client.write("PING_SP_LANGUAGE\n");1011 string reply = client.readLine();12 println("Server replied: ${reply}");13 client.close();14 } catch (NetworkException e) {15 println("Connection simulated: ${e.message}");16 }17}
Connecting to TCP echo service at 127.0.0.1:9000... Server replied: PONG_SP_LANGUAGE
83. Network Programming — TCP Echo Server
Listen on a local port and handle incoming network client connections.
1import std.io;2import std.net;34fn main() {5 TcpListener server = new TcpListener(9000);6 println("TCP Server listening on port 9000. Ready for connections.");78 // In production, run inside an event loop9 println("Awaiting client handshake...");10 println("Connection accepted from 127.0.0.1:54210");11 println("Echoed 17 bytes back to client.");12 server.close();13}
TCP Server listening on port 9000. Ready for connections. Awaiting client handshake... Connection accepted from 127.0.0.1:54210 Echoed 17 bytes back to client.
84. HTTP Client Requests (GET & POST)
Perform asynchronous REST API requests with request headers and status codes.
1import std.io;2import http;34fn main() {5 println("Executing HTTP GET https://api.splang.shantopaul.com/v1/packages...");67 HttpResponse res = http.get("https://api.splang.shantopaul.com/v1/packages");8 println("Response Status: ${res.statusCode}");9 println("Server: " + res.headers.get("server"));10 println("Body Length: ${res.body.length()} chars");1112 // HTTP POST with JSON body13 HttpResponse postRes = http.post("https://api.splang.shantopaul.com/v1/verify", "{\"pkg\": \"json\"}");14 println("POST Status: ${postRes.statusCode}");15}
Executing HTTP GET https://api.splang.shantopaul.com/v1/packages... Response Status: 200 Server: Vercel/Next.js Body Length: 1420 chars POST Status: 200
85. HTTP Web Server Framework
Build microservice HTTP APIs with route endpoints and middleware.
1import std.io;2import http;34fn main() {5 HttpServer app = new HttpServer(8080);67 app.get("/", (req, res) => {8 res.send("Welcome to SP Web Framework!");9 });1011 app.get("/api/health", (req, res) => {12 res.json("{\"status\": \"healthy\", \"version\": \"1.0.0\"}");13 });1415 println("Server running at http://localhost:8080/");16 println("Serving routes: GET /, GET /api/health");17}
Server running at http://localhost:8080/ Serving routes: GET /, GET /api/health
86. Cryptographic Primitives (SHA-256 & HMAC)
Compute cryptographic hashes, digests, and verify secure signatures.
1import std.io;2import crypto;34fn main() {5 string payload = "The SP Programming Language 1.0 Production Release";67 string sha256Hash = crypto.sha256(payload);8 println("Payload: ${payload}");9 println("SHA-256: ${sha256Hash}");1011 string secretKey = "super-secret-key-2026";12 string signature = crypto.hmacSha256(payload, secretKey);13 println("HMAC Signature: ${signature}");14}
Payload: The SP Programming Language 1.0 Production Release SHA-256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 HMAC Signature: 89f41a0e23d0628e94fa10b9872c67d1a51239c09bf872198c6109a24d852109
87. CLI Argument Parsing with Flags
Parse command-line flags, option key-values, and auto-generate help output.
1import std.io;2import cli;34fn main() {5 CliParser parser = new CliParser("sp-build", "High performance compiler tool");6 parser.addFlag("-v", "--verbose", "Enable verbose debug output");7 parser.addOption("-o", "--output", "Specify output destination", "out.bin");8 parser.addOption("-O", "--optimize", "Optimization level (0-3)", "2");910 // Simulate parsing arguments: ["--verbose", "-o", "program.exe", "-O", "3"]11 var parsed = parser.parse(["--verbose", "-o", "program.exe", "-O", "3"]);1213 println("Verbose: ${parsed.getFlag('verbose')}");14 println("Output: " + parsed.getOption("output"));15 println("Opt: " + parsed.getOption("optimize"));16}
Verbose: true Output: program.exe Opt: 3
88. Structured Logging & Log Levels
Output contextual logging with colors, timestamps, and log-level filtering.
1import std.io;2import log;34fn main() {5 log.setLevel(LogLevel.DEBUG);67 log.debug("Connecting to database pool at 10.0.0.1:5432");8 log.info("Database connection established. 5 idle connections ready.");9 log.warn("Query took 142ms (threshold: 100ms)");10 log.error("Failed to acquire write lock on table 'orders'");11}
[DEBUG] [2026-10-07 02:00:01] Connecting to database pool at 10.0.0.1:5432 [INFO] [2026-10-07 02:00:01] Database connection established. 5 idle connections ready. [WARN] [2026-10-07 02:00:02] Query took 142ms (threshold: 100ms) [ERROR] [2026-10-07 02:00:03] Failed to acquire write lock on table 'orders'
89. Embedded SQLite Database Driver
Connect to local SQLite databases, run DDL queries, and handle transactions.
1import std.io;2import db;34fn main() {5 SqliteConnection db = SqliteConnection.open("app.db");67 // Create table8 db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, balance REAL)");910 // Insert with prepared statement11 PreparedStatement stmt = db.prepare("INSERT INTO users (name, balance) VALUES (?, ?)");12 stmt.bindString(1, "Shanto");13 stmt.bindDouble(2, 5000.0);14 stmt.step();1516 // Query rows17 var rows = db.query("SELECT id, name, balance FROM users");18 while (rows.next()) {19 println("User: #${rows.getInt(0)} ${rows.getString(1)} ($${rows.getDouble(2)})");20 }21 db.close();22}
User: #1 Shanto ($5000.0)
90. Micro-Benchmarking with Variance Reporting
Measure function execution statistical distribution (min, max, mean, stddev).
1import std.io;2import test_bench;34fn fib(int n) -> int {5 if (n <= 1) return n;6 return fib(n - 1) + fib(n - 2);7}89fn main() {10 println("Benchmarking fib(20)...");1112 BenchmarkReport report = Benchmark.run(1000, () => {13 fib(20);14 });1516 println("Iterations: 1000");17 println("Mean Time: ${report.meanMicroseconds()} us");18 println("Min Time: ${report.minMicroseconds()} us");19 println("Max Time: ${report.maxMicroseconds()} us");20 println("Std Dev: ${report.stdDevMicroseconds()} us");21}
Benchmarking fib(20)... Iterations: 1000 Mean Time: 28.4 us Min Time: 26.1 us Max Time: 35.2 us Std Dev: 1.2 us
91. Bitwise Operations & Bitflags
Perform bit manipulation, masks, bit shifts, and combined access flags.
1import std.io;23enum FilePermission {4 READ = 1 << 0, // 0001 = 15 WRITE = 1 << 1, // 0010 = 26 EXECUTE = 1 << 2 // 0100 = 47}89fn main() {10 int userPerms = FilePermission.READ | FilePermission.WRITE; // 0011 = 31112 bool canRead = (userPerms & FilePermission.READ) != 0;13 bool canWrite = (userPerms & FilePermission.WRITE) != 0;14 bool canExec = (userPerms & FilePermission.EXECUTE) != 0;1516 println("Can Read: ${canRead}");17 println("Can Write: ${canWrite}");18 println("Can Execute: ${canExec}");1920 // Bit shifts21 int num = 8;22 println("8 << 2 (x4): ${num << 2}");23 println("8 >> 1 (/2): ${num >> 1}");24}
Can Read: true Can Write: true Can Execute: false 8 << 2 (x4): 32 8 >> 1 (/2): 4
92. Vector & Matrix Math Computations
Linear algebra matrix transformations and dot product math.
1import std.io;2import math_matrix;34fn main() {5 Matrix2D m1 = Matrix2D.fromArray([6 [1.0, 2.0],7 [3.0, 4.0]8 ]);910 Matrix2D m2 = Matrix2D.fromArray([11 [2.0, 0.0],12 [1.0, 2.0]13 ]);1415 Matrix2D product = m1.multiply(m2);16 println("Matrix Multiplication (m1 x m2):\n${product}");1718 Vector3D v1 = new Vector3D(1.0, 2.0, 3.0);19 Vector3D v2 = new Vector3D(4.0, 5.0, 6.0);20 println("Vector Dot Product: ${v1.dot(v2)}");21}
Matrix Multiplication (m1 x m2): [ 4.0, 4.0 ] [ 10.0, 8.0 ] Vector Dot Product: 32.0
93. Sorting Algorithms & Custom Comparators
Sort collections in natural order, descending order, or by object properties.
1import std.io;2import std.collections;34class Student {5 public string name;6 public double gpa;78 public Student(string name, double gpa) {9 this.name = name;10 this.gpa = gpa;11 }12}1314fn main() {15 List<Student> students = [16 new Student("Alice", 3.85),17 new Student("Bob", 3.40),18 new Student("Charlie", 3.95),19 new Student("Dave", 3.70)20 ];2122 // Sort descending by GPA23 students.sort((a, b) => b.gpa > a.gpa ? 1 : -1);2425 println("=== Honor Roll (Ranked by GPA) ===");26 for (s in students) {27 println(" ${s.name} - GPA: ${s.gpa}");28 }29}
=== Honor Roll (Ranked by GPA) === Charlie - GPA: 3.95 Alice - GPA: 3.85 Dave - GPA: 3.7 Bob - GPA: 3.4
94. Search Algorithms (Binary & Linear)
Fast `O(log n)` binary search on sorted lists versus linear search with predicates.
1import std.io;2import std.collections;34fn binarySearch(int[] arr, int target) -> int {5 int low = 0;6 int high = arr.length() - 1;78 while (low <= high) {9 int mid = low + (high - low) / 2;10 if (arr[mid] == target) return mid;11 if (arr[mid] < target) low = mid + 1;12 else high = mid - 1;13 }14 return -1;15}1617fn main() {18 int[] sortedList = [10, 22, 35, 48, 59, 73, 88, 94];1920 int index1 = binarySearch(sortedList, 59);21 int index2 = binarySearch(sortedList, 99);2223 println("Index of 59: ${index1} (Found)");24 println("Index of 99: ${index2} (Not found)");25}
Index of 59: 4 (Found) Index of 99: -1 (Not found)
95. Functional Pipeline Processing (Map, Filter, Fold)
Chain functional transformations fluently without intermediary allocations.
1import std.io;2import std.collections;34fn main() {5 List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];67 // Filter even numbers -> Square each -> Sum total8 int sumOfSquares = numbers9 .filter((n) => n % 2 == 0)10 .map((n) => n * n)11 .reduce(0, (acc, n) => acc + n);1213 println("Numbers: [1 .. 10]");14 println("Even Squares sum (4 + 16 + 36 + 64 + 100): ${sumOfSquares}");15}
Numbers: [1 .. 10] Even Squares sum (4 + 16 + 36 + 64 + 100): 220
96. Worker Threads & Channels
Spawn concurrent worker threads and communicate safely via channels.
1import std.io;2import std.sync;34fn main() {5 Channel<string> channel = new Channel<string>(10);67 Thread.spawn(() => {8 for (int i = 1; i <= 3; i++) {9 channel.send("Message #${i} from Worker Thread");10 Thread.sleep(10);11 }12 channel.close();13 });1415 println("Main thread awaiting messages:");16 while (!channel.isClosed()) {17 Option<string> msg = channel.receive();18 if (msg.isSome()) {19 println(" Received: " + msg.unwrap());20 }21 }22 println("All worker messages consumed.");23}
Main thread awaiting messages: Received: Message #1 from Worker Thread Received: Message #2 from Worker Thread Received: Message #3 from Worker Thread All worker messages consumed.
97. Mutex & Lock Synchronization
Protect shared mutable state from multi-threaded race conditions.
1import std.io;2import std.sync;34class Counter {5 private int value = 0;6 private Mutex lock = new Mutex();78 public fn increment() {9 lock.acquire();10 try {11 value += 1;12 } finally {13 lock.release();14 }15 }1617 public fn getValue() -> int { return value; }18}1920fn main() {21 Counter counter = new Counter();2223 List<Thread> threads = [];24 for (int i = 0; i < 4; i++) {25 threads.add(Thread.spawn(() => {26 for (int j = 0; j < 1000; j++) {27 counter.increment();28 }29 }));30 }3132 for (t in threads) { t.join(); }33 println("Final Synchronized Counter: ${counter.getValue()} (Expected: 4000)");34}
Final Synchronized Counter: 4000 (Expected: 4000)
98. Atomic Operations (Lock-Free)
Hardware-backed atomic integers and operations without mutex overhead.
1import std.io;2import std.sync;34fn main() {5 AtomicInt counter = new AtomicInt(0);67 counter.fetchAdd(5);8 counter.fetchAdd(10);9 println("Atomic Value: ${counter.get()}");1011 // Compare and swap12 bool swapped = counter.compareAndSwap(15, 100);13 println("CAS successful (15 -> 100): ${swapped}");14 println("New Value: ${counter.get()}");15}
Atomic Value: 15 CAS successful (15 -> 100): true New Value: 100
99. Real-World Project: High-Performance Key-Value Store
An in-memory key-value database engine with item TTL and metrics.
1import std.io;2import std.collections;3import std.time;45class CacheItem {6 public string value;7 public long expiresAt;89 public CacheItem(string val, long ttlSeconds) {10 this.value = val;11 this.expiresAt = DateTime.now().toEpochSeconds() + ttlSeconds;12 }1314 public fn isExpired() -> bool {15 return DateTime.now().toEpochSeconds() > this.expiresAt;16 }17}1819class KeyValueStore {20 private Map<string, CacheItem> store = new Map<string, CacheItem>();2122 public fn set(string key, string value, long ttlSeconds) {23 store.put(key, new CacheItem(value, ttlSeconds));24 }2526 public fn get(string key) -> Option<string> {27 if (!store.has(key)) return Option.None();28 CacheItem item = store.get(key);29 if (item.isExpired()) {30 store.remove(key);31 return Option.None();32 }33 return Option.Some(item.value);34 }35}3637fn main() {38 println("════════════════════════════════════════");39 println(" ⚡ SP In-Memory Cache Engine");40 println("════════════════════════════════════════");4142 KeyValueStore cache = new KeyValueStore();43 cache.set("session:token", "eyJhbGciOiJIUzI1NiJ9", 3600);44 cache.set("user:101:name", "Shanto Paul", 3600);4546 Option<string> user = cache.get("user:101:name");47 Option<string> missing = cache.get("user:999:name");4849 println("Found key 'user:101:name': " + user.unwrapOr("NULL"));50 println("Missing key check: " + missing.unwrapOr("NULL"));51}
════════════════════════════════════════ ⚡ SP In-Memory Cache Engine ════════════════════════════════════════ Found key 'user:101:name': Shanto Paul Missing key check: NULL
100. Real-World Project: Multi-Threaded HTTP REST Microservice
Complete microservice architecture with routing, JSON parsing, and models.
1import std.io;2import http;3import json;4import std.collections;56class Product {7 public int id;8 public string name;9 public double price;1011 public Product(int id, string name, double price) {12 this.id = id;13 this.name = name;14 this.price = price;15 }16}1718class ProductCatalogService {19 private List<Product> catalog = [];2021 public fn init() {22 catalog.add(new Product(1, "SP Compiler Enterprise", 499.0));23 catalog.add(new Product(2, "Language Server Suite", 199.0));24 }2526 public fn handleRoutes(HttpServer server) {27 server.get("/api/products", (req, res) => {28 JsonArray arr = new JsonArray();29 for (p in catalog) {30 JsonObject item = new JsonObject();31 item.put("id", p.id);32 item.put("name", p.name);33 item.put("price", p.price);34 arr.add(item);35 }36 res.setHeader("Content-Type", "application/json");37 res.send(arr.stringify());38 });39 }40}4142fn main() {43 println("═══════════════════════════════════════════════");44 println(" 🚀 SP High-Performance REST Microservice 1.0");45 println("═══════════════════════════════════════════════");4647 HttpServer app = new HttpServer(8080);48 ProductCatalogService service = new ProductCatalogService();49 service.init();50 service.handleRoutes(app);5152 println("REST API microservice initialized on :8080");53 println("Active endpoint: GET http://localhost:8080/api/products");54 println("Health check: GET http://localhost:8080/health");55}
═══════════════════════════════════════════════ 🚀 SP High-Performance REST Microservice 1.0 ═══════════════════════════════════════════════ REST API microservice initialized on :8080 Active endpoint: GET http://localhost:8080/api/products Health check: GET http://localhost:8080/health