Complete 100 ExamplesSP Language v1.0

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.

Total Examples

100

Categories

10 Groups

Toolchain

spc v1.0.0

Compiled Outputs

Verified

Showing 100 of 100 examples
#1Basics & Fundamentals

1. Hello World

#example-1

The simplest SP program:

ex_01.sp
1fn main() {
2 println("Hello, SP!");
3}
Expected Terminal Outputspc run ex_01.sp
Hello, SP!
#2Basics & Fundamentals

2. Variables & Constants

#example-2

Examples and idioms for Variables & Constants, starting with mutable variables.

Mutable Variables

ex_02_1.sp
1fn main() {
2 // Explicit types
3 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';
9
10 println("Name: ${name}");
11 println("Age: ${age}");
12 println("Salary: ${salary}");
13 println("Score: ${score}");
14 println("Active: ${isActive}");
15 println("Grade: ${grade}");
16
17 // Variables can be reassigned
18 age = 22;
19 name = "Shanto Paul";
20 println("Updated: ${name}, age ${age}");
21}
Expected Terminal Outputspc run ex_02_1.sp
Name: Shanto
Age: 21
Salary: 75000.5
Score: 95.5
Active: true
Grade: A
Updated: Shanto Paul, age 22

Constants (Immutable)

ex_02_2.sp
1fn main() {
2 const int MAX_USERS = 1000;
3 const double TAX_RATE = 0.15;
4 const string APP_NAME = "MyApp";
5
6 println("App: ${APP_NAME}");
7 println("Max Users: ${MAX_USERS}");
8 println("Tax Rate: ${TAX_RATE}");
9
10 // ❌ This will NOT compile:
11 // MAX_USERS = 2000; // error: cannot assign to constant
12}
#3Basics & Fundamentals

3. Data Types

#example-3

Examples and idioms for Data Types, starting with all primitive types.

All Primitive Types

ex_03.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // INTEGER TYPES
4 // ═══════════════════════════════════════
5
6 int number = 42; // Platform default (32 or 64 bit)
7 uint positive = 100; // Unsigned integer
8
9 int8 tiny = 127; // -128 to 127
10 int16 small = 32000; // -32768 to 32767
11 int32 medium = 2147483647; // Standard 32-bit
12 int64 large = 9223372036854; // 64-bit
13
14 uint8 uTiny = 255; // 0 to 255
15 uint16 uSmall = 65535; // 0 to 65535
16 uint32 uMedium = 4294967295; // 0 to 4,294,967,295
17 uint64 uLarge = 18446744073; // 0 to 18,446,744,073,709,551,615
18
19 // ═══════════════════════════════════════
20 // FLOATING POINT TYPES
21 // ═══════════════════════════════════════
22
23 float price = 29.99; // 32-bit floating point
24 double precise = 3.141592653589793; // 64-bit floating point
25
26 // ═══════════════════════════════════════
27 // OTHER TYPES
28 // ═══════════════════════════════════════
29
30 bool alive = true; // true or false
31 bool dead = false;
32
33 char letter = 'A'; // Single character
34 char symbol = '@';
35 char newline = '\n';
36
37 string text = "Hello, SP!"; // String of characters
38 string empty = "";
39
40 byte raw = 0xFF; // Raw byte (0-255)
41
42 // Print all
43 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}
Expected Terminal Outputspc run ex_03.sp
int:    42
float:  29.99
double: 3.141592653589793
bool:   true
char:   A
string: Hello, SP!
byte:   255
#4Basics & Fundamentals

4. Type Inference

#example-4

Hands-on syntax example and reference implementation for Type Inference.

ex_04.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // var — mutable, type inferred
4 // ═══════════════════════════════════════
5
6 var age = 21; // inferred as int
7 var name = "Shanto"; // inferred as string
8 var price = 99.99; // inferred as double
9 var active = true; // inferred as bool
10
11 age = 22; // ✅ Can reassign
12 name = "Shanto Paul"; // ✅ Can reassign
13
14 // ═══════════════════════════════════════
15 // let — mutable inferred (alternative)
16 // ═══════════════════════════════════════
17
18 let count = 100;
19 let message = "Hello";
20
21 // ═══════════════════════════════════════
22 // const — immutable, type inferred
23 // ═══════════════════════════════════════
24
25 const PI = 3.14159; // inferred as double, immutable
26 const APP = "SP Lang"; // inferred as string, immutable
27
28 // ❌ PI = 3.14; // error: cannot assign to constant
29
30 println("Age: ${age}");
31 println("Name: ${name}");
32 println("PI: ${PI}");
33 println("App: ${APP}");
34}
Expected Terminal Outputspc run ex_04.sp
Age: 22
Name: Shanto Paul
PI: 3.14159
App: SP Lang
#5Basics & Fundamentals

5. Operators

#example-5

Hands-on syntax example and reference implementation for Operators.

ex_05.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // ARITHMETIC
4 // ═══════════════════════════════════════
5
6 int a = 20;
7 int b = 7;
8
9 println("${a} + ${b} = ${a + b}"); // 27
10 println("${a} - ${b} = ${a - b}"); // 13
11 println("${a} * ${b} = ${a * b}"); // 140
12 println("${a} / ${b} = ${a / b}"); // 2 (integer division)
13 println("${a} % ${b} = ${a % b}"); // 6 (remainder)
14
15 // ═══════════════════════════════════════
16 // COMPARISON
17 // ═══════════════════════════════════════
18
19 println("${a} == ${b} → ${a == b}"); // false
20 println("${a} != ${b} → ${a != b}"); // true
21 println("${a} > ${b} → ${a > b}"); // true
22 println("${a} < ${b} → ${a < b}"); // false
23 println("${a} >= ${b} → ${a >= b}"); // true
24 println("${a} <= ${b} → ${a <= b}"); // false
25
26 // ═══════════════════════════════════════
27 // LOGICAL
28 // ═══════════════════════════════════════
29
30 bool x = true;
31 bool y = false;
32
33 println("${x} && ${y} → ${x && y}"); // false
34 println("${x} || ${y} → ${x || y}"); // true
35 println("!${x} → ${!x}"); // false
36
37 // ═══════════════════════════════════════
38 // ASSIGNMENT
39 // ═══════════════════════════════════════
40
41 int n = 10;
42 n += 5; println("n += 5 → ${n}"); // 15
43 n -= 3; println("n -= 3 → ${n}"); // 12
44 n *= 2; println("n *= 2 → ${n}"); // 24
45 n /= 4; println("n /= 4 → ${n}"); // 6
46 n %= 4; println("n %= 4 → ${n}"); // 2
47
48 // ═══════════════════════════════════════
49 // INCREMENT / DECREMENT
50 // ═══════════════════════════════════════
51
52 int counter = 0;
53 counter++; println("counter++ → ${counter}"); // 1
54 counter++; println("counter++ → ${counter}"); // 2
55 counter--; println("counter-- → ${counter}"); // 1
56
57 // ═══════════════════════════════════════
58 // BITWISE
59 // ═══════════════════════════════════════
60
61 int p = 0b1100; // 12
62 int q = 0b1010; // 10
63
64 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}"); // -13
68 println("p << 1 = ${p << 1}"); // 24
69 println("p >> 1 = ${p >> 1}"); // 6
70}
#6Basics & Fundamentals

6. Strings & Interpolation

#example-6

Hands-on syntax example and reference implementation for Strings & Interpolation.

ex_06.sp
1fn main() {
2 string firstName = "Shanto";
3 string lastName = "Paul";
4 int age = 21;
5
6 // ═══════════════════════════════════════
7 // CONCATENATION
8 // ═══════════════════════════════════════
9
10 string fullName = firstName + " " + lastName;
11 println(fullName); // Shanto Paul
12
13 // ═══════════════════════════════════════
14 // STRING INTERPOLATION ${expression}
15 // ═══════════════════════════════════════
16
17 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()}");
22
23 // ═══════════════════════════════════════
24 // ESCAPE SEQUENCES
25 // ═══════════════════════════════════════
26
27 println("Line 1\nLine 2"); // newline
28 println("Tab\there"); // tab
29 println("She said \"Hello\""); // quotes
30 println("Backslash: \\"); // backslash
31 println("Unicode: \u0041"); // A
32
33 // ═══════════════════════════════════════
34 // MULTI-LINE (future)
35 // ═══════════════════════════════════════
36
37 string poem = "Roses are red,\n"
38 + "Violets are blue,\n"
39 + "SP is awesome,\n"
40 + "And so are you.";
41
42 println(poem);
43}
Expected Terminal Outputspc run ex_06.sp
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.
#7Basics & Fundamentals

7. Console I/O

#example-7

Hands-on syntax example and reference implementation for Console I/O.

ex_07.sp
1import std.io;
2
3fn main() {
4 // ═══════════════════════════════════════
5 // OUTPUT
6 // ═══════════════════════════════════════
7
8 println("Hello, World!"); // Print with newline
9 print("Enter name: "); // Print without newline
10
11 // ═══════════════════════════════════════
12 // INPUT
13 // ═══════════════════════════════════════
14
15 string name = readLine();
16 println("Hello, ${name}!");
17
18 print("Enter age: ");
19 int age = int.parse(readLine());
20 println("You are ${age} years old.");
21
22 print("Enter score: ");
23 double score = double.parse(readLine());
24 println("Your score is ${score}");
25}
#8Basics & Fundamentals

8. Functions

#example-8

Examples and idioms for Functions, starting with basic functions.

Basic Functions

ex_08_1.sp
1// ═══════════════════════════════════════════════════
2// SP-NATIVE SYNTAX: fn name(params) -> returnType
3// ═══════════════════════════════════════════════════
4
5fn add(int a, int b) -> int {
6 return a + b;
7}
8
9fn greet(string name) {
10 println("Hello, ${name}!");
11}
12
13fn isAdult(int age) -> bool {
14 return age >= 18;
15}
16
17fn getFullName(string first, string last) -> string {
18 return "${first} ${last}";
19}
20
21fn main() {
22 int sum = add(10, 20);
23 println("Sum: ${sum}"); // Sum: 30
24
25 greet("Shanto"); // Hello, Shanto!
26
27 println(isAdult(21)); // true
28 println(isAdult(15)); // false
29
30 println(getFullName("Shanto", "Paul")); // Shanto Paul
31}

Java/C++ Style Functions (Also Valid!)

ex_08_2.sp
1// ═══════════════════════════════════════════════════
2// JAVA/C++ STYLE: returnType name(params)
3// ═══════════════════════════════════════════════════
4
5int multiply(int a, int b) {
6 return a * b;
7}
8
9string formatAge(string name, int age) {
10 return "${name} is ${age} years old";
11}
12
13void sayGoodbye(string name) {
14 println("Goodbye, ${name}!");
15}
16
17fn main() {
18 println(multiply(5, 4)); // 20
19 println(formatAge("Shanto", 21)); // Shanto is 21 years old
20 sayGoodbye("World"); // Goodbye, World!
21}

Short Form Functions

ex_08_3.sp
1// ═══════════════════════════════════════════════════
2// SHORT FORM: fn name(params) => expression
3// ═══════════════════════════════════════════════════
4
5fn 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;
11
12fn main() {
13 println("5² = ${square(5)}"); // 25
14 println("3³ = ${cube(3)}"); // 27
15 println("max(3,7) = ${max(3, 7)}"); // 7
16 println("min(3,7) = ${min(3, 7)}"); // 3
17 println("isEven(4) = ${isEven(4)}");// true
18 println("double(8) = ${double(8)}");// 16
19}

Functions with Default Parameters

ex_08_4.sp
1fn createUser(string name, int age, string role = "user") -> string {
2 return "${name} (${age}) - ${role}";
3}
4
5fn main() {
6 println(createUser("Shanto", 21)); // Shanto (21) - user
7 println(createUser("Admin", 30, "admin")); // Admin (30) - admin
8}

Recursive Functions

ex_08_5.sp
1fn factorial(int n) -> int {
2 if (n <= 1) return 1;
3 return n * factorial(n - 1);
4}
5
6fn 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}
11
12fn main() {
13 println("5! = ${factorial(5)}"); // 120
14 println("10! = ${factorial(10)}"); // 3628800
15
16 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 34
22}
#9Basics & Fundamentals

9. If / Else / Else-If

#example-9

Hands-on syntax example and reference implementation for If / Else / Else-If.

ex_09.sp
1fn main() {
2 int age = 21;
3 int score = 85;
4 string role = "admin";
5
6 // ═══════════════════════════════════════
7 // SIMPLE IF
8 // ═══════════════════════════════════════
9
10 if (age >= 18) {
11 println("You are an adult.");
12 }
13
14 // ═══════════════════════════════════════
15 // IF / ELSE
16 // ═══════════════════════════════════════
17
18 if (age >= 18) {
19 println("Welcome! You can enter.");
20 } else {
21 println("Sorry, you must be 18+.");
22 }
23
24 // ═══════════════════════════════════════
25 // IF / ELSE-IF / ELSE (Grade System)
26 // ═══════════════════════════════════════
27
28 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 }
39
40 // ═══════════════════════════════════════
41 // NESTED IF
42 // ═══════════════════════════════════════
43
44 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 }
53
54 // ═══════════════════════════════════════
55 // LOGICAL CONDITIONS
56 // ═══════════════════════════════════════
57
58 bool hasLicense = true;
59
60 if (age >= 18 && hasLicense) {
61 println("You can drive! 🚗");
62 }
63
64 if (role == "admin" || role == "moderator") {
65 println("You have elevated permissions.");
66 }
67
68 if (!hasLicense) {
69 println("Get a license first.");
70 }
71
72 // ═══════════════════════════════════════
73 // TERNARY OPERATOR
74 // ═══════════════════════════════════════
75
76 string status = age >= 18 ? "Adult" : "Minor";
77 println("Status: ${status}");
78}
Expected Terminal Outputspc run ex_09.sp
You are an adult.
Welcome! You can enter.
Grade: B  👍 Good job!
Admin access granted.
You can drive! 🚗
You have elevated permissions.
Status: Adult
#10Basics & Fundamentals

10. Switch & Match

#example-10

Examples and idioms for Switch & Match, starting with classic switch.

Classic Switch

ex_10_1.sp
1fn main() {
2 int day = 3;
3
4 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

ex_10_2.sp
1fn main() {
2 int day = 3;
3
4 // ═══════════════════════════════════════
5 // MATCH EXPRESSION (cleaner syntax)
6 // ═══════════════════════════════════════
7
8 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 }
18
19 // ═══════════════════════════════════════
20 // MATCH WITH STRINGS
21 // ═══════════════════════════════════════
22
23 string command = "start";
24
25 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 }
32
33 // ═══════════════════════════════════════
34 // MATCH WITH ENUM
35 // ═══════════════════════════════════════
36
37 enum Season { Spring, Summer, Autumn, Winter }
38
39 Season current = Season.Summer;
40
41 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}
Expected Terminal Outputspc run ex_10_2.sp
Wednesday
Starting server...
☀️ Beach time!
#11Control Flow & Structures

11. For Loops

#example-11

Hands-on syntax example and reference implementation for For Loops.

ex_11.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // CLASSIC FOR LOOP (C/Java style)
4 // ═══════════════════════════════════════
5
6 println("=== Classic For ===");
7 for (int i = 1; i <= 5; i++) {
8 println("Count: ${i}");
9 }
10
11 // ═══════════════════════════════════════
12 // RANGE LOOP (Modern SP)
13 // ═══════════════════════════════════════
14
15 println("\n=== Range Loop ===");
16 for (i in 0..5) {
17 print("${i} ");
18 }
19 println("");
20 // 0 1 2 3 4
21
22 // ═══════════════════════════════════════
23 // FOR-EACH (iterate collections)
24 // ═══════════════════════════════════════
25
26 println("\n=== For-Each ===");
27 let fruits = ["Apple", "Banana", "Cherry", "Date"];
28
29 for (string fruit in fruits) {
30 println("🍎 ${fruit}");
31 }
32
33 // ═══════════════════════════════════════
34 // NESTED LOOPS
35 // ═══════════════════════════════════════
36
37 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 }
44
45 // ═══════════════════════════════════════
46 // BREAK & CONTINUE
47 // ═══════════════════════════════════════
48
49 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 4
56
57 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 9
64
65 // ═══════════════════════════════════════
66 // COUNTDOWN
67 // ═══════════════════════════════════════
68
69 println("\n=== Countdown ===");
70 for (int i = 5; i >= 1; i--) {
71 println("${i}...");
72 }
73 println("🚀 Liftoff!");
74
75 // ═══════════════════════════════════════
76 // PATTERN: Sum of numbers
77 // ═══════════════════════════════════════
78
79 int sum = 0;
80 for (int i = 1; i <= 100; i++) {
81 sum += i;
82 }
83 println("\nSum of 1-100: ${sum}"); // 5050
84}
Expected Terminal Outputspc run ex_11.sp
=== 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
#12Control Flow & Structures

12. While & Do-While

#example-12

Hands-on syntax example and reference implementation for While & Do-While.

ex_12.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // WHILE LOOP
4 // ═══════════════════════════════════════
5
6 println("=== While Loop ===");
7 int count = 1;
8 while (count <= 5) {
9 println("Count: ${count}");
10 count++;
11 }
12
13 // ═══════════════════════════════════════
14 // DO-WHILE LOOP (runs at least once)
15 // ═══════════════════════════════════════
16
17 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, 16
24
25 // ═══════════════════════════════════════
26 // PATTERN: Find first power of 2 > 1000
27 // ═══════════════════════════════════════
28
29 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 = 1024
37
38 // ═══════════════════════════════════════
39 // PATTERN: Collatz Conjecture
40 // ═══════════════════════════════════════
41
42 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}
#13Control Flow & Structures

13. Arrays

#example-13

Hands-on syntax example and reference implementation for Arrays.

ex_13.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // DECLARATION
4 // ═══════════════════════════════════════
5
6 int[] numbers = {10, 20, 30, 40, 50};
7 string[] names = {"Alice", "Bob", "Charlie"};
8
9 // Modern syntax
10 let scores = [95, 87, 92, 78, 88];
11
12 // ═══════════════════════════════════════
13 // ACCESS & MODIFY
14 // ═══════════════════════════════════════
15
16 println("First: ${numbers[0]}"); // 10
17 println("Last: ${numbers[4]}"); // 50
18
19 numbers[0] = 100;
20 println("Updated first: ${numbers[0]}"); // 100
21
22 // ═══════════════════════════════════════
23 // ITERATE
24 // ═══════════════════════════════════════
25
26 println("\nAll names:");
27 for (string name in names) {
28 println(" - ${name}");
29 }
30
31 println("\nAll scores:");
32 for (int i = 0; i < scores.length(); i++) {
33 println(" Student ${i + 1}: ${scores[i]}");
34 }
35
36 // ═══════════════════════════════════════
37 // ARRAY OPERATIONS
38 // ═══════════════════════════════════════
39
40 println("\nLength: ${scores.length()}");
41
42 // Find max
43 int maxScore = scores[0];
44 for (int s in scores) {
45 if (s > maxScore) maxScore = s;
46 }
47 println("Highest score: ${maxScore}");
48
49 // Sum
50 int total = 0;
51 for (int s in scores) {
52 total += s;
53 }
54 println("Total: ${total}");
55 println("Average: ${total / scores.length()}");
56}
Expected Terminal Outputspc run ex_13.sp
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
#14Control Flow & Structures

14. Lists

#example-14

Hands-on syntax example and reference implementation for Lists.

ex_14.sp
1import std.collections;
2
3fn main() {
4 // ═══════════════════════════════════════
5 // CREATE LIST
6 // ═══════════════════════════════════════
7
8 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");
14
15 // Modern syntax
16 let numbers = [10, 20, 30, 40, 50];
17
18 // ═══════════════════════════════════════
19 // ACCESS
20 // ═══════════════════════════════════════
21
22 println("First fruit: ${fruits[0]}"); // Apple
23 println("List size: ${fruits.size()}"); // 5
24
25 // ═══════════════════════════════════════
26 // MODIFY
27 // ═══════════════════════════════════════
28
29 fruits.push("Fig"); // Add to end
30 fruits.remove("Date"); // Remove by value
31 fruits[1] = "Blueberry"; // Replace
32
33 // ═══════════════════════════════════════
34 // ITERATE
35 // ═══════════════════════════════════════
36
37 println("\nFruit basket:");
38 for (string fruit in fruits) {
39 println(" 🍎 ${fruit}");
40 }
41
42 // ═══════════════════════════════════════
43 // CHECK
44 // ═══════════════════════════════════════
45
46 if (fruits.contains("Cherry")) {
47 println("\nWe have cherries! 🍒");
48 }
49
50 println("Is empty: ${fruits.isEmpty()}"); // false
51
52 // ═══════════════════════════════════════
53 // FUNCTIONAL OPERATIONS
54 // ═══════════════════════════════════════
55
56 let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
57
58 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);
61
62 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}"); // 55
66}
#15Control Flow & Structures

15. Maps & Dictionaries

#example-15

Hands-on syntax example and reference implementation for Maps & Dictionaries.

ex_15.sp
1import std.collections;
2
3fn main() {
4 // ═══════════════════════════════════════
5 // CREATE MAP
6 // ═══════════════════════════════════════
7
8 Map<string, int> ages = new Map<string, int>();
9 ages["Shanto"] = 21;
10 ages["Alice"] = 25;
11 ages["Bob"] = 30;
12
13 // Modern literal syntax
14 let config = {
15 "host": "localhost",
16 "port": 8080,
17 "debug": true
18 };
19
20 let scores = {
21 "math": 95,
22 "science": 87,
23 "english": 92
24 };
25
26 // ═══════════════════════════════════════
27 // ACCESS
28 // ═══════════════════════════════════════
29
30 println("Shanto's age: ${ages["Shanto"]}"); // 21
31 println("Math score: ${scores["math"]}"); // 95
32
33 // ═══════════════════════════════════════
34 // MODIFY
35 // ═══════════════════════════════════════
36
37 ages["Charlie"] = 28; // Add new entry
38 ages["Shanto"] = 22; // Update existing
39 ages.remove("Bob"); // Remove entry
40
41 // ═══════════════════════════════════════
42 // CHECK
43 // ═══════════════════════════════════════
44
45 if (ages.containsKey("Alice")) {
46 println("Alice is ${ages["Alice"]} years old");
47 }
48
49 println("Total entries: ${ages.size()}");
50
51 // ═══════════════════════════════════════
52 // ITERATE
53 // ═══════════════════════════════════════
54
55 println("\nAll ages:");
56 for (entry in ages) {
57 println(" ${entry.key}: ${entry.value}");
58 }
59
60 println("\nAll scores:");
61 for (entry in scores) {
62 println(" 📚 ${entry.key} → ${entry.value}");
63 }
64}
Expected Terminal Outputspc run ex_15.sp
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
#16Control Flow & Structures

16. Classes

#example-16

Hands-on syntax example and reference implementation for Classes.

ex_16.sp
1class User {
2 string name;
3 int age;
4 string email;
5
6 // Constructor
7 User(string name, int age, string email) {
8 this.name = name;
9 this.age = age;
10 this.email = email;
11 }
12
13 // Methods
14 fn introduce() {
15 println("Hi! I'm ${name}, ${age} years old.");
16 println("Email: ${email}");
17 }
18
19 fn isAdult() -> bool {
20 return age >= 18;
21 }
22
23 fn birthday() {
24 age++;
25 println("🎂 Happy Birthday, ${name}! Now ${age}.");
26 }
27}
28
29fn main() {
30 // Create objects
31 User user1 = new User("Shanto", 21, "shanto@email.com");
32 User user2 = new User("Alice", 17, "alice@email.com");
33
34 // Use methods
35 user1.introduce();
36 println("Is adult: ${user1.isAdult()}"); // true
37 println("");
38
39 user2.introduce();
40 println("Is adult: ${user2.isAdult()}"); // false
41 println("");
42
43 user2.birthday(); // 🎂 Happy Birthday, Alice! Now 18.
44 println("Is adult now: ${user2.isAdult()}"); // true
45}
Expected Terminal Outputspc run ex_16.sp
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
#17Control Flow & Structures

17. Constructors

#example-17

Hands-on syntax example and reference implementation for Constructors.

ex_17.sp
1class Product {
2 string name;
3 double price;
4 int quantity;
5 string category;
6
7 // ═══════════════════════════════════════
8 // PRIMARY CONSTRUCTOR
9 // ═══════════════════════════════════════
10
11 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 }
17
18 // ═══════════════════════════════════════
19 // JAVA/C# STYLE CONSTRUCTOR (also valid)
20 // ═══════════════════════════════════════
21
22 Product(string name, double price) {
23 this.name = name;
24 this.price = price;
25 this.quantity = 0;
26 this.category = "General";
27 }
28
29 // Methods
30 fn totalValue() -> double {
31 return price * quantity;
32 }
33
34 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}
44
45fn main() {
46 Product laptop = new Product("MacBook Pro", 2499.99, 10, "Electronics");
47 Product book = new Product("SP Language Guide", 29.99);
48
49 laptop.display();
50 println("");
51 book.display();
52}
#18Control Flow & Structures

18. Access Modifiers

#example-18

Hands-on syntax example and reference implementation for Access Modifiers.

ex_18.sp
1class BankAccount {
2 // ═══════════════════════════════════════
3 // PUBLIC — accessible from anywhere
4 // ═══════════════════════════════════════
5 public string ownerName;
6
7 // ═══════════════════════════════════════
8 // PRIVATE — only within this class
9 // ═══════════════════════════════════════
10 private double balance;
11 private string accountNumber;
12
13 // ═══════════════════════════════════════
14 // PROTECTED — this class + subclasses
15 // ═══════════════════════════════════════
16 protected string accountType;
17
18 // ═══════════════════════════════════════
19 // INTERNAL — within same module only
20 // ═══════════════════════════════════════
21 internal string branchCode;
22
23 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 }
30
31 // Public methods — anyone can call
32 public fn deposit(double amount) {
33 if (amount > 0) {
34 balance += amount;
35 println("✅ Deposited \$${amount}. New balance: \$${balance}");
36 }
37 }
38
39 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 }
47
48 public fn getBalance() -> double {
49 return balance;
50 }
51
52 // Private method — internal use only
53 private fn generateId() -> string {
54 return "123456789";
55 }
56}
57
58fn main() {
59 BankAccount account = new BankAccount("Shanto", 1000.0);
60
61 println("Owner: ${account.ownerName}"); // ✅ public
62 account.deposit(500.0); // ✅ public method
63 account.withdraw(200.0); // ✅ public method
64 println("Balance: \$${account.getBalance()}");
65
66 // ❌ These would NOT compile:
67 // println(account.balance); // error: 'balance' is private
68 // println(account.accountNumber); // error: 'accountNumber' is private
69 // account.generateId(); // error: 'generateId' is private
70}
Expected Terminal Outputspc run ex_18.sp
Owner: Shanto
✅ Deposited $500.0. New balance: $1500.0
✅ Withdrew $200.0. New balance: $1300.0
Balance: $1300.0
#19Control Flow & Structures

19. Inheritance

#example-19

Hands-on syntax example and reference implementation for Inheritance.

ex_19.sp
1// ═══════════════════════════════════════════════════
2// BASE CLASS
3// ═══════════════════════════════════════════════════
4
5class Animal {
6 protected string name;
7 protected int age;
8
9 Animal(string name, int age) {
10 this.name = name;
11 this.age = age;
12 }
13
14 fn speak() {
15 println("${name} makes a sound.");
16 }
17
18 fn info() {
19 println("${name}, age ${age}");
20 }
21}
22
23// ═══════════════════════════════════════════════════
24// SUBCLASS — extends keyword
25// ═══════════════════════════════════════════════════
26
27class Dog extends Animal {
28
29 string breed;
30
31 Dog(string name, int age, string breed) {
32 super(name, age);
33 this.breed = breed;
34 }
35
36 override fn speak() {
37 println("${name} says: Woof! 🐕");
38 }
39
40 fn fetch() {
41 println("${name} fetches the ball! 🎾");
42 }
43}
44
45class Cat extends Animal {
46
47 bool isIndoor;
48
49 Cat(string name, int age, bool isIndoor) {
50 super(name, age);
51 this.isIndoor = isIndoor;
52 }
53
54 override fn speak() {
55 println("${name} says: Meow! 🐱");
56 }
57
58 fn purr() {
59 println("${name} is purring... 😺");
60 }
61}
62
63// ═══════════════════════════════════════════════════
64// C# STYLE SYNTAX (also valid!)
65// class Bird : Animal { }
66// ═══════════════════════════════════════════════════
67
68class Bird : Animal {
69 Bird(string name, int age) {
70 super(name, age);
71 }
72
73 override fn speak() {
74 println("${name} says: Tweet! 🐦");
75 }
76}
77
78fn 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);
82
83 // Polymorphism
84 Animal[] animals = {dog, cat, bird};
85
86 println("=== Animal Shelter ===\n");
87
88 for (Animal animal in animals) {
89 animal.info();
90 animal.speak();
91 println("");
92 }
93
94 // Class-specific methods
95 dog.fetch();
96 cat.purr();
97}
Expected Terminal Outputspc run ex_19.sp
=== 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... 😺
#20Control Flow & Structures

20. Interfaces

#example-20

Hands-on syntax example and reference implementation for Interfaces.

ex_20.sp
1// ═══════════════════════════════════════════════════
2// DEFINE INTERFACES
3// ═══════════════════════════════════════════════════
4
5interface Drawable {
6 fn draw();
7 fn getColor() -> string;
8}
9
10interface Resizable {
11 fn resize(double factor);
12 fn getArea() -> double;
13}
14
15// ═══════════════════════════════════════════════════
16// IMPLEMENT INTERFACES
17// ═══════════════════════════════════════════════════
18
19class Circle implements Drawable, Resizable {
20 double radius;
21 string color;
22
23 Circle(double radius, string color) {
24 this.radius = radius;
25 this.color = color;
26 }
27
28 fn draw() {
29 println("Drawing ⭕ Circle (r=${radius}, color=${color})");
30 }
31
32 fn getColor() -> string {
33 return color;
34 }
35
36 fn resize(double factor) {
37 radius *= factor;
38 println("Resized circle to radius ${radius}");
39 }
40
41 fn getArea() -> double {
42 return 3.14159 * radius * radius;
43 }
44}
45
46class Rectangle implements Drawable, Resizable {
47 double width;
48 double height;
49 string color;
50
51 Rectangle(double w, double h, string color) {
52 this.width = w;
53 this.height = h;
54 this.color = color;
55 }
56
57 fn draw() {
58 println("Drawing ▬ Rectangle (${width}x${height}, color=${color})");
59 }
60
61 fn getColor() -> string {
62 return color;
63 }
64
65 fn resize(double factor) {
66 width *= factor;
67 height *= factor;
68 }
69
70 fn getArea() -> double {
71 return width * height;
72 }
73}
74
75fn main() {
76 Drawable[] shapes = {
77 new Circle(5.0, "Red"),
78 new Rectangle(4.0, 6.0, "Blue")
79 };
80
81 for (Drawable shape in shapes) {
82 shape.draw();
83 }
84
85 println("\nAreas:");
86 Circle c = new Circle(10.0, "Green");
87 println("Circle area: ${c.getArea()}"); // 314.159
88
89 Rectangle r = new Rectangle(5.0, 8.0, "Yellow");
90 println("Rectangle area: ${r.getArea()}"); // 40.0
91}
#21Object-Oriented Programming

21. Abstract Classes

#example-21

Hands-on syntax example and reference implementation for Abstract Classes.

ex_21.sp
1abstract class Vehicle {
2 protected string brand;
3 protected int year;
4
5 Vehicle(string brand, int year) {
6 this.brand = brand;
7 this.year = year;
8 }
9
10 // Abstract — must be implemented by subclasses
11 abstract fn fuelType() -> string;
12 abstract fn maxSpeed() -> int;
13
14 // Concrete — shared by all subclasses
15 fn info() {
16 println("${brand} (${year}) — ${fuelType()}, max ${maxSpeed()} km/h");
17 }
18}
19
20class Car extends Vehicle {
21 Car(string brand, int year) { super(brand, year); }
22
23 fn fuelType() -> string { return "Gasoline ⛽"; }
24 fn maxSpeed() -> int { return 220; }
25}
26
27class ElectricCar extends Vehicle {
28 ElectricCar(string brand, int year) { super(brand, year); }
29
30 fn fuelType() -> string { return "Electric ⚡"; }
31 fn maxSpeed() -> int { return 250; }
32}
33
34class Bicycle extends Vehicle {
35 Bicycle(string brand, int year) { super(brand, year); }
36
37 fn fuelType() -> string { return "Human Power 🚴"; }
38 fn maxSpeed() -> int { return 45; }
39}
40
41fn main() {
42 Vehicle[] vehicles = {
43 new Car("Toyota", 2024),
44 new ElectricCar("Tesla", 2025),
45 new Bicycle("Trek", 2023)
46 };
47
48 println("=== Vehicle Fleet ===\n");
49 for (Vehicle v in vehicles) {
50 v.info();
51 }
52}
Expected Terminal Outputspc run ex_21.sp
=== Vehicle Fleet ===

Toyota (2024) — Gasoline ⛽, max 220 km/h
Tesla (2025) — Electric ⚡, max 250 km/h
Trek (2023) — Human Power 🚴, max 45 km/h
#22Object-Oriented Programming

22. Static Members

#example-22

Hands-on syntax example and reference implementation for Static Members.

ex_22.sp
1class Counter {
2 private static int count = 0;
3
4 static fn increment() {
5 count++;
6 }
7
8 static fn getCount() -> int {
9 return count;
10 }
11
12 static fn reset() {
13 count = 0;
14 }
15}
16
17class MathUtils {
18 static const double PI = 3.14159265358979;
19 static const double E = 2.71828182845904;
20
21 static fn circleArea(double radius) -> double {
22 return PI * radius * radius;
23 }
24
25 static fn square(int x) -> int {
26 return x * x;
27 }
28
29 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}
37
38fn main() {
39 // Static methods — no object needed
40 Counter.increment();
41 Counter.increment();
42 Counter.increment();
43 println("Count: ${Counter.getCount()}"); // 3
44
45 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}
#23Object-Oriented Programming

23. Structs

#example-23

Hands-on syntax example and reference implementation for Structs.

ex_23.sp
1// ═══════════════════════════════════════════════════
2// STRUCT — lightweight value type (stack allocated)
3// ═══════════════════════════════════════════════════
4
5struct Point {
6 int x;
7 int y;
8}
9
10struct Color {
11 int r;
12 int g;
13 int b;
14}
15
16struct Rectangle {
17 Point topLeft;
18 Point bottomRight;
19 Color color;
20}
21
22fn 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}
27
28fn main() {
29 Point p1;
30 p1.x = 0;
31 p1.y = 0;
32
33 Point p2;
34 p2.x = 3;
35 p2.y = 4;
36
37 println("Point 1: (${p1.x}, ${p1.y})");
38 println("Point 2: (${p2.x}, ${p2.y})");
39 println("Distance: ${distance(p1, p2)}"); // 5.0
40
41 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}
#24Object-Oriented Programming

24. Enums

#example-24

Hands-on syntax example and reference implementation for Enums.

ex_24.sp
1enum Direction {
2 North,
3 South,
4 East,
5 West
6}
7
8enum HttpStatus {
9 OK = 200,
10 NotFound = 404,
11 ServerError = 500
12}
13
14enum LogLevel {
15 Debug,
16 Info,
17 Warning,
18 Error,
19 Fatal
20}
21
22fn 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}
30
31fn 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}
40
41fn main() {
42 Direction dir = Direction.North;
43 println(describeDirection(dir));
44
45 HttpStatus status = HttpStatus.OK;
46 println("HTTP ${status}");
47
48 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}
Expected Terminal Outputspc run ex_24.sp
⬆️ Going North
HTTP 200

=== Log Messages ===
[INFO]    Application started
[DEBUG]   Loading config...
[WARNING] Memory usage high
[ERROR]   Connection failed
#25Object-Oriented Programming

25. Generics

#example-25

Hands-on syntax example and reference implementation for Generics.

ex_25.sp
1// ═══════════════════════════════════════════════════
2// GENERIC CLASS
3// ═══════════════════════════════════════════════════
4
5class Box<T> {
6 private T value;
7
8 Box(T value) {
9 this.value = value;
10 }
11
12 fn get() -> T {
13 return value;
14 }
15
16 fn set(T newValue) {
17 value = newValue;
18 }
19
20 fn display() {
21 println("Box contains: ${value}");
22 }
23}
24
25// ═══════════════════════════════════════════════════
26// GENERIC PAIR
27// ═══════════════════════════════════════════════════
28
29class Pair<A, B> {
30 A first;
31 B second;
32
33 Pair(A first, B second) {
34 this.first = first;
35 this.second = second;
36 }
37
38 fn display() {
39 println("(${first}, ${second})");
40 }
41}
42
43// ═══════════════════════════════════════════════════
44// GENERIC STACK
45// ═══════════════════════════════════════════════════
46
47class Stack<T> {
48 private List<T> items = new List<T>();
49
50 fn push(T item) {
51 items.add(item);
52 }
53
54 fn pop() -> T {
55 return items.removeLast();
56 }
57
58 fn peek() -> T {
59 return items[items.size() - 1];
60 }
61
62 fn isEmpty() -> bool {
63 return items.size() == 0;
64 }
65
66 fn size() -> int {
67 return items.size();
68 }
69}
70
71// ═══════════════════════════════════════════════════
72// GENERIC FUNCTIONS
73// ═══════════════════════════════════════════════════
74
75fn max<T>(T a, T b) -> T {
76 return a > b ? a : b;
77}
78
79fn swap<T>(T a, T b) -> Pair<T, T> {
80 return new Pair<T, T>(b, a);
81}
82
83fn main() {
84 // Generic Box
85 Box<int> intBox = new Box<int>(42);
86 Box<string> strBox = new Box<string>("Hello SP");
87
88 intBox.display(); // Box contains: 42
89 strBox.display(); // Box contains: Hello SP
90
91 // Generic Pair
92 Pair<string, int> person = new Pair<string, int>("Shanto", 21);
93 person.display(); // (Shanto, 21)
94
95 // Generic Stack
96 Stack<string> stack = new Stack<string>();
97 stack.push("first");
98 stack.push("second");
99 stack.push("third");
100
101 println("\nStack (LIFO):");
102 while (!stack.isEmpty()) {
103 println(" popped: ${stack.pop()}");
104 }
105
106 // Generic functions
107 println("\nmax(10, 20) = ${max(10, 20)}");
108 println("max(\"apple\", \"banana\") = ${max("apple", "banana")}");
109}
Expected Terminal Outputspc run ex_25.sp
Box contains: 42
Box contains: Hello SP
(Shanto, 21)

Stack (LIFO):
  popped: third
  popped: second
  popped: first

max(10, 20) = 20
max("apple", "banana") = banana
#26Object-Oriented Programming

26. Null Safety

#example-26

Hands-on syntax example and reference implementation for Null Safety.

ex_26.sp
1class User {
2 string name;
3 string? email; // Nullable — can be null
4
5 User(string name, string? email) {
6 this.name = name;
7 this.email = email;
8 }
9}
10
11fn 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 found
15}
16
17fn main() {
18 // ═══════════════════════════════════════
19 // NULLABLE TYPES (?)
20 // ═══════════════════════════════════════
21
22 User? user1 = findUser(1);
23 User? user2 = findUser(2);
24 User? user3 = findUser(999);
25
26 // ═══════════════════════════════════════
27 // SAFE ACCESS (?.)
28 // ═══════════════════════════════════════
29
30 println("User 1 name: ${user1?.name}"); // Shanto
31 println("User 1 email: ${user1?.email}"); // shanto@email.com
32 println("User 3 name: ${user3?.name}"); // null (no crash!)
33
34 // ═══════════════════════════════════════
35 // NULL COALESCING (??)
36 // ═══════════════════════════════════════
37
38 string email1 = user1?.email ?? "no-email@default.com";
39 string email2 = user2?.email ?? "no-email@default.com";
40 string name3 = user3?.name ?? "Unknown User";
41
42 println("\nEmail 1: ${email1}"); // shanto@email.com
43 println("Email 2: ${email2}"); // no-email@default.com
44 println("Name 3: ${name3}"); // Unknown User
45
46 // ═══════════════════════════════════════
47 // NULL CHECK
48 // ═══════════════════════════════════════
49
50 if (user1 != null) {
51 println("\n✅ Found user: ${user1.name}");
52 }
53
54 if (user3 == null) {
55 println("❌ User not found");
56 }
57
58 // ═══════════════════════════════════════
59 // NON-NULLABLE (default — safe!)
60 // ═══════════════════════════════════════
61
62 // string name = null; // ❌ COMPILE ERROR!
63 // int age = null; // ❌ COMPILE ERROR!
64}
#27Object-Oriented Programming

27. Error Handling — Try/Catch

#example-27

Hands-on syntax example and reference implementation for Error Handling — Try/Catch.

ex_27.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // TRY / CATCH / FINALLY
4 // ═══════════════════════════════════════
5
6 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 }
14
15 // ═══════════════════════════════════════
16 // MULTIPLE CATCH BLOCKS
17 // ═══════════════════════════════════════
18
19 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 }
34
35 // ═══════════════════════════════════════
36 // THROW EXCEPTIONS
37 // ═══════════════════════════════════════
38
39 try {
40 validateAge(-5);
41 } catch (Exception e) {
42 println("Validation: ${e.message}");
43 }
44}
45
46fn 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}
#28Object-Oriented Programming

28. Error Handling — Result Type

#example-28

Hands-on syntax example and reference implementation for Error Handling — Result Type.

ex_28.sp
1// ═══════════════════════════════════════════════════
2// RESULT TYPE — Modern error handling
3// ═══════════════════════════════════════════════════
4
5fn 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}
11
12fn 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}
19
20fn main() {
21 // Success case
22 let result1 = divide(100, 5);
23 match result1 {
24 Ok(value) => println("100 / 5 = ${value}"),
25 Error(err) => println("Error: ${err}")
26 }
27
28 // Error case
29 let result2 = divide(100, 0);
30 match result2 {
31 Ok(value) => println("Result: ${value}"),
32 Error(err) => println("Error: ${err}")
33 }
34
35 // Chain operations
36 let parsed = parseNumber("42");
37 match parsed {
38 Ok(n) => println("Parsed: ${n}"),
39 Error(e) => println("Failed: ${e}")
40 }
41
42 let invalid = parseNumber("hello");
43 match invalid {
44 Ok(n) => println("Parsed: ${n}"),
45 Error(e) => println("Failed: ${e}")
46 }
47}
Expected Terminal Outputspc run ex_28.sp
100 / 5 = 20
Error: Cannot divide 100 by zero
Parsed: 42
Failed: Invalid number: 'hello'
#29Object-Oriented Programming

29. Lambda Functions

#example-29

Hands-on syntax example and reference implementation for Lambda Functions.

ex_29.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // LAMBDA SYNTAX: (params) => expression
4 // ═══════════════════════════════════════
5
6 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}!";
11
12 println(add(10, 20)); // 30
13 println(multiply(5, 4)); // 20
14 println(square(7)); // 49
15 println(isEven(42)); // true
16 println(greet("Shanto")); // Hello, Shanto!
17
18 // ═══════════════════════════════════════
19 // LAMBDA WITH BLOCK BODY
20 // ═══════════════════════════════════════
21
22 var factorial = (int n) => {
23 int result = 1;
24 for (int i = 2; i <= n; i++) {
25 result *= i;
26 }
27 return result;
28 };
29
30 println("5! = ${factorial(5)}"); // 120
31 println("10! = ${factorial(10)}"); // 3628800
32
33 // ═══════════════════════════════════════
34 // LAMBDA AS FUNCTION ARGUMENT
35 // ═══════════════════════════════════════
36
37 let numbers = [1, 2, 3, 4, 5];
38
39 let doubled = numbers.map(x => x * 2);
40 println("Doubled: ${doubled}"); // [2, 4, 6, 8, 10]
41
42 let evens = numbers.filter(x => x % 2 == 0);
43 println("Evens: ${evens}"); // [2, 4]
44
45 let sum = numbers.reduce((a, b) => a + b);
46 println("Sum: ${sum}"); // 15
47}
#30Object-Oriented Programming

30. Higher-Order Functions

#example-30

Hands-on syntax example and reference implementation for Higher-Order Functions.

ex_30.sp
1// ═══════════════════════════════════════════════════
2// FUNCTIONS THAT TAKE FUNCTIONS AS PARAMETERS
3// ═══════════════════════════════════════════════════
4
5fn applyTwice(fn(int) -> int operation, int value) -> int {
6 return operation(operation(value));
7}
8
9fn 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}
16
17fn executeIf(bool condition, fn() action) {
18 if (condition) {
19 action();
20 }
21}
22
23// ═══════════════════════════════════════════════════
24// FUNCTIONS THAT RETURN FUNCTIONS
25// ═══════════════════════════════════════════════════
26
27fn multiplier(int factor) -> fn(int) -> int {
28 return (int x) => x * factor;
29}
30
31fn adder(int amount) -> fn(int) -> int {
32 return (int x) => x + amount;
33}
34
35fn main() {
36 // Pass lambda to function
37 int result = applyTwice(x => x * 2, 3);
38 println("applyTwice(double, 3) = ${result}"); // 12
39
40 // Transform array
41 int[] nums = {1, 2, 3, 4, 5};
42 int[] squared = transform(nums, x => x * x);
43 println("Squared: ${squared}"); // [1, 4, 9, 16, 25]
44
45 // Conditional execution
46 executeIf(true, () => println("This runs!"));
47 executeIf(false, () => println("This doesn't!"));
48
49 // Function factories
50 var double = multiplier(2);
51 var triple = multiplier(3);
52 var addTen = adder(10);
53
54 println("double(5) = ${double(5)}"); // 10
55 println("triple(5) = ${triple(5)}"); // 15
56 println("addTen(5) = ${addTen(5)}"); // 15
57
58 // ═══════════════════════════════════════
59 // CHAINING: map → filter → reduce
60 // ═══════════════════════════════════════
61
62 let result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
63 .map(x => x * x) // square each
64 .filter(x => x > 20) // keep > 20
65 .reduce((a, b) => a + b); // sum them
66
67 println("\nSum of squares > 20: ${result}"); // 25+36+49+64+81+100 = 355
68}
#31Advanced Types & Safety

31. Closures

#example-31

Hands-on syntax example and reference implementation for Closures.

ex_31.sp
1fn makeCounter() -> fn() -> int {
2 int count = 0;
3 return () => {
4 count++;
5 return count;
6 };
7}
8
9fn makeGreeter(string greeting) -> fn(string) -> string {
10 return (string name) => "${greeting}, ${name}!";
11}
12
13fn main() {
14 // Counter closure — captures and modifies `count`
15 var counter = makeCounter();
16 println(counter()); // 1
17 println(counter()); // 2
18 println(counter()); // 3
19
20 // Greeter closure — captures `greeting`
21 var hello = makeGreeter("Hello");
22 var hi = makeGreeter("Hi");
23
24 println(hello("Shanto")); // Hello, Shanto!
25 println(hi("Alice")); // Hi, Alice!
26}
#32Advanced Types & Safety

32. String Methods

#example-32

Hands-on syntax example and reference implementation for String Methods.

ex_32.sp
1fn main() {
2 string text = " Hello, SP Programming Language! ";
3
4 // ═══════════════════════════════════════
5 // COMMON STRING METHODS
6 // ═══════════════════════════════════════
7
8 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")}"); // true
14 println("StartsWith: ${text.trim().startsWith("Hello")}"); // true
15 println("EndsWith: ${text.trim().endsWith("!")}"); // true
16 println("IndexOf: ${text.indexOf("SP")}"); // 9
17 println("Replace: ${text.trim().replace("SP", "Shanto Paul")}");
18 println("Substring: ${text.trim().substring(0, 5)}"); // Hello
19 println("CharAt: ${text.trim().charAt(0)}"); // H
20
21 // ═══════════════════════════════════════
22 // SPLIT & JOIN
23 // ═══════════════════════════════════════
24
25 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 }
31
32 string joined = fruits.join(" | ");
33 println("Joined: ${joined}");
34 // apple | banana | cherry | date
35
36 // ═══════════════════════════════════════
37 // STRING INTERPOLATION
38 // ═══════════════════════════════════════
39
40 string name = "Shanto";
41 int age = 21;
42 double gpa = 3.95;
43
44 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}
#33Advanced Types & Safety

33. Method Overloading

#example-33

Hands-on syntax example and reference implementation for Method Overloading.

ex_33.sp
1class Printer {
2
3 // Same method name, different parameter types
4 fn print(int value) {
5 println("Integer: ${value}");
6 }
7
8 fn print(double value) {
9 println("Double: ${value}");
10 }
11
12 fn print(string value) {
13 println("String: ${value}");
14 }
15
16 fn print(bool value) {
17 println("Boolean: ${value}");
18 }
19
20 // Different parameter counts
21 fn print(string label, int value) {
22 println("${label}: ${value}");
23 }
24
25 fn print(string label, int value, string unit) {
26 println("${label}: ${value} ${unit}");
27 }
28}
29
30fn main() {
31 Printer p = new Printer();
32
33 p.print(42); // Integer: 42
34 p.print(3.14); // Double: 3.14
35 p.print("Hello"); // String: Hello
36 p.print(true); // Boolean: true
37 p.print("Age", 21); // Age: 21
38 p.print("Weight", 75, "kg"); // Weight: 75 kg
39}
#34Advanced Types & Safety

34. Operator Overloading

#example-34

Hands-on syntax example and reference implementation for Operator Overloading.

ex_34.sp
1struct Vector2 {
2 float x;
3 float y;
4
5 operator +(Vector2 a, Vector2 b) {
6 return Vector2(a.x + b.x, a.y + b.y);
7 }
8
9 operator -(Vector2 a, Vector2 b) {
10 return Vector2(a.x - b.x, a.y - b.y);
11 }
12
13 operator *(Vector2 v, float scalar) {
14 return Vector2(v.x * scalar, v.y * scalar);
15 }
16
17 operator ==(Vector2 a, Vector2 b) {
18 return a.x == b.x && a.y == b.y;
19 }
20}
21
22fn main() {
23 Vector2 a = Vector2(3.0, 4.0);
24 Vector2 b = Vector2(1.0, 2.0);
25
26 Vector2 sum = a + b;
27 Vector2 diff = a - b;
28 Vector2 scaled = a * 2.0;
29
30 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}"); // false
34}
#35Advanced Types & Safety

35. Extension Methods

#example-35

Hands-on syntax example and reference implementation for Extension Methods.

ex_35.sp
1extend string {
2 fn isEmail() -> bool {
3 return this.contains("@") && this.contains(".");
4 }
5
6 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 }
13
14 fn wordCount() -> int {
15 return this.trim().split(" ").length();
16 }
17}
18
19extend 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}
28
29fn main() {
30 // String extensions
31 println("test@email.com".isEmail()); // true
32 println("not-an-email".isEmail()); // false
33 println("Hello".reverse()); // olleH
34 println("Hello SP World".wordCount()); // 3
35
36 // Int extensions
37 println(42.isEven()); // true
38 println(7.isOdd()); // true
39 println(5.factorial()); // 120
40}
#36Advanced Types & Safety

36. Traits

#example-36

Hands-on syntax example and reference implementation for Traits.

ex_36.sp
1trait Serializable {
2 fn serialize() -> string;
3 fn deserialize(string data);
4}
5
6trait Displayable {
7 fn display();
8}
9
10class User with Serializable, Displayable {
11 string name;
12 int age;
13
14 User(string name, int age) {
15 this.name = name;
16 this.age = age;
17 }
18
19 fn serialize() -> string {
20 return "{\"name\":\"${name}\",\"age\":${age}}";
21 }
22
23 fn deserialize(string data) {
24 // Parse JSON data...
25 }
26
27 fn display() {
28 println("👤 ${name} (${age})");
29 }
30}
31
32fn main() {
33 User user = new User("Shanto", 21);
34 user.display(); // 👤 Shanto (21)
35 println("JSON: ${user.serialize()}"); // {"name":"Shanto","age":21}
36}
#37Advanced Types & Safety

37. Annotations

#example-37

Hands-on syntax example and reference implementation for Annotations.

ex_37.sp
1@Serializable
2class Config {
3 string host;
4 int port;
5 bool debug;
6}
7
8class ApiController {
9
10 @Route("/users")
11 @Method("GET")
12 fn getUsers() -> List<User> {
13 return userService.findAll();
14 }
15
16 @Route("/users")
17 @Method("POST")
18 fn createUser(User user) -> User {
19 return userService.save(user);
20 }
21
22 @Deprecated("Use getUsers() instead")
23 fn listUsers() -> List<User> {
24 return getUsers();
25 }
26}
27
28class MathService {
29
30 @inline
31 fn add(int a, int b) -> int {
32 return a + b;
33 }
34
35 @Test
36 fn testAdd() {
37 assert(add(2, 3) == 5);
38 }
39}
#38Advanced Types & Safety

38. Modules & Imports

#example-38

Hands-on syntax example and reference implementation for Modules & Imports.

ex_38.sp
1// ═══════════════════════════════════════════════════
2// FILE: src/models/user.sp
3// ═══════════════════════════════════════════════════
4
5module myapp.models;
6
7public class User {
8 public string name;
9 public int age;
10
11 public User(string name, int age) {
12 this.name = name;
13 this.age = age;
14 }
15}
16
17// ═══════════════════════════════════════════════════
18// FILE: src/services/user_service.sp
19// ═══════════════════════════════════════════════════
20
21module myapp.services;
22
23import myapp.models.User;
24
25public class UserService {
26 private List<User> users = new List<User>();
27
28 public fn addUser(User user) {
29 users.add(user);
30 }
31
32 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}
39
40// ═══════════════════════════════════════════════════
41// FILE: src/main.sp
42// ═══════════════════════════════════════════════════
43
44import std.io;
45import myapp.models.User;
46import myapp.services.UserService;
47
48fn main() {
49 UserService service = new UserService();
50 service.addUser(new User("Shanto", 21));
51 service.addUser(new User("Alice", 25));
52
53 User? user = service.findByName("Shanto");
54 println("Found: ${user?.name}, age ${user?.age}");
55
56 // Standard library imports
57 import std.math;
58 import std.collections;
59 import std.fs;
60 import std.json;
61 import std.http;
62 import std.time;
63}
#39Advanced Types & Safety

39. Async & Await

#example-39

Hands-on syntax example and reference implementation for Async & Await.

ex_39.sp
1import std.http;
2import std.io;
3
4async 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}
8
9async fn fetchMultipleUsers() {
10 // Sequential
11 let user1 = await fetchUser(1);
12 let user2 = await fetchUser(2);
13
14 println("User 1: ${user1.name}");
15 println("User 2: ${user2.name}");
16}
17
18async fn main() {
19 println("Fetching data...");
20 await fetchMultipleUsers();
21 println("Done!");
22}
#40Advanced Types & Safety

40. Threads & Concurrency

#example-40

Hands-on syntax example and reference implementation for Threads & Concurrency.

ex_40.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // SPAWN A THREAD
4 // ═══════════════════════════════════════
5
6 thread {
7 for (i in 0..5) {
8 println("Background: ${i}");
9 }
10 }
11
12 for (i in 0..5) {
13 println("Main: ${i}");
14 }
15
16 // ═══════════════════════════════════════
17 // FUTURE PRIMITIVES
18 // ═══════════════════════════════════════
19 // spawn — launch concurrent task
20 // channel — message passing
21 // mutex — mutual exclusion
22 // atomic — atomic operations
23}
#41File I/O & System APIs

41. Unsafe Mode

#example-41

Hands-on syntax example and reference implementation for Unsafe Mode.

ex_41.sp
1fn main() {
2 // ═══════════════════════════════════════
3 // UNSAFE BLOCK — for systems programming
4 // ═══════════════════════════════════════
5
6 unsafe {
7 pointer p = allocate(1024); // Raw memory allocation
8 // Direct memory operations
9 // Pointer arithmetic
10 // No bounds checking
11 free(p);
12 }
13
14 // Outside unsafe: full safety guarantees
15 println("Back to safe SP! ✅");
16}
#42File I/O & System APIs

42. Native Interop (C FFI)

#example-42

Hands-on syntax example and reference implementation for Native Interop (C FFI).

ex_42.sp
1// ═══════════════════════════════════════════════════
2// CALL C FUNCTIONS FROM SP
3// ═══════════════════════════════════════════════════
4
5extern "C" {
6 fn printf(string format);
7 fn strlen(string s) -> int;
8 fn malloc(int size) -> pointer;
9 fn free(pointer p);
10}
11
12fn main() {
13 // Call C's printf directly
14 printf("Hello from C! %d\n", 42);
15
16 // Use C's strlen
17 int len = strlen("Hello");
18 println("strlen: ${len}"); // 5
19}
#43File I/O & System APIs

43. Testing

#example-43

Hands-on syntax example and reference implementation for Testing.

ex_43.sp
1import std.testing;
2
3// ═══════════════════════════════════════════════════
4// FUNCTIONS TO TEST
5// ═══════════════════════════════════════════════════
6
7fn 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; }
13
14// ═══════════════════════════════════════════════════
15// TEST BLOCKS
16// ═══════════════════════════════════════════════════
17
18test "addition works" {
19 assert(add(2, 3) == 5);
20 assert(add(-1, 1) == 0);
21 assert(add(0, 0) == 0);
22}
23
24test "factorial is correct" {
25 assert(factorial(0) == 1);
26 assert(factorial(1) == 1);
27 assert(factorial(5) == 120);
28 assert(factorial(10) == 3628800);
29}
30
31test "even/odd detection" {
32 assert(isEven(0) == true);
33 assert(isEven(2) == true);
34 assert(isEven(3) == false);
35 assert(isEven(100) == true);
36}
37
38test "string operations" {
39 string name = "Shanto";
40 assert(name.length() == 6);
41 assert(name.upper() == "SHANTO");
42 assert(name.contains("han") == true);
43}
#44File I/O & System APIs

44. Comments & Documentation

#example-44

Hands-on syntax example and reference implementation for Comments & Documentation.

ex_44.sp
1// ═══════════════════════════════════════════════════
2// SINGLE-LINE COMMENT
3// ═══════════════════════════════════════════════════
4
5// This is a single-line comment
6int age = 21; // This is an inline comment
7
8// ═══════════════════════════════════════════════════
9// MULTI-LINE COMMENT
10// ═══════════════════════════════════════════════════
11
12/*
13 This is a multi-line comment.
14 It can span multiple lines.
15 Useful for longer explanations.
16*/
17
18// ═══════════════════════════════════════════════════
19// DOCUMENTATION COMMENT (for spc doc)
20// ═══════════════════════════════════════════════════
21
22/// 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///
#45File I/O & System APIs

45. Multi-Syntax Compatibility

#example-45

SP's unique feature — multiple syntax styles that compile to identical code:

ex_45.sp
1// ═══════════════════════════════════════════════════
2// FUNCTION DECLARATION — 3 valid styles
3// ═══════════════════════════════════════════════════
4
5// Style 1: SP-native
6fn add(int a, int b) -> int {
7 return a + b;
8}
9
10// Style 2: Java / C++ / C#
11int add(int a, int b) {
12 return a + b;
13}
14
15// Style 3: Short form
16fn add(a, b) => a + b;
17
18
19// ═══════════════════════════════════════════════════
20// VOID FUNCTIONS — 2 valid styles
21// ═══════════════════════════════════════════════════
22
23// SP-native
24fn printName() {
25 println("Shanto");
26}
27
28// Java/C++ style
29void printName() {
30 println("Shanto");
31}
32
33
34// ═══════════════════════════════════════════════════
35// INHERITANCE — 2 valid styles
36// ═══════════════════════════════════════════════════
37
38// Java style
39class Dog extends Animal { }
40
41// C# style
42class Dog : Animal { }
43
44
45// ═══════════════════════════════════════════════════
46// INTERFACE IMPLEMENTATION — 2 valid styles
47// ═══════════════════════════════════════════════════
48
49// Java style
50class User implements Serializable { }
51
52// C# style
53class User : Serializable { }
54
55
56// ═══════════════════════════════════════════════════
57// SWITCH vs MATCH
58// ═══════════════════════════════════════════════════
59
60// Classic (C/Java)
61switch (x) {
62 case 1: println("one"); break;
63 default: println("other");
64}
65
66// Modern (SP)
67match x {
68 1 => println("one"),
69 _ => println("other")
70}
71
72
73// ═══════════════════════════════════════════════════
74// CONSTRUCTOR — 2 valid styles
75// ═══════════════════════════════════════════════════
76
77// SP-native
78class User {
79 constructor(string name) {
80 this.name = name;
81 }
82}
83
84// Java/C# style
85class User {
86 User(string name) {
87 this.name = name;
88 }
89}
90
91
92// ═══════════════════════════════════════════════════
93// ENTRY POINT — 2 valid styles
94// ═══════════════════════════════════════════════════
95
96// SP-native (recommended)
97fn main() {
98 println("Hello, SP!");
99}
100
101// Java-style (compatibility)
102public static void main() {
103 System.out.println("Hello, SP!");
104}
#46File I/O & System APIs

46. Complete Programs

#example-46

Examples and idioms for Complete Programs, starting with 🧮 calculator.

🧮 Calculator

ex_46_1.sp
1import std.io;
2
3fn main() {
4 println("═══════════════════════════");
5 println(" SP Calculator");
6 println("═══════════════════════════\n");
7
8 print("Enter first number: ");
9 double a = double.parse(readLine());
10
11 print("Enter operator (+, -, *, /): ");
12 string op = readLine();
13
14 print("Enter second number: ");
15 double b = double.parse(readLine());
16
17 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 }
34
35 println("\n✅ ${a} ${op} ${b} = ${result}");
36}

📝 Todo App

ex_46_2.sp
1import std.io;
2import std.collections;
3
4class Task {
5 string title;
6 bool done;
7
8 Task(string title) {
9 this.title = title;
10 this.done = false;
11 }
12
13 fn toggle() { done = !done; }
14
15 fn toString() -> string {
16 string icon = done ? "✅" : "⬜";
17 return "${icon} ${title}";
18 }
19}
20
21class TodoApp {
22 private List<Task> tasks = new List<Task>();
23
24 fn add(string title) {
25 tasks.add(new Task(title));
26 println("Added: ${title}");
27 }
28
29 fn complete(int index) {
30 if (index >= 0 && index < tasks.size()) {
31 tasks[index].toggle();
32 println("Toggled: ${tasks[index].title}");
33 }
34 }
35
36 fn show() {
37 println("\n╔══════════════════════════════╗");
38 println("║ 📋 TODO LIST ║");
39 println("╠══════════════════════════════╣");
40
41 if (tasks.isEmpty()) {
42 println("║ No tasks yet! ║");
43 }
44
45 for (int i = 0; i < tasks.size(); i++) {
46 println("║ ${i + 1}. ${tasks[i].toString()}");
47 }
48
49 int done = tasks.filter(t => t.done).size();
50 println("╠══════════════════════════════╣");
51 println("║ ${done}/${tasks.size()} completed");
52 println("╚══════════════════════════════╝");
53 }
54}
55
56fn main() {
57 TodoApp app = new TodoApp();
58
59 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");
64
65 app.complete(0); // Learn SP syntax ✅
66 app.complete(1); // Build a compiler ✅
67
68 app.show();
69}
Expected Terminal Outputspc run ex_46_2.sp
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

ex_46_3.sp
1import std.io;
2import std.collections;
3
4class Account {
5 private string owner;
6 private double balance;
7 private List<string> history = new List<string>();
8
9 Account(string owner, double initial) {
10 this.owner = owner;
11 this.balance = initial;
12 log("Account created with \$${initial}");
13 }
14
15 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 }
24
25 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 }
34
35 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 }
46
47 fn showBalance() {
48 println("💰 ${owner}'s balance: \$${balance}");
49 }
50
51 fn showHistory() {
52 println("\n📜 ${owner}'s Transaction History:");
53 for (string entry in history) {
54 println(" ${entry}");
55 }
56 }
57
58 private fn log(string message) {
59 history.add(message);
60 }
61}
62
63fn main() {
64 println("═══════════════════════════════");
65 println(" 🏦 SP Banking System");
66 println("═══════════════════════════════\n");
67
68 Account shanto = new Account("Shanto", 5000.0);
69 Account alice = new Account("Alice", 3000.0);
70
71 shanto.deposit(2000.0);
72 shanto.withdraw(500.0);
73 shanto.transfer(alice, 1000.0);
74
75 println("");
76 shanto.showBalance();
77 alice.showBalance();
78
79 shanto.showHistory();
80 alice.showHistory();
81}
Expected Terminal Outputspc run ex_46_3.sp
═══════════════════════════════
  🏦 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
#47File I/O & System APIs

47. File System & File I/O (`std.fs`)

#example-47

Read and write text files synchronously with robust error handling.

ex_47.sp
1import std.io;
2import std.fs;
3
4fn main() {
5 string filePath = "notes.txt";
6
7 // Write text to a file
8 fs.writeString(filePath, "Hello from SP File System!\nSecond line of notes.\n");
9 println("File written successfully.");
10
11 // Check if file exists
12 if (fs.exists(filePath)) {
13 println("Verified: ${filePath} exists.");
14 }
15
16 // Read the file contents
17 string contents = fs.readString(filePath);
18 println("File Contents:\n${contents}");
19
20 // Append to file
21 fs.appendString(filePath, "Third line added via append.\n");
22 println("Updated Size: ${fs.size(filePath)} bytes");
23}
Expected Terminal Outputspc run ex_47.sp
File written successfully.
Verified: notes.txt exists.
File Contents:
Hello from SP File System!
Second line of notes.

Updated Size: 67 bytes
#48File I/O & System APIs

48. File Streaming & Buffers

#example-48

Read and process large files line-by-line without loading the entire file into memory.

ex_48.sp
1import std.io;
2import std.fs;
3
4fn 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");
7
8 FileStream stream = fs.openRead(logFile);
9 int lineNumber = 1;
10
11 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}
Expected Terminal Outputspc run ex_48.sp
[1] INFO: System started
[2] WARN: High memory usage
🚨 Alert on line 3: ERROR: Connection timed out
[4] INFO: Retry succeeded
#49File I/O & System APIs

49. Directory Traversal & Path Operations

#example-49

Work with paths, check file extensions, and traverse directories.

ex_49.sp
1import std.io;
2import std.fs;
3
4fn 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());
9
10 string joined = Path.join(["build", "bin", "spc.exe"]);
11 println("Joined Path: ${joined}");
12
13 // Create directory tree if not exists
14 fs.createDirAll("test_workspace/logs");
15 println("Directory created: test_workspace/logs");
16
17 List<string> entries = fs.listDir(".");
18 println("Total root entries found: ${entries.length()}");
19}
Expected Terminal Outputspc run ex_49.sp
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
#50File I/O & System APIs

50. Standard Math Functions (`std.math`)

#example-50

Trigonometry, exponential, rounding, and floating-point math utilities.

ex_50.sp
1import std.io;
2import std.math;
3
4fn main() {
5 double x = 45.0;
6 double rad = math.toRadians(x);
7
8 println("Angle: ${x} deg = ${rad} rad");
9 println("sin(45 deg): ${math.sin(rad)}");
10 println("cos(45 deg): ${math.cos(rad)}");
11
12 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}
Expected Terminal Outputspc run ex_50.sp
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
#51Collections & OS Utilities

51. Random & Pseudo-Random Generation

#example-51

Generate cryptographically sound or fast pseudo-random values.

ex_51.sp
1import std.io;
2import std.math;
3
4fn main() {
5 Random rng = new Random(1337); // Seeded for reproducibility
6
7 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("");
13
14 double probability = rng.nextDouble();
15 println("Random probability: ${probability}");
16
17 List<string> choices = ["Red", "Green", "Blue", "Cyan", "Amber"];
18 string picked = rng.choice(choices);
19 println("Randomly picked color: ${picked}");
20}
Expected Terminal Outputspc run ex_51.sp
🎲 Rolling a 6-sided dice 5 times:
4 2 6 1 5 
Random probability: 0.68421
Randomly picked color: Cyan
#52Collections & OS Utilities

52. Date & Time Manipulation (`std.time`)

#example-52

Current system clock, durations, timestamps, and ISO 8601 formatting.

ex_52.sp
1import std.io;
2import std.time;
3
4fn main() {
5 DateTime now = DateTime.now();
6 println("Current UTC Timestamp: ${now.toIsoString()}");
7 println("Year: ${now.year()}, Month: ${now.month()}, Day: ${now.day()}");
8
9 Duration tenDays = Duration.fromDays(10);
10 DateTime future = now.add(tenDays);
11 println("10 Days in Future: ${future.toIsoString()}");
12
13 Duration diff = future.diff(now);
14 println("Hours between: ${diff.inHours()} hours");
15}
Expected Terminal Outputspc run ex_52.sp
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
#53Collections & OS Utilities

53. High-Resolution Benchmarking & Stopwatches

#example-53

Measure execution elapsed time in microseconds and nanoseconds.

ex_53.sp
1import std.io;
2import std.time;
3
4fn heavyCalculation() -> long {
5 long sum = 0;
6 for (long i = 0; i < 1000000; i++) {
7 sum += i;
8 }
9 return sum;
10}
11
12fn main() {
13 Stopwatch sw = Stopwatch.startNew();
14
15 long result = heavyCalculation();
16 sw.stop();
17
18 println("Computation Result: ${result}");
19 println("Elapsed Milliseconds: ${sw.elapsedMilliseconds()} ms");
20 println("Elapsed Microseconds: ${sw.elapsedMicroseconds()} us");
21}
Expected Terminal Outputspc run ex_53.sp
Computation Result: 499999500000
Elapsed Milliseconds: 1.42 ms
Elapsed Microseconds: 1420 us
#54Collections & OS Utilities

54. OS Environment & System Info (`std.os`)

#example-54

Inspect hardware architecture, OS platform, and environment variables.

ex_54.sp
1import std.io;
2import std.os;
3
4fn main() {
5 println("OS Platform: " + os.platform());
6 println("CPU Architecture: " + os.arch());
7 println("Logical CPU Cores: ${os.cpuCount()}");
8
9 // Environment Variables
10 string user = os.getEnv("USER", os.getEnv("USERNAME", "Developer"));
11 println("Current User: ${user}");
12
13 os.setEnv("SP_ENV", "PRODUCTION");
14 println("SP_ENV: " + os.getEnv("SP_ENV", "DEFAULT"));
15}
Expected Terminal Outputspc run ex_54.sp
OS Platform: Windows
CPU Architecture: x86_64
Logical CPU Cores: 16
Current User: Shanto Paul
SP_ENV: PRODUCTION
#55Collections & OS Utilities

55. Process Spawning & Command Execution (`std.process`)

#example-55

Spawn native system processes, pass arguments, and capture output streams.

ex_55.sp
1import std.io;
2import std.process;
3
4fn main() {
5 println("Spawning git version check process...");
6
7 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}
Expected Terminal Outputspc run ex_55.sp
Spawning git version check process...
Success! Output: git version 2.44.0.windows.1
#56Collections & OS Utilities

56. Stack Data Structure (`std.collections.Stack`)

#example-56

LIFO (Last In First Out) collection with push, pop, peek, and size tracking.

ex_56.sp
1import std.io;
2import std.collections;
3
4fn 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}
22
23fn main() {
24 println("Balanced '({[]})': ${isBalanced('({[]})')}");
25 println("Balanced '([)]': ${isBalanced('([)]')}");
26}
Expected Terminal Outputspc run ex_56.sp
Balanced '({[]})': true
Balanced '([)]': false
#57Collections & OS Utilities

57. Queue Data Structure (`std.collections.Queue`)

#example-57

FIFO (First In First Out) collection for task queues and buffer pipelines.

ex_57.sp
1import std.io;
2import std.collections;
3
4fn main() {
5 Queue<string> taskQueue = new Queue<string>();
6
7 taskQueue.enqueue("Compile AST");
8 taskQueue.enqueue("Run Semantic Analysis");
9 taskQueue.enqueue("Optimize LLVM IR");
10 taskQueue.enqueue("Emit Object Binary");
11
12 println("Queue count: ${taskQueue.size()}");
13 println("Next task: " + taskQueue.peek());
14
15 while (!taskQueue.isEmpty()) {
16 string task = taskQueue.dequeue();
17 println("Executing: ${task}");
18 }
19 println("All tasks finished.");
20}
Expected Terminal Outputspc run ex_57.sp
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.
#58Collections & OS Utilities

58. Set Operations (`std.collections.Set`)

#example-58

High-performance unique element storage with mathematical set operations.

ex_58.sp
1import std.io;
2import std.collections;
3
4fn main() {
5 Set<int> setA = Set.of([1, 2, 3, 4, 5]);
6 Set<int> setB = Set.of([4, 5, 6, 7, 8]);
7
8 Set<int> unionSet = setA.union(setB);
9 Set<int> intersectSet = setA.intersect(setB);
10 Set<int> diffSet = setA.difference(setB);
11
12 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}
Expected Terminal Outputspc run ex_58.sp
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}
#59Collections & OS Utilities

59. Priority Queue & Heap

#example-59

Auto-sorted binary heap for priority scheduling and Dijkstra algorithms.

ex_59.sp
1import std.io;
2import std.collections;
3
4class Job {
5 public string name;
6 public int priority;
7
8 public Job(string name, int priority) {
9 this.name = name;
10 this.priority = priority;
11 }
12}
13
14fn main() {
15 // Highest priority job dequeues first
16 PriorityQueue<Job> pq = new PriorityQueue<Job>((a, b) => b.priority - a.priority);
17
18 pq.push(new Job("Send telemetry", 1));
19 pq.push(new Job("Critical security patch", 10));
20 pq.push(new Job("Database backup", 5));
21
22 while (!pq.isEmpty()) {
23 Job job = pq.pop();
24 println("Processing Job: ${job.name} (Priority ${job.priority})");
25 }
26}
Expected Terminal Outputspc run ex_59.sp
Processing Job: Critical security patch (Priority 10)
Processing Job: Database backup (Priority 5)
Processing Job: Send telemetry (Priority 1)
#60Collections & OS Utilities

60. Tuples & Destructuring

#example-60

Group multiple typed values together without creating dedicated structs.

ex_60.sp
1import std.io;
2
3fn 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}
12
13fn main() {
14 int[] scores = [84, 92, 45, 99, 73, 61];
15
16 // Tuple destructuring
17 (int lowest, int highest) = findMinMax(scores);
18
19 println("Lowest Score: ${lowest}");
20 println("Highest Score: ${highest}");
21
22 // Direct index access
23 var coordinate = ("X_AXIS", 1920, 1080);
24 println("Label: ${coordinate.0}, Width: ${coordinate.1}, Height: ${coordinate.2}");
25}
Expected Terminal Outputspc run ex_60.sp
Lowest Score: 45
Highest Score: 99
Label: X_AXIS, Width: 1920, Height: 1080
#61Modern Idioms & Error Handling

61. Pattern Matching with Guards

#example-61

Multi-way matching with value pattern tests and boolean conditions.

ex_61.sp
1import std.io;
2
3fn 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}
11
12fn main() {
13 println("-5 -> " + categorizeNumber(-5));
14 println("0 -> " + categorizeNumber(0));
15 println("42 -> " + categorizeNumber(42));
16 println("101 -> " + categorizeNumber(101));
17}
Expected Terminal Outputspc run ex_61.sp
-5  -> Negative number
0   -> Zero
42  -> Positive Even number
101 -> Positive Odd number
#62Modern Idioms & Error Handling

62. Immutability & Deep Constants

#example-62

Guarantee thread-safety and avoid accidental side-effects using `const`.

ex_62.sp
1import std.io;
2
3const double PI = 3.141592653589793;
4const string ECOSYSTEM_NAME = "SP 1.0 Production";
5
6fn main() {
7 println("Constant PI: ${PI}");
8 println("Ecosystem: ${ECOSYSTEM_NAME}");
9
10 // Immutable array reference
11 const int[] primeNumbers = [2, 3, 5, 7, 11, 13, 17];
12 println("Primes count: ${primeNumbers.length()}");
13}
Expected Terminal Outputspc run ex_62.sp
Constant PI: 3.141592653589793
Ecosystem: SP 1.0 Production
Primes count: 7
#63Modern Idioms & Error Handling

63. Value Semantics with Structs

#example-63

Structs in SP have value semantics: passing or assigning creates a direct stack copy.

ex_63.sp
1import std.io;
2
3struct Vector2D {
4 public double x;
5 public double y;
6
7 public fn length() -> double {
8 return math.sqrt(x * x + y * y);
9 }
10}
11
12fn main() {
13 Vector2D v1;
14 v1.x = 3.0;
15 v1.y = 4.0;
16
17 // Value copy: v2 receives its own independent copy
18 Vector2D v2 = v1;
19 v2.x = 10.0;
20
21 println("v1: (${v1.x}, ${v1.y}) - Length: ${v1.length()}");
22 println("v2: (${v2.x}, ${v2.y}) - Length: ${v2.length()}");
23}
Expected Terminal Outputspc run ex_63.sp
v1: (3.0, 4.0) - Length: 5.0
v2: (10.0, 4.0) - Length: 10.77033
#64Modern Idioms & Error Handling

64. Memory Layout & sizeof Operations

#example-64

Query exact byte size and memory alignment for primitives and structures.

ex_64.sp
1import std.io;
2
3struct CompactHeader {
4 int id; // 4 bytes
5 bool active; // 1 byte
6 double ratio; // 8 bytes
7}
8
9fn 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}
Expected Terminal Outputspc run ex_64.sp
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
#65Modern Idioms & Error Handling

65. Reference Parameters (ref & out)

#example-65

Pass arguments by reference to allow callers to observe mutations directly.

ex_65.sp
1import std.io;
2
3fn swap(ref int a, ref int b) {
4 int temp = a;
5 a = b;
6 b = temp;
7}
8
9fn divideWithRemainder(int dividend, int divisor, out int quotient, out int remainder) {
10 quotient = dividend / divisor;
11 remainder = dividend % divisor;
12}
13
14fn 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}");
20
21 int q;
22 int r;
23 divideWithRemainder(29, 6, out q, out r);
24 println("29 / 6 = ${q} with remainder ${r}");
25}
Expected Terminal Outputspc run ex_65.sp
Before swap: x=100, y=500
After swap:  x=500, y=100
29 / 6 = 4 with remainder 5
#66Modern Idioms & Error Handling

66. Defer Statement & RAII Cleanup

#example-66

Guarantee clean execution of resource cleanup when exiting the current block.

ex_66.sp
1import std.io;
2
3fn simulateDatabaseTransaction() {
4 println("1. Begin transaction");
5 defer println("4. Close database connection (deferred)");
6
7 println("2. Execute write queries");
8 defer println("3. Commit transaction (deferred)");
9
10 println("Working inside transaction scope...");
11}
12
13fn main() {
14 simulateDatabaseTransaction();
15 println("Function exited completely.");
16}
Expected Terminal Outputspc run ex_66.sp
1. Begin transaction
2. Execute write queries
Working inside transaction scope...
3. Commit transaction (deferred)
4. Close database connection (deferred)
Function exited completely.
#67Modern Idioms & Error Handling

67. Option Type Idiom (Option<T>)

#example-67

Express values that may or may not exist without using unsafe null references.

ex_67.sp
1import std.io;
2
3fn findUserEmail(int userId) -> Option<string> {
4 if (userId == 101) {
5 return Option.Some("alice@splang.shantopaul.com");
6 }
7 return Option.None();
8}
9
10fn main() {
11 Option<string> user1 = findUserEmail(101);
12 Option<string> user2 = findUserEmail(999);
13
14 println("User 101 Email: " + user1.unwrapOr("no-email@example.com"));
15 println("User 999 Email: " + user2.unwrapOr("no-email@example.com"));
16
17 if (user1.isSome()) {
18 println("User 101 is verified!");
19 }
20}
Expected Terminal Outputspc run ex_67.sp
User 101 Email: alice@splang.shantopaul.com
User 999 Email: no-email@example.com
User 101 is verified!
#68Modern Idioms & Error Handling

68. Result Type with Error Chaining

#example-68

Railway-oriented error handling for operations that can fail without throwing exceptions.

ex_68.sp
1import std.io;
2
3fn 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}
14
15fn main() {
16 var valid = parsePort("8080");
17 var invalid = parsePort("999999");
18
19 if (valid.isOk()) {
20 println("Server listening on port: ${valid.unwrap()}");
21 }
22
23 if (invalid.isErr()) {
24 println("Configuration error: " + invalid.unwrapErr());
25 }
26}
Expected Terminal Outputspc run ex_68.sp
Server listening on port: 8080
Configuration error: Port must be between 1 and 65535
#69Modern Idioms & Error Handling

69. Custom Exception Classes & Hierarchies

#example-69

Define domain-specific exception hierarchies with custom payload data.

ex_69.sp
1import std.io;
2
3class ValidationException extends Exception {
4 public string field;
5 public string rule;
6
7 public ValidationException(string field, string rule, string message) : super(message) {
8 this.field = field;
9 this.rule = rule;
10 }
11}
12
13fn validateUsername(string name) {
14 if (name.length() < 3) {
15 throw new ValidationException("username", "minLength", "Username must be at least 3 characters");
16 }
17}
18
19fn 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}
Expected Terminal Outputspc run ex_69.sp
❌ Validation Error on field 'username': Username must be at least 3 characters (Rule: minLength)
#70Modern Idioms & Error Handling

70. Multi-Catch & Exception Filtering

#example-70

Handle different exceptions cleanly in specialized catch handlers.

ex_70.sp
1import std.io;
2
3fn 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}
8
9fn 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}
Expected Terminal Outputspc run ex_70.sp
Job code 0 completed successfully.
Caught argument error: Negative value disallowed
Caught network timeout: Service did not respond within 500ms
#71Design Patterns & Functional

71. Builder Design Pattern

#example-71

Progressive object instantiation with fluent API chaining.

ex_71.sp
1import std.io;
2
3class HttpRequest {
4 public string method;
5 public string url;
6 public Map<string, string> headers;
7 public string body;
8
9 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}
16
17class RequestBuilder {
18 private string method = "GET";
19 private string url = "";
20 private Map<string, string> headers = new Map<string, string>();
21 private string body = "";
22
23 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; }
27
28 public fn build() -> HttpRequest {
29 return new HttpRequest(this.method, this.url, this.headers, this.body);
30 }
31}
32
33fn 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();
40
41 println("Request: ${req.method} ${req.url}");
42 println("Payload: ${req.body}");
43}
Expected Terminal Outputspc run ex_71.sp
Request: POST https://api.splang.shantopaul.com/v1/auth
Payload: {"user": "shanto"}
#72Design Patterns & Functional

72. Factory Design Pattern

#example-72

Encapsulate polymorphic object creation behind static factory methods.

ex_72.sp
1import std.io;
2
3interface NotificationService {
4 fn notify(string message);
5}
6
7class EmailService implements NotificationService {
8 public fn notify(string message) { println("📧 Sending Email: ${message}"); }
9}
10
11class SmsService implements NotificationService {
12 public fn notify(string message) { println("📱 Sending SMS: ${message}"); }
13}
14
15class 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}
22
23fn main() {
24 NotificationService email = NotificationFactory.create("email");
25 NotificationService sms = NotificationFactory.create("sms");
26
27 email.notify("Your SP compiler v1.0 build has finished!");
28 sms.notify("Two-factor code: 489201");
29}
Expected Terminal Outputspc run ex_72.sp
📧 Sending Email: Your SP compiler v1.0 build has finished!
📱 Sending SMS: Two-factor code: 489201
#73Design Patterns & Functional

73. Singleton Design Pattern

#example-73

Ensure only a single global instance of a resource manager exists.

ex_73.sp
1import std.io;
2
3class ConfigurationManager {
4 private static ConfigurationManager instance = null;
5 public string environment;
6
7 private ConfigurationManager() {
8 this.environment = "Production";
9 }
10
11 public static fn getInstance() -> ConfigurationManager {
12 if (instance == null) {
13 instance = new ConfigurationManager();
14 }
15 return instance;
16 }
17}
18
19fn main() {
20 ConfigurationManager cfg1 = ConfigurationManager.getInstance();
21 ConfigurationManager cfg2 = ConfigurationManager.getInstance();
22
23 println("cfg1 env: " + cfg1.environment);
24 cfg1.environment = "Staging";
25
26 // Both references point to the exact same instance
27 println("cfg2 env: " + cfg2.environment);
28 println("Identical reference: ${cfg1 === cfg2}");
29}
Expected Terminal Outputspc run ex_73.sp
cfg1 env: Production
cfg2 env: Staging
Identical reference: true
#74Design Patterns & Functional

74. Observer Design Pattern

#example-74

Decouple event publishers from multiple subscribed listeners.

ex_74.sp
1import std.io;
2import std.collections;
3
4interface Observer {
5 fn onEvent(string eventName);
6}
7
8class EventHub {
9 private List<Observer> listeners = new List<Observer>();
10
11 public fn subscribe(Observer obs) {
12 listeners.add(obs);
13 }
14
15 public fn emit(string eventName) {
16 println("📢 Event emitted: ${eventName}");
17 for (obs in listeners) {
18 obs.onEvent(eventName);
19 }
20 }
21}
22
23class UserLogger implements Observer {
24 public fn onEvent(string eventName) { println(" -> Logger recorded: ${eventName}"); }
25}
26
27class EmailAlert implements Observer {
28 public fn onEvent(string eventName) { println(" -> Alert sent for: ${eventName}"); }
29}
30
31fn main() {
32 EventHub hub = new EventHub();
33 hub.subscribe(new UserLogger());
34 hub.subscribe(new EmailAlert());
35
36 hub.emit("USER_REGISTERED");
37}
Expected Terminal Outputspc run ex_74.sp
📢 Event emitted: USER_REGISTERED
  -> Logger recorded: USER_REGISTERED
  -> Alert sent for: USER_REGISTERED
#75Design Patterns & Functional

75. Strategy Design Pattern with Lambdas

#example-75

Dynamically configure algorithms using first-class function closures.

ex_75.sp
1import std.io;
2
3type PaymentStrategy = fn(double) -> bool;
4
5class 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}
12
13fn main() {
14 Checkout shop = new Checkout();
15
16 PaymentStrategy creditCard = (amt) => {
17 println("Charging $${amt} via Credit Card gateway.");
18 return true;
19 };
20
21 PaymentStrategy crypto = (amt) => {
22 println("Generating on-chain transaction for $${amt}.");
23 return true;
24 };
25
26 shop.processPayment(150.0, creditCard);
27 shop.processPayment(420.0, crypto);
28}
Expected Terminal Outputspc run ex_75.sp
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.
#76Design Patterns & Functional

76. Custom Iterators & Iterable<T>

#example-76

Implement custom iterators to allow any class to be traversed with `for-in` loops.

ex_76.sp
1import std.io;
2
3class NumberRange implements Iterable<int> {
4 private int start;
5 private int end;
6
7 public NumberRange(int start, int end) {
8 this.start = start;
9 this.end = end;
10 }
11
12 public fn iterator() -> Iterator<int> {
13 return new RangeIterator(this.start, this.end);
14 }
15}
16
17class RangeIterator implements Iterator<int> {
18 private int current;
19 private int end;
20
21 public RangeIterator(int current, int end) {
22 this.current = current;
23 this.end = end;
24 }
25
26 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}
33
34fn main() {
35 NumberRange range = new NumberRange(5, 10);
36 for (num in range) {
37 print("${num} ");
38 }
39 println("");
40}
Expected Terminal Outputspc run ex_76.sp
5 6 7 8 9 10
#77Design Patterns & Functional

77. Generator & Yield Semantics

#example-77

Produce infinite or lazy data sequences on demand without upfront memory allocation.

ex_77.sp
1import std.io;
2
3fn 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}
13
14fn 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}
Expected Terminal Outputspc run ex_77.sp
Generating first 8 Fibonacci numbers:
0 1 1 2 3 5 8 13
#78Design Patterns & Functional

78. String Formatting & Padding

#example-78

Format numbers with precision, align table columns, and pad strings.

ex_78.sp
1import std.io;
2import std.string;
3
4fn main() {
5 println("=== Invoice Report ===");
6 println(string.format("%-15s | %8s | %10s", ["Item", "Qty", "Price"]));
7 println("----------------------------------------");
8
9 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]));
12
13 // Hex and Binary padding
14 int hexVal = 255;
15 println("Hex: 0x" + hexVal.toHex().padStart(4, '0'));
16}
Expected Terminal Outputspc run ex_78.sp
=== Invoice Report ===
Item            |      Qty |      Price
----------------------------------------
SP Compiler Pro |        2 | $    99.50
Cloud License   |        1 | $   450.00
Support SLA     |       12 | $    25.00
Hex: 0x00ff
#79Design Patterns & Functional

79. Regular Expressions & String Scanning

#example-79

Validate input format, extract capture groups, and replace text using patterns.

ex_79.sp
1import std.io;
2import std.string;
3
4fn main() {
5 string emailPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
6 Regex reg = new Regex(emailPattern);
7
8 string email1 = "team@splang.shantopaul.com";
9 string email2 = "invalid-email-address";
10
11 println("'${email1}' is valid: ${reg.test(email1)}");
12 println("'${email2}' is valid: ${reg.test(email2)}");
13
14 string text = "Order #1042 was placed on 2026-10-06";
15 string masked = text.replaceAll("\\d", "*");
16 println("Masked text: ${masked}");
17}
Expected Terminal Outputspc run ex_79.sp
'team@splang.shantopaul.com' is valid: true
'invalid-email-address' is valid: false
Masked text: Order #**** was placed on ****-**-**
#80Design Patterns & Functional

80. Byte Arrays & Binary Buffer Manipulation

#example-80

Low-level binary data serialization and byte slicing.

ex_80.sp
1import std.io;
2
3fn main() {
4 ByteBuffer buffer = new ByteBuffer(16);
5 buffer.writeInt32(1048576);
6 buffer.writeFloat64(3.14159);
7 buffer.writeString("SP");
8
9 println("Total bytes written: ${buffer.position()} bytes");
10
11 buffer.seek(0);
12 int readInt = buffer.readInt32();
13 double readFloat = buffer.readFloat64();
14 string readStr = buffer.readString(2);
15
16 println("Decoded Int: ${readInt}");
17 println("Decoded Float: ${readFloat}");
18 println("Decoded String: ${readStr}");
19}
Expected Terminal Outputspc run ex_80.sp
Total bytes written: 14 bytes
Decoded Int: 1048576
Decoded Float: 3.14159
Decoded String: SP
#81Networking, JSON & Protocols

81. JSON Serialization & Deserialization

#example-81

Streamlined JSON encode/decode with native SP mapping.

ex_81.sp
1import std.io;
2import json;
3
4fn main() {
5 string rawJson = "{\"language\": \"SP\", \"version\": 1.0, \"active\": true}";
6
7 JsonObject obj = json.parse(rawJson);
8 println("Language: " + obj.getString("language"));
9 println("Version: ${obj.getDouble('version')}");
10 println("Active: ${obj.getBool('active')}");
11
12 // Create and serialize
13 JsonObject outbound = new JsonObject();
14 outbound.put("status", "SUCCESS");
15 outbound.put("code", 200);
16
17 println("Serialized: " + outbound.stringify());
18}
Expected Terminal Outputspc run ex_81.sp
Language: SP
Version:  1.0
Active:   true
Serialized: {"code":200,"status":"SUCCESS"}
#82Networking, JSON & Protocols

82. Network Programming — TCP Client

#example-82

Connect to remote TCP servers, send raw bytes, and receive responses.

ex_82.sp
1import std.io;
2import std.net;
3
4fn main() {
5 println("Connecting to TCP echo service at 127.0.0.1:9000...");
6
7 try {
8 TcpSocket client = TcpSocket.connect("127.0.0.1", 9000);
9 client.write("PING_SP_LANGUAGE\n");
10
11 string reply = client.readLine();
12 println("Server replied: ${reply}");
13 client.close();
14 } catch (NetworkException e) {
15 println("Connection simulated: ${e.message}");
16 }
17}
Expected Terminal Outputspc run ex_82.sp
Connecting to TCP echo service at 127.0.0.1:9000...
Server replied: PONG_SP_LANGUAGE
#83Networking, JSON & Protocols

83. Network Programming — TCP Echo Server

#example-83

Listen on a local port and handle incoming network client connections.

ex_83.sp
1import std.io;
2import std.net;
3
4fn main() {
5 TcpListener server = new TcpListener(9000);
6 println("TCP Server listening on port 9000. Ready for connections.");
7
8 // In production, run inside an event loop
9 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}
Expected Terminal Outputspc run ex_83.sp
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.
#84Networking, JSON & Protocols

84. HTTP Client Requests (GET & POST)

#example-84

Perform asynchronous REST API requests with request headers and status codes.

ex_84.sp
1import std.io;
2import http;
3
4fn main() {
5 println("Executing HTTP GET https://api.splang.shantopaul.com/v1/packages...");
6
7 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");
11
12 // HTTP POST with JSON body
13 HttpResponse postRes = http.post("https://api.splang.shantopaul.com/v1/verify", "{\"pkg\": \"json\"}");
14 println("POST Status: ${postRes.statusCode}");
15}
Expected Terminal Outputspc run ex_84.sp
Executing HTTP GET https://api.splang.shantopaul.com/v1/packages...
Response Status: 200
Server: Vercel/Next.js
Body Length: 1420 chars
POST Status: 200
#85Networking, JSON & Protocols

85. HTTP Web Server Framework

#example-85

Build microservice HTTP APIs with route endpoints and middleware.

ex_85.sp
1import std.io;
2import http;
3
4fn main() {
5 HttpServer app = new HttpServer(8080);
6
7 app.get("/", (req, res) => {
8 res.send("Welcome to SP Web Framework!");
9 });
10
11 app.get("/api/health", (req, res) => {
12 res.json("{\"status\": \"healthy\", \"version\": \"1.0.0\"}");
13 });
14
15 println("Server running at http://localhost:8080/");
16 println("Serving routes: GET /, GET /api/health");
17}
Expected Terminal Outputspc run ex_85.sp
Server running at http://localhost:8080/
Serving routes: GET /, GET /api/health
#86Networking, JSON & Protocols

86. Cryptographic Primitives (SHA-256 & HMAC)

#example-86

Compute cryptographic hashes, digests, and verify secure signatures.

ex_86.sp
1import std.io;
2import crypto;
3
4fn main() {
5 string payload = "The SP Programming Language 1.0 Production Release";
6
7 string sha256Hash = crypto.sha256(payload);
8 println("Payload: ${payload}");
9 println("SHA-256: ${sha256Hash}");
10
11 string secretKey = "super-secret-key-2026";
12 string signature = crypto.hmacSha256(payload, secretKey);
13 println("HMAC Signature: ${signature}");
14}
Expected Terminal Outputspc run ex_86.sp
Payload: The SP Programming Language 1.0 Production Release
SHA-256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
HMAC Signature: 89f41a0e23d0628e94fa10b9872c67d1a51239c09bf872198c6109a24d852109
#87Networking, JSON & Protocols

87. CLI Argument Parsing with Flags

#example-87

Parse command-line flags, option key-values, and auto-generate help output.

ex_87.sp
1import std.io;
2import cli;
3
4fn 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");
9
10 // Simulate parsing arguments: ["--verbose", "-o", "program.exe", "-O", "3"]
11 var parsed = parser.parse(["--verbose", "-o", "program.exe", "-O", "3"]);
12
13 println("Verbose: ${parsed.getFlag('verbose')}");
14 println("Output: " + parsed.getOption("output"));
15 println("Opt: " + parsed.getOption("optimize"));
16}
Expected Terminal Outputspc run ex_87.sp
Verbose: true
Output:  program.exe
Opt:     3
#88Networking, JSON & Protocols

88. Structured Logging & Log Levels

#example-88

Output contextual logging with colors, timestamps, and log-level filtering.

ex_88.sp
1import std.io;
2import log;
3
4fn main() {
5 log.setLevel(LogLevel.DEBUG);
6
7 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}
Expected Terminal Outputspc run ex_88.sp
[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'
#89Networking, JSON & Protocols

89. Embedded SQLite Database Driver

#example-89

Connect to local SQLite databases, run DDL queries, and handle transactions.

ex_89.sp
1import std.io;
2import db;
3
4fn main() {
5 SqliteConnection db = SqliteConnection.open("app.db");
6
7 // Create table
8 db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, balance REAL)");
9
10 // Insert with prepared statement
11 PreparedStatement stmt = db.prepare("INSERT INTO users (name, balance) VALUES (?, ?)");
12 stmt.bindString(1, "Shanto");
13 stmt.bindDouble(2, 5000.0);
14 stmt.step();
15
16 // Query rows
17 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}
Expected Terminal Outputspc run ex_89.sp
User: #1 Shanto ($5000.0)
#90Networking, JSON & Protocols

90. Micro-Benchmarking with Variance Reporting

#example-90

Measure function execution statistical distribution (min, max, mean, stddev).

ex_90.sp
1import std.io;
2import test_bench;
3
4fn fib(int n) -> int {
5 if (n <= 1) return n;
6 return fib(n - 1) + fib(n - 2);
7}
8
9fn main() {
10 println("Benchmarking fib(20)...");
11
12 BenchmarkReport report = Benchmark.run(1000, () => {
13 fib(20);
14 });
15
16 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}
Expected Terminal Outputspc run ex_90.sp
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
#91Concurrency, Algorithms & Projects

91. Bitwise Operations & Bitflags

#example-91

Perform bit manipulation, masks, bit shifts, and combined access flags.

ex_91.sp
1import std.io;
2
3enum FilePermission {
4 READ = 1 << 0, // 0001 = 1
5 WRITE = 1 << 1, // 0010 = 2
6 EXECUTE = 1 << 2 // 0100 = 4
7}
8
9fn main() {
10 int userPerms = FilePermission.READ | FilePermission.WRITE; // 0011 = 3
11
12 bool canRead = (userPerms & FilePermission.READ) != 0;
13 bool canWrite = (userPerms & FilePermission.WRITE) != 0;
14 bool canExec = (userPerms & FilePermission.EXECUTE) != 0;
15
16 println("Can Read: ${canRead}");
17 println("Can Write: ${canWrite}");
18 println("Can Execute: ${canExec}");
19
20 // Bit shifts
21 int num = 8;
22 println("8 << 2 (x4): ${num << 2}");
23 println("8 >> 1 (/2): ${num >> 1}");
24}
Expected Terminal Outputspc run ex_91.sp
Can Read:    true
Can Write:   true
Can Execute: false
8 << 2 (x4): 32
8 >> 1 (/2): 4
#92Concurrency, Algorithms & Projects

92. Vector & Matrix Math Computations

#example-92

Linear algebra matrix transformations and dot product math.

ex_92.sp
1import std.io;
2import math_matrix;
3
4fn main() {
5 Matrix2D m1 = Matrix2D.fromArray([
6 [1.0, 2.0],
7 [3.0, 4.0]
8 ]);
9
10 Matrix2D m2 = Matrix2D.fromArray([
11 [2.0, 0.0],
12 [1.0, 2.0]
13 ]);
14
15 Matrix2D product = m1.multiply(m2);
16 println("Matrix Multiplication (m1 x m2):\n${product}");
17
18 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}
Expected Terminal Outputspc run ex_92.sp
Matrix Multiplication (m1 x m2):
[ 4.0, 4.0 ]
[ 10.0, 8.0 ]
Vector Dot Product: 32.0
#93Concurrency, Algorithms & Projects

93. Sorting Algorithms & Custom Comparators

#example-93

Sort collections in natural order, descending order, or by object properties.

ex_93.sp
1import std.io;
2import std.collections;
3
4class Student {
5 public string name;
6 public double gpa;
7
8 public Student(string name, double gpa) {
9 this.name = name;
10 this.gpa = gpa;
11 }
12}
13
14fn 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 ];
21
22 // Sort descending by GPA
23 students.sort((a, b) => b.gpa > a.gpa ? 1 : -1);
24
25 println("=== Honor Roll (Ranked by GPA) ===");
26 for (s in students) {
27 println(" ${s.name} - GPA: ${s.gpa}");
28 }
29}
Expected Terminal Outputspc run ex_93.sp
=== Honor Roll (Ranked by GPA) ===
  Charlie - GPA: 3.95
  Alice - GPA: 3.85
  Dave - GPA: 3.7
  Bob - GPA: 3.4
#94Concurrency, Algorithms & Projects

94. Search Algorithms (Binary & Linear)

#example-94

Fast `O(log n)` binary search on sorted lists versus linear search with predicates.

ex_94.sp
1import std.io;
2import std.collections;
3
4fn binarySearch(int[] arr, int target) -> int {
5 int low = 0;
6 int high = arr.length() - 1;
7
8 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}
16
17fn main() {
18 int[] sortedList = [10, 22, 35, 48, 59, 73, 88, 94];
19
20 int index1 = binarySearch(sortedList, 59);
21 int index2 = binarySearch(sortedList, 99);
22
23 println("Index of 59: ${index1} (Found)");
24 println("Index of 99: ${index2} (Not found)");
25}
Expected Terminal Outputspc run ex_94.sp
Index of 59: 4 (Found)
Index of 99: -1 (Not found)
#95Concurrency, Algorithms & Projects

95. Functional Pipeline Processing (Map, Filter, Fold)

#example-95

Chain functional transformations fluently without intermediary allocations.

ex_95.sp
1import std.io;
2import std.collections;
3
4fn main() {
5 List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
6
7 // Filter even numbers -> Square each -> Sum total
8 int sumOfSquares = numbers
9 .filter((n) => n % 2 == 0)
10 .map((n) => n * n)
11 .reduce(0, (acc, n) => acc + n);
12
13 println("Numbers: [1 .. 10]");
14 println("Even Squares sum (4 + 16 + 36 + 64 + 100): ${sumOfSquares}");
15}
Expected Terminal Outputspc run ex_95.sp
Numbers: [1 .. 10]
Even Squares sum (4 + 16 + 36 + 64 + 100): 220
#96Concurrency, Algorithms & Projects

96. Worker Threads & Channels

#example-96

Spawn concurrent worker threads and communicate safely via channels.

ex_96.sp
1import std.io;
2import std.sync;
3
4fn main() {
5 Channel<string> channel = new Channel<string>(10);
6
7 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 });
14
15 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}
Expected Terminal Outputspc run ex_96.sp
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.
#97Concurrency, Algorithms & Projects

97. Mutex & Lock Synchronization

#example-97

Protect shared mutable state from multi-threaded race conditions.

ex_97.sp
1import std.io;
2import std.sync;
3
4class Counter {
5 private int value = 0;
6 private Mutex lock = new Mutex();
7
8 public fn increment() {
9 lock.acquire();
10 try {
11 value += 1;
12 } finally {
13 lock.release();
14 }
15 }
16
17 public fn getValue() -> int { return value; }
18}
19
20fn main() {
21 Counter counter = new Counter();
22
23 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 }
31
32 for (t in threads) { t.join(); }
33 println("Final Synchronized Counter: ${counter.getValue()} (Expected: 4000)");
34}
Expected Terminal Outputspc run ex_97.sp
Final Synchronized Counter: 4000 (Expected: 4000)
#98Concurrency, Algorithms & Projects

98. Atomic Operations (Lock-Free)

#example-98

Hardware-backed atomic integers and operations without mutex overhead.

ex_98.sp
1import std.io;
2import std.sync;
3
4fn main() {
5 AtomicInt counter = new AtomicInt(0);
6
7 counter.fetchAdd(5);
8 counter.fetchAdd(10);
9 println("Atomic Value: ${counter.get()}");
10
11 // Compare and swap
12 bool swapped = counter.compareAndSwap(15, 100);
13 println("CAS successful (15 -> 100): ${swapped}");
14 println("New Value: ${counter.get()}");
15}
Expected Terminal Outputspc run ex_98.sp
Atomic Value: 15
CAS successful (15 -> 100): true
New Value: 100
#99Concurrency, Algorithms & Projects

99. Real-World Project: High-Performance Key-Value Store

#example-99

An in-memory key-value database engine with item TTL and metrics.

ex_99.sp
1import std.io;
2import std.collections;
3import std.time;
4
5class CacheItem {
6 public string value;
7 public long expiresAt;
8
9 public CacheItem(string val, long ttlSeconds) {
10 this.value = val;
11 this.expiresAt = DateTime.now().toEpochSeconds() + ttlSeconds;
12 }
13
14 public fn isExpired() -> bool {
15 return DateTime.now().toEpochSeconds() > this.expiresAt;
16 }
17}
18
19class KeyValueStore {
20 private Map<string, CacheItem> store = new Map<string, CacheItem>();
21
22 public fn set(string key, string value, long ttlSeconds) {
23 store.put(key, new CacheItem(value, ttlSeconds));
24 }
25
26 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}
36
37fn main() {
38 println("════════════════════════════════════════");
39 println(" ⚡ SP In-Memory Cache Engine");
40 println("════════════════════════════════════════");
41
42 KeyValueStore cache = new KeyValueStore();
43 cache.set("session:token", "eyJhbGciOiJIUzI1NiJ9", 3600);
44 cache.set("user:101:name", "Shanto Paul", 3600);
45
46 Option<string> user = cache.get("user:101:name");
47 Option<string> missing = cache.get("user:999:name");
48
49 println("Found key 'user:101:name': " + user.unwrapOr("NULL"));
50 println("Missing key check: " + missing.unwrapOr("NULL"));
51}
Expected Terminal Outputspc run ex_99.sp
════════════════════════════════════════
  ⚡ SP In-Memory Cache Engine
════════════════════════════════════════
Found key 'user:101:name': Shanto Paul
Missing key check: NULL
#100Concurrency, Algorithms & Projects

100. Real-World Project: Multi-Threaded HTTP REST Microservice

#example-100

Complete microservice architecture with routing, JSON parsing, and models.

ex_100.sp
1import std.io;
2import http;
3import json;
4import std.collections;
5
6class Product {
7 public int id;
8 public string name;
9 public double price;
10
11 public Product(int id, string name, double price) {
12 this.id = id;
13 this.name = name;
14 this.price = price;
15 }
16}
17
18class ProductCatalogService {
19 private List<Product> catalog = [];
20
21 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 }
25
26 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}
41
42fn main() {
43 println("═══════════════════════════════════════════════");
44 println(" 🚀 SP High-Performance REST Microservice 1.0");
45 println("═══════════════════════════════════════════════");
46
47 HttpServer app = new HttpServer(8080);
48 ProductCatalogService service = new ProductCatalogService();
49 service.init();
50 service.handleRoutes(app);
51
52 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}
Expected Terminal Outputspc run ex_100.sp
═══════════════════════════════════════════════
  🚀 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