Module Examples#
Examples demonstrating Bark’s module functions. Modules provide specialized operations accessed via module.function() syntax.
str#
String manipulation operations.
modules/str/strings.bark
View on GitLab// bark String Module Examples
// Demonstrates string manipulation operations
println("=== String Case Conversion ===")
// Convert to uppercase
"hello world" > str.upper() > println()
// Convert to lowercase
"HELLO WORLD" > str.lower() > println()
println("\n=== String Trimming ===")
// Trim whitespace from both ends
" hello world " > str.trim() > println()
println("\n=== String Prefix/Suffix Checks ===")
// Check if string starts with prefix
"hello world" > str.starts_with?("hello") > println()
"hello world" > str.starts_with?("world") > println()
// Check if string ends with suffix
"hello world" > str.ends_with?("world") > println()
"hello world" > str.ends_with?("hello") > println()
println("\n=== String Replacement ===")
// Replace all occurrences of a substring
"hello hello hello" > str.replace("hello", "hi") > println()
println("\n=== String Splitting ===")
// Split string by delimiter
"apple,banana,cherry" > str.split(",") > (fruits array) {
println("Fruits: {fruits}")
// Get individual elements
fruits > get(0) > println()
fruits > get(1) > println()
fruits > get(2) > println()
}()
println("\n=== String Joining ===")
// Join array of strings with separator
["red", "green", "blue"] > str.join(", ") > println()
["one", "two", "three"] > str.join("-") > println()
println("\n=== String Concatenation ===")
// Concatenate multiple strings
str.concat("Hello", " ", "World", "!") > println()
println("\n=== String Formatting ===")
// Format string with placeholders
str.format("Name: {0}, Age: {1}", "Alice", 30) > println()
str.format("Coordinates: ({0}, {1})", 10, 20) > println()
println("\n=== Practical Examples ===")
// Building a full name
fn format_name(first string, last string) {
str.concat(first, " ", last) > str.upper() > return()
}(string)
"john" > format_name("doe") > println()
// Parsing CSV-like data
"id:123,name:Alice,role:admin" > str.split(",") > (parts array) {
parts > each((arr array, i int) {
arr > get(i) > (part string) {
println("Part {i}: {part}")
}()
}())
}()
// Cleaning and normalizing input
fn normalize_input(input string) {
input > str.trim() > str.lower() > return()
}(string)
" HELLO World " > normalize_input() > println()
println("\nAll string examples completed!")
math#
Mathematical operations including basic arithmetic, trigonometry, and constants.
modules/math/basic.bark
View on GitLab// bark Math Module Examples - Basic Operations
// Demonstrates basic mathematical operations
println("=== Arithmetic Operations ===")
// Modulo (remainder)
17 > math.mod(5) > println() // 2
-7 > math.mod(3) > println() // -1
// Absolute value
-42 > math.abs() > println() // 42
3.14 > math.abs() > println() // 3.14
-2.718 > math.abs() > println() // 2.718
println("\n=== Rounding Operations ===")
// Ceiling (round up)
3.2 > math.ceil() > println() // 4
-3.2 > math.ceil() > println() // -3
// Floor (round down)
3.8 > math.floor() > println() // 3
-3.8 > math.floor() > println() // -4
// Round to decimal places
3.14159 > math.round(2) > println() // 3.14
3.14159 > math.round(4) > println() // 3.1416
2.5 > math.round(0) > println() // 3
println("\n=== Min and Max ===")
// Find minimum value
math.min(5, 3, 8, 1, 9) > println() // 1
math.min(3.14, 2.71, 1.41) > println() // 1.41
// Find maximum value
math.max(5, 3, 8, 1, 9) > println() // 9
math.max(3.14, 2.71, 1.41) > println() // 3.14
println("\n=== Power and Root Operations ===")
// Square root
16 > math.sqrt() > println() // 4
2 > math.sqrt() > println() // 1.4142...
// Power (exponentiation)
2 > math.pow(10) > println() // 1024
3 > math.pow(4) > println() // 81
2.0 > math.pow(0.5) > println() // 1.4142... (square root)
// Exponential (e^x)
1 > math.exp() > println() // 2.718... (e)
0 > math.exp() > println() // 1
println("\n=== Logarithms ===")
// Natural logarithm (base e)
math.e() > math.log() > println() // 1
10 > math.log() > println() // 2.302...
// Base-10 logarithm
100 > math.log10() > println() // 2
1000 > math.log10() > println() // 3
println("\n=== Integer/Float Conversion ===")
// Convert float to integer (truncates)
3.7 > math.to_int() > println() // 3
-3.7 > math.to_int() > println() // -3
// Convert integer to float
42 > math.to_float() > println() // 42.0
println("\n=== Odd/Even Checks ===")
// Check if odd
7 > math.odd?() > println() // true
8 > math.odd?() > println() // false
// Check if even
7 > math.even?() > println() // false
8 > math.even?() > println() // true
println("\n=== Constants ===")
// Mathematical constants
math.pi() > println() // 3.14159...
math.e() > println() // 2.71828...
println("\n=== Practical Examples ===")
// Calculate compound interest: A = P(1 + r)^t
fn compound_interest(principal float, rate float, years int) {
1.0 > add(rate) > math.pow(years) > mul(principal) > return()
}(float)
1000.0 > compound_interest(0.05, 10) > (result float) {
println("$1000 at 5% for 10 years: {result}")
}()
// Calculate distance between two points
fn distance(x1 float, y1 float, x2 float, y2 float) {
x2 > sub(x1) > math.pow(2) > (dx_sq float) {
y2 > sub(y1) > math.pow(2) > (dy_sq float) {
dx_sq > add(dy_sq) > math.sqrt() > return()
}()
}()
}(float)
0.0 > distance(0.0, 3.0, 4.0) > (dist float) {
println("Distance from (0,0) to (3,4): {dist}")
}()
// Check if a number is a perfect square
fn is_perfect_square(n int) {
n > math.sqrt() > math.to_int() > (root int) {
root > mul(root) > eq?(n) > return()
}()
}(bool)
16 > is_perfect_square() > println() // true
17 > is_perfect_square() > println() // false
25 > is_perfect_square() > println() // true
println("\nAll basic math examples completed!")
modules/math/trigonometry.bark
View on GitLab// bark Math Module Examples - Trigonometry
// Demonstrates trigonometric functions (all angles in radians)
println("=== Mathematical Constants ===")
// Pi and Euler's number
math.pi() > (pi float) {
println("Pi: {pi}")
}()
math.e() > (e float) {
println("e: {e}")
}()
println("\n=== Basic Trigonometric Functions ===")
// Sin, Cos, Tan at common angles
println("At 0 radians:")
0 > math.sin() > println() // 0
0 > math.cos() > println() // 1
0 > math.tan() > println() // 0
// pi/2 radians (90 degrees)
math.pi() > div(2.0) > (half_pi float) {
println("\nAt pi/2 radians (90 degrees):")
half_pi > math.sin() > println() // 1
half_pi > math.cos() > println() // ~0 (very small due to floating point)
}()
// pi radians (180 degrees)
math.pi() > (pi float) {
println("\nAt pi radians (180 degrees):")
pi > math.sin() > println() // ~0
pi > math.cos() > println() // -1
}()
// pi/4 radians (45 degrees)
math.pi() > div(4.0) > (quarter_pi float) {
println("\nAt pi/4 radians (45 degrees):")
quarter_pi > math.sin() > println() // 0.7071...
quarter_pi > math.cos() > println() // 0.7071...
quarter_pi > math.tan() > println() // 1
}()
println("\n=== Inverse Trigonometric Functions ===")
// Arcsine (returns radians)
0 > math.asin() > println() // 0
1 > math.asin() > println() // pi/2 (1.5707...)
0.5 > math.asin() > println() // pi/6 (0.5235...)
// Arccosine
1 > math.acos() > println() // 0
0 > math.acos() > println() // pi/2 (1.5707...)
0.5 > math.acos() > println() // pi/3 (1.0471...)
// Arctangent
0 > math.atan() > println() // 0
1 > math.atan() > println() // pi/4 (0.7853...)
println("\n=== Practical Examples ===")
// Convert degrees to radians
fn degrees_to_radians(degrees float) {
math.pi() > (pi float) {
degrees > mul(pi) > div(180.0) > return()
}()
}(float)
// Convert radians to degrees
fn radians_to_degrees(radians float) {
math.pi() > (pi float) {
radians > mul(180.0) > div(pi) > return()
}()
}(float)
45.0 > degrees_to_radians() > (rad float) {
println("45 degrees = {rad} radians")
}()
math.pi() > radians_to_degrees() > (deg float) {
println("Pi radians = {deg} degrees")
}()
// Calculate sin of an angle in degrees
fn sin_degrees(degrees float) {
degrees > degrees_to_radians() > math.sin() > return()
}(float)
30.0 > sin_degrees() > (result float) {
println("sin(30 degrees) = {result}")
}()
90.0 > sin_degrees() > (result float) {
println("sin(90 degrees) = {result}")
}()
// Verify Pythagorean identity: sin^2(x) + cos^2(x) = 1
fn verify_pythagorean_identity(radians float) {
radians > math.sin() > math.pow(2) > (sin_sq float) {
radians > math.cos() > math.pow(2) > (cos_sq float) {
sin_sq > add(cos_sq) > return()
}()
}()
}(float)
println("\nPythagorean identity sin^2(x) + cos^2(x) at various angles:")
0.5 > verify_pythagorean_identity() > println() // Should be 1
1.0 > verify_pythagorean_identity() > println() // Should be 1
2.0 > verify_pythagorean_identity() > println() // Should be 1
// Calculate the angle of a right triangle given opposite and adjacent sides
fn calculate_angle(opposite float, adjacent float) {
opposite > div(adjacent) > math.atan() > radians_to_degrees() > return()
}(float)
3.0 > calculate_angle(4.0) > (angle float) {
println("\nAngle with opposite=3, adjacent=4: {angle} degrees")
}()
// Calculate the hypotenuse using trigonometry
fn calculate_hypotenuse(adjacent float, angle_degrees float) {
angle_degrees > degrees_to_radians() > math.cos() > (cos_val float) {
adjacent > div(cos_val) > return()
}()
}(float)
4.0 > calculate_hypotenuse(60.0) > (hyp float) {
println("Hypotenuse with adjacent=4, angle=60 degrees: {hyp}")
}()
println("\nAll trigonometry examples completed!")
array#
Array manipulation operations.
modules/array/operations.bark
View on GitLab// bark Array Module Examples
// Demonstrates array manipulation operations
println("=== Array Push (Add to End) ===")
// Push single element
[1, 2, 3] > array.push(4) > println()
// Push multiple elements
[1, 2, 3] > array.push(4, 5, 6) > println()
println("\n=== Array Append To (Pipe-friendly Push) ===")
// Append value to array (value first, array second - for link operator)
10 > array.append_to([1, 2, 3]) > println()
println("\n=== Array Unshift (Add to Beginning) ===")
// Add element to beginning
[2, 3, 4] > array.unshift(1) > println()
// Add multiple elements to beginning
[4, 5, 6] > array.unshift(1, 2, 3) > println()
println("\n=== Array Pop (Remove from End) ===")
// Pop returns (modified_array, popped_element)
[1, 2, 3, 4, 5] > array.pop() > (result array) {
result > get(0) > println() // The modified array
result > get(1) > println() // The popped element
}()
println("\n=== Array Shift (Remove from Beginning) ===")
// Shift returns (modified_array, shifted_element)
[1, 2, 3, 4, 5] > array.shift() > (result array) {
result > get(0) > println() // The modified array
result > get(1) > println() // The shifted element
}()
println("\n=== Array Slice ===")
// Extract a portion of array (start, end - exclusive)
[10, 20, 30, 40, 50] > array.slice(1, 4) > println()
// Slice from beginning
[10, 20, 30, 40, 50] > array.slice(0, 3) > println()
// Slice to end
[10, 20, 30, 40, 50] > array.slice(2, 5) > println()
println("\n=== Array Dedupe (Remove Duplicates) ===")
// Remove duplicate elements
[1, 2, 2, 3, 3, 3, 4] > array.dedupe() > println()
["apple", "banana", "apple", "cherry", "banana"] > array.dedupe() > println()
println("\n=== Array Range (Generate Sequence) ===")
// Generate range of integers (inclusive)
array.range(1, 5) > println()
array.range(0, 10) > println()
array.range(-3, 3) > println()
println("\n=== Practical Examples ===")
// Stack operations (LIFO)
fn stack_example() {
[] > stack
// Push items
stack > array.push(1) > stack
stack > array.push(2) > stack
stack > array.push(3) > stack
println("Stack after pushes: {0}", stack)
// Pop item
stack > array.pop() > (result array) {
result > get(0) > stack
result > get(1) > (popped int) {
println("Popped: {0}", popped)
}()
}()
println("Stack after pop: {0}", stack)
}()
stack_example()
// Queue operations (FIFO)
fn queue_example() {
[] > queue
// Enqueue (add to end)
queue > array.push("first") > queue
queue > array.push("second") > queue
queue > array.push("third") > queue
println("Queue after enqueues: {0}", queue)
// Dequeue (remove from front)
queue > array.shift() > (result array) {
result > get(0) > queue
result > get(1) > (dequeued string) {
println("Dequeued: {0}", dequeued)
}()
}()
println("Queue after dequeue: {0}", queue)
}()
queue_example()
// Paginating results
fn paginate(items array, page int, page_size int) {
page > mul(page_size) > start
start > add(page_size) > end
// Clamp end to array length
items > len() > total
end > gt?(total) > (exceeded bool) {
exceeded > return?(total)
return(end)
}(int) > end
items > array.slice(start, end) > return()
}(array)
array.range(1, 20) > (items array) {
items > paginate(0, 5) > (page0 array) {
println("Page 0: {0}", page0)
}()
items > paginate(1, 5) > (page1 array) {
println("Page 1: {0}", page1)
}()
items > paginate(2, 5) > (page2 array) {
println("Page 2: {0}", page2)
}()
}()
println("\nAll array examples completed!")
map#
Map (dictionary) operations.
modules/map/operations.bark
View on GitLab// bark Map Module Examples
// Demonstrates map manipulation operations
println("=== Map Get With Default ===")
// Get value with default if key doesn't exist
{"name": "Alice", "age": 30} > person
person > map.get_or("name", "Unknown") > name
println("Name: {name}")
person > map.get_or("email", "no-email@example.com") > email
println("Email: {email}")
println("\n=== Map Delete ===")
// Delete single key
{"a": 1, "b": 2, "c": 3} > map.del("b") > after_del
println("After del(b): {after_del}")
// Delete multiple keys
{"a": 1, "b": 2, "c": 3, "d": 4} > map.del("b", "d") > after_multi_del
println("After del(b, d): {after_multi_del}")
println("\n=== Map Keys ===")
// Get all keys as array
{"name": "Alice", "age": 30, "city": "NYC"} > map.keys() > keys
println("Keys: {keys}")
println("\n=== Map Values ===")
// Get all values as array
{"x": 10, "y": 20, "z": 30} > map.values() > values
println("Values: {values}")
println("\n=== Map Entries ===")
// Get all key-value pairs as array of [key, value] arrays
{"a": 1, "b": 2, "c": 3} > map.entries() > entries
println("Entries: {entries}")
println("\n=== Map Key Checks ===")
{"name": "Alice", "age": 30} > data
// Check if key exists
data > map.key_present?("name") > has_name
println("Has name: {has_name}")
data > map.key_present?("email") > has_email
println("Has email: {has_email}")
// Check if key is absent
data > map.key_absent?("email") > missing_email
println("Missing email: {missing_email}")
println("\n=== Map Merge ===")
// Merge two maps (later values override earlier ones)
{"a": 1, "b": 2} > map.merge({"c": 3, "d": 4}) > merged1
println("Merged: {merged1}")
// Merge with override
{"a": 1, "b": 2} > map.merge({"b": 20, "c": 3}) > merged2
println("Merged with override: {merged2}")
println("\n=== Practical Examples ===")
// Configuration with defaults
fn get_config() {
{"debug": false, "timeout": 30, "retries": 3} > defaults
{"debug": true, "timeout": 60} > overrides
defaults > map.merge(overrides) > return()
}(map)
get_config() > config
println("Config: {config}")
// Building a user record
fn build_user(name string, email string) {
{"name": name, "email": email} > user
// Add admin role if admin email
email > str.ends_with?("@admin.com") > is_admin
user > map.merge({"role": "admin"}) > admin_user
is_admin > return?(admin_user)
return(user)
}(map)
"Alice" > build_user("alice@example.com") > user1
println("User 1: {user1}")
"Bob" > build_user("bob@admin.com") > user2
println("User 2: {user2}")
println("\nAll map examples completed!")
json#
JSON parsing and serialization.
modules/json/serialization.bark
View on GitLab// bark JSON Module Examples
// Demonstrates JSON parsing and serialization
println("=== JSON Stringify ===")
// Convert map to JSON string
{"name": "Alice", "age": 30} > json.stringify() > json_str
println("JSON: {json_str}")
// Convert array to JSON
[1, 2, 3, "four", "five"] > json.stringify() > arr_json
println("Array JSON: {arr_json}")
// Convert nested structure
{"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]} > json.stringify() > nested_json
println("Nested JSON: {nested_json}")
println("\n=== JSON Stringify Pretty ===")
// Pretty print JSON with indentation
{"name": "David", "email": "david@example.com", "roles": ["admin", "user"]} > json.stringify_pretty() > pretty_json
println("Pretty JSON:")
println(pretty_json)
println("\n=== JSON Parse ===")
// Parse JSON string back to map
json_str > json.parse() > (err error, data map) {
err > present?() > return?()
data > get("name") > name
data > get("age") > age
println("Parsed name: {name}")
println("Parsed age: {age}")
}()
println("\n=== Round-trip Example ===")
// Create, stringify, parse, modify, stringify again
{"name": "Bob", "score": 100} > json.stringify() > original
println("Original: {original}")
original > json.parse() > (err error, parsed map) {
err > present?() > return?()
parsed > set("score", 200) > modified
modified > json.stringify() > modified_json
println("Modified: {modified_json}")
}()
println("\n=== Practical Example: API Response ===")
// Simulate API response processing
{"status": "success", "data": {"items": [1, 2, 3]}} > json.stringify() > api_response
api_response > json.parse() > (err error, response map) {
err > present?() > return?()
response > get("status") > status
println("Status: {status}")
response > get("data") > data
data > get("items") > items
items > len() > count
println("Found {count} items")
}()
println("\nAll JSON examples completed!")
file#
File I/O operations.
modules/file/io.bark
View on GitLab// bark File Module Examples
// Demonstrates file I/O operations
println("=== Writing Files ===")
// Write a new file (creates parent directories if needed)
"/tmp/bark_test/hello.txt" > file.write("Hello, bark!\nThis is a test file.\n") > (err map) {
err > absent?() > println?("File written successfully")
err > present?() > println?("Write failed: ", err)
}()
// Write another file
"/tmp/bark_test/data.txt" > file.write("Line 1\nLine 2\nLine 3\n") > (err map) {
err > absent?() > println?("Data file written successfully")
}()
println("\n=== Reading Files ===")
// Read file contents
"/tmp/bark_test/hello.txt" > file.read() > capture(err, content)
err > absent?() > (success bool) {
success > not() > return?()
println("Read file content:")
content > println()
}()
println("\n=== Appending to Files ===")
// Append to existing file
"/tmp/bark_test/data.txt" > file.append("Line 4 (appended)\n") > (err map) {
err > absent?() > println?("Content appended successfully")
}()
// Read to verify append
"/tmp/bark_test/data.txt" > file.read() > capture(err2, content2)
err2 > absent?() > (success bool) {
success > not() > return?()
println("File content after append:")
content2 > println()
}()
println("\n=== Checking File Existence ===")
// Check if files exist
"/tmp/bark_test/hello.txt" > file.exists?() > (exists bool) {
println("hello.txt exists: {exists}")
}()
"/tmp/bark_test/nonexistent.txt" > file.exists?() > (exists bool) {
println("nonexistent.txt exists: {exists}")
}()
// Check if files are absent
"/tmp/bark_test/nonexistent.txt" > file.absent?() > (absent bool) {
println("nonexistent.txt is absent: {absent}")
}()
println("\n=== Getting File Info ===")
// Get file information
"/tmp/bark_test/hello.txt" > file.info() > capture(info_err, info)
info_err > absent?() > (success bool) {
success > not() > return?()
println("File info:")
info > get("size") > (size int) {
println(" Size: {size} bytes")
}()
info > get("modified") > (modified int) {
println(" Modified timestamp: {modified}")
}()
info > get("is_dir") > (is_dir bool) {
println(" Is directory: {is_dir}")
}()
}()
println("\n=== Deleting Files ===")
// Delete a file
"/tmp/bark_test/hello.txt" > file.delete() > (err map) {
err > absent?() > println?("hello.txt deleted successfully")
}()
// Verify deletion
"/tmp/bark_test/hello.txt" > file.absent?() > (absent bool) {
println("hello.txt is now absent: {absent}")
}()
println("\n=== Practical Examples ===")
// Copy file by reading and writing
fn copy_file(src string, dest string) {
src > file.read() > capture(read_err, content)
read_err > present?() > return?(read_err)
dest > file.write(content) > return()
}(map)
// Create source file
"/tmp/bark_test/original.txt" > file.write("Original content") > (err map) {
err > absent?() > return?()
}()
// Copy it
"/tmp/bark_test/original.txt" > copy_file("/tmp/bark_test/copy.txt") > (err map) {
err > absent?() > println?("File copied successfully")
}()
// Verify copy
"/tmp/bark_test/copy.txt" > file.read() > capture(copy_err, copy_content)
copy_err > absent?() > (success bool) {
success > not() > return?()
println("Copied content: {copy_content}")
}()
// Clean up remaining test files
"/tmp/bark_test/data.txt" > file.delete() > (err map) {}()
"/tmp/bark_test/original.txt" > file.delete() > (err map) {}()
"/tmp/bark_test/copy.txt" > file.delete() > (err map) {}()
println("\nAll file I/O examples completed!")
dir#
Directory operations.
modules/dir/operations.bark
View on GitLab// bark Dir Module Examples
// Demonstrates directory operations
println("=== Checking Directory Existence ===")
// Check if directories exist
"/tmp" > dir.exists?() > (exists bool) {
println("/tmp exists: {exists}")
}()
"/nonexistent_dir_xyz" > dir.exists?() > (exists bool) {
println("/nonexistent_dir_xyz exists: {exists}")
}()
// Check if directories are absent
"/nonexistent_dir_xyz" > dir.absent?() > (absent bool) {
println("/nonexistent_dir_xyz is absent: {absent}")
}()
"/tmp" > dir.absent?() > (absent bool) {
println("/tmp is absent: {absent}")
}()
println("\n=== Listing Directory Contents ===")
// Create some test files for listing
"/tmp/bark_dir_test/file1.txt" > file.write("content 1") > (err map) {}()
"/tmp/bark_dir_test/file2.txt" > file.write("content 2") > (err map) {}()
"/tmp/bark_dir_test/file3.txt" > file.write("content 3") > (err map) {}()
// List directory contents
"/tmp/bark_dir_test" > dir.list() > capture(err, files)
err > absent?() > (success bool) {
success > not() > return?()
println("Files in /tmp/bark_dir_test:")
files > each((arr array, i int) {
arr > get(i) > (file string) {
println(" {i}: {file}")
}()
}())
}()
// Listing a non-existent directory returns an error
"/nonexistent_directory" > dir.list() > capture(err2, files2)
err2 > present?() > (has_error bool) {
has_error > not() > return?()
println("\nListing non-existent directory returns error (expected)")
}()
println("\n=== Distinguishing Files from Directories ===")
// Create a subdirectory for testing
"/tmp/bark_dir_test/subdir/nested.txt" > file.write("nested") > (err map) {}()
// Check if path is a directory vs file
"/tmp/bark_dir_test" > dir.exists?() > (is_dir bool) {
println("/tmp/bark_dir_test is a directory: {is_dir}")
}()
"/tmp/bark_dir_test/file1.txt" > dir.exists?() > (is_dir bool) {
println("/tmp/bark_dir_test/file1.txt is a directory: {is_dir}")
}()
"/tmp/bark_dir_test/file1.txt" > file.exists?() > (is_file bool) {
println("/tmp/bark_dir_test/file1.txt is a file: {is_file}")
}()
println("\n=== Practical Examples ===")
// Count files in a directory
fn count_files(path string) {
path > dir.list() > capture(err, files)
err > present?() > return?(0)
files > len() > return()
}(int)
"/tmp/bark_dir_test" > count_files() > (count int) {
println("Number of items in /tmp/bark_dir_test: {count}")
}()
// Find files with specific extension (simplified pattern matching)
fn has_txt_extension(filename string) {
filename > str.ends_with?(".txt") > return()
}(bool)
"/tmp/bark_dir_test" > dir.list() > capture(list_err, file_list)
list_err > absent?() > (success bool) {
success > not() > return?()
println("\nFiles with .txt extension:")
file_list > each((arr array, i int) {
arr > get(i) > (file string) {
file > has_txt_extension() > (is_txt bool) {
is_txt > println?(" {file}")
}()
}()
}())
}()
// Clean up test files
"/tmp/bark_dir_test/file1.txt" > file.delete() > (err map) {}()
"/tmp/bark_dir_test/file2.txt" > file.delete() > (err map) {}()
"/tmp/bark_dir_test/file3.txt" > file.delete() > (err map) {}()
"/tmp/bark_dir_test/subdir/nested.txt" > file.delete() > (err map) {}()
println("\nAll directory operation examples completed!")
time#
Date and time operations.
modules/time/datetime.bark
View on GitLab// bark Time Module Examples
// Demonstrates date and time operations
println("=== Getting Current Time ===")
// Get current Unix timestamp (seconds)
time.now() > (now int) {
println("Current timestamp (seconds): {now}")
}()
// Get current Unix timestamp (milliseconds)
time.now_ms() > (now_ms int) {
println("Current timestamp (milliseconds): {now_ms}")
}()
println("\n=== Formatting Timestamps ===")
// Format using strftime-style placeholders
time.now() > (ts int) {
// Full date and time
ts > time.format("%Y-%m-%d %H:%M:%S") > (formatted string) {
println("Full datetime: {formatted}")
}()
// Just the date
ts > time.format("%Y-%m-%d") > (date string) {
println("Date only: {date}")
}()
// Just the time
ts > time.format("%H:%M:%S") > (time_str string) {
println("Time only: {time_str}")
}()
// Human-readable format
ts > time.format("%B %d, %Y") > (human string) {
println("Human readable: {human}")
}()
// With weekday
ts > time.format("%A, %B %d, %Y") > (with_day string) {
println("With weekday: {with_day}")
}()
// ISO 8601 shortcuts
ts > time.format("%F") > (iso_date string) {
println("ISO 8601 date: {iso_date}")
}()
ts > time.format("%F %T") > (iso_full string) {
println("ISO 8601 full: {iso_full}")
}()
}()
println("\n=== ISO 8601 Formatting ===")
// Format as ISO 8601 (RFC3339)
time.now() > (ts int) {
ts > time.format_iso8601() > (iso string) {
println("ISO 8601 format: {iso}")
}()
}()
println("\n=== Parsing Date Strings ===")
// Parse a date string with custom format
"2024-06-15" > time.parse("%Y-%m-%d") > capture(err, ts)
err > absent?() > (success bool) {
success > not() > return?()
println("Parsed '2024-06-15' to timestamp: {ts}")
// Format it back to verify
ts > time.format("%B %d, %Y") > (formatted string) {
println("Formatted back: {formatted}")
}()
}()
// Parse date with time
"2024-12-25 14:30:00" > time.parse("%Y-%m-%d %H:%M:%S") > capture(err2, ts2)
err2 > absent?() > (success bool) {
success > not() > return?()
println("Parsed '2024-12-25 14:30:00' to timestamp: {ts2}")
}()
println("\n=== Parsing ISO 8601 ===")
// Parse ISO 8601 format
"2024-07-04T12:00:00Z" > time.parse_iso8601() > capture(err3, ts3)
err3 > absent?() > (success bool) {
success > not() > return?()
println("Parsed ISO 8601 to timestamp: {ts3}")
ts3 > time.format("%Y-%m-%d %H:%M:%S") > (formatted string) {
println("Formatted: {formatted}")
}()
}()
println("\n=== Practical Examples ===")
// Calculate time difference
fn time_diff_days(ts1 int, ts2 int) {
ts2 > sub(ts1) > div(86400) > return()
}(int)
// Parse two dates and calculate difference
"2024-01-01" > time.parse("%Y-%m-%d") > capture(err5, jan1)
err5 > present?() > return?()
"2024-12-31" > time.parse("%Y-%m-%d") > capture(err6, dec31)
err6 > present?() > return?()
jan1 > time_diff_days(dec31) > (days int) {
println("Days between Jan 1 and Dec 31, 2024: {days}")
}()
// Add days to a timestamp
fn add_days(ts int, days int) {
days > mul(86400) > add(ts) > return()
}(int)
"2024-06-01" > time.parse("%Y-%m-%d") > capture(err7, june1)
err7 > present?() > return?()
june1 > add_days(30) > (future int) {
future > time.format("%Y-%m-%d") > (date string) {
println("30 days after June 1, 2024: {date}")
}()
}()
// Format timestamps for logging
fn log_message(msg string) {
time.now() > (ts int) {
ts > time.format("[%Y-%m-%d %H:%M:%S]") > (timestamp string) {
str.concat(timestamp, " ", msg) > println()
}()
}()
}()
"Application started" > log_message()
"Processing complete" > log_message()
// Convert UTC to EST (UTC-5)
fn utc_to_est(utc_ts int) {
utc_ts > sub(18000) > return() // 5 hours = 18000 seconds
}(int)
time.now() > (utc_ts int) {
utc_ts > time.format("%H:%M:%S") > (utc_time string) {
println("\nUTC time: {utc_time}")
}()
utc_ts > utc_to_est() > (est_ts int) {
est_ts > time.format("%H:%M:%S") > (est_time string) {
println("EST time (UTC-5): {est_time}")
}()
}()
}()
println("\nAll time/datetime examples completed!")
env#
Environment variable operations.
modules/env/variables.bark
View on GitLab// bark Env Module Examples
// Demonstrates environment variable operations
println("=== Getting Environment Variables ===")
// Get common environment variables
env.get("HOME") > (home string) {
println("HOME: {home}")
}()
env.get("USER") > (user string) {
println("USER: {user}")
}()
env.get("PATH") > (path string) {
// Just show first 60 chars of PATH for readability
path > len() > gt?(60) > (long bool) {
long > not() > (short bool) {
short > println?("PATH: {path}")
}()
long > println?("PATH: (truncated for display)")
}()
}()
println("\n=== Getting with Default Values ===")
// Get with default if not set
env.get_or("DATABASE_URL", "localhost:5432") > (db_url string) {
println("DATABASE_URL: {db_url}")
}()
env.get_or("LOG_LEVEL", "info") > (log_level string) {
println("LOG_LEVEL: {log_level}")
}()
env.get_or("NONEXISTENT_VAR", "default_value") > (val string) {
println("NONEXISTENT_VAR: {val}")
}()
println("\n=== Checking Variable Existence ===")
// Check if variables exist
env.present?("HOME") > (exists bool) {
println("HOME is present: {exists}")
}()
env.present?("NONEXISTENT_VAR_XYZ") > (exists bool) {
println("NONEXISTENT_VAR_XYZ is present: {exists}")
}()
// Check if variables are absent
env.absent?("NONEXISTENT_VAR_XYZ") > (absent bool) {
println("NONEXISTENT_VAR_XYZ is absent: {absent}")
}()
env.absent?("USER") > (absent bool) {
println("USER is absent: {absent}")
}()
println("\n=== Conditional Configuration ===")
// Use environment variables for conditional logic
fn get_environment() {
env.get_or("BARK_ENV", "development") > return()
}(string)
get_environment() > (bark_env string) {
println("Running in environment: {bark_env}")
}()
// Check for required variables
fn require_env(var_name string) {
var_name > env.present?() > (exists bool) {
exists > not() > (missing bool) {
"Required env var not set" > err() > (error_val map) {
missing > return?(error_val)
}()
env.get(var_name) > return()
}()
}()
}(string)
// Example: Check for optional debug flag
env.get_or("DEBUG", "false") > (debug string) {
debug > eq?("true") > (is_debug bool) {
is_debug > println?("Debug mode enabled")
is_debug > not() > println?("Debug mode disabled")
}()
}()
println("\n=== Listing Environment Variables ===")
// Get all environment variables (showing just a few)
env.all() > (all_vars map) {
all_vars > map.keys() > (keys array) {
keys > len() > (count int) {
println("Total environment variables: {count}")
}()
}()
// Show a few common ones if they exist
all_vars > map.key_present?("SHELL") > (has_shell bool) {
has_shell > not() > return?()
all_vars > get("SHELL") > (shell string) {
println("SHELL from all(): {shell}")
}()
}()
}()
println("\n=== Practical Examples ===")
// Build configuration from environment
fn get_config() {
env.get_or("APP_HOST", "localhost") > (host string) {
env.get_or("APP_PORT", "8080") > (port string) {
env.get_or("APP_ENV", "development") > (env_val string) {
env.get_or("APP_DEBUG", "false") > (debug string) {
{"host": host, "port": port, "env": env_val, "debug": debug} > return()
}()
}()
}()
}()
}(map)
get_config() > (config map) {
println("Application configuration:")
config > get("host") > (host string) {
println(" Host: {host}")
}()
config > get("port") > (port string) {
println(" Port: {port}")
}()
config > get("env") > (env_val string) {
println(" Environment: {env_val}")
}()
config > get("debug") > (debug string) {
println(" Debug: {debug}")
}()
}()
// Check for production environment
fn is_production() {
env.get_or("APP_ENV", "development") > eq?("production") > return()
}(bool)
is_production() > (prod bool) {
prod > println?("WARNING: Running in production mode")
prod > not() > println?("Running in non-production mode")
}()
println("\nAll environment variable examples completed!")
http#
HTTP client operations.
modules/http/requests.bark
View on GitLab// JSON + Security Features Example
// Demonstrates JSON processing, input validation, and sanitization
println("=== JSON Operations ===")
{} > set("name", "Alice") > set("age", 30) > set("role", "developer") > person
person > json.stringify() > json_str
println("JSON Output: {0}", json_str)
json_str > json.parse() > (err error, parsed map) {
parsed > get("name") > name_val
println(name_val)
}()
println()
println("=== HTML Sanitization (XSS Prevention) ===")
fn sanitize_html(text string) {
text >
str.replace("&", "&") >
str.replace("<", "<") >
str.replace(">", ">") >
str.replace("\"", """) >
str.replace("'", "'") >
return()
}(string)
"<script>alert('XSS')</script>" > sanitize_html() > safe
println("Input: <script>alert('XSS')</script>")
println("Output: {0}", safe)
println()
println("=== Base64 Encoding ===")
"Secret Message!" > base64.encode() > encoded
println("Encoded: {0}", encoded)
encoded > base64.decode() > (err error, decoded string) {
println("Decoded: {0}", decoded)
}()
println()
println("=== URL Encoding ===")
"hello world & friends" > url.encode() > url_enc
println("Encoded: {0}", url_enc)
url_enc > url.decode() > (err error, url_dec string) {
println("Decoded: {0}", url_dec)
}()
println()
println("=== Regex Matching ===")
"user@example.com" > regex.match?(`^[a-z]+@[a-z]+\.[a-z]+$`) > eq?(true) > email_valid
println(email_valid)
"Order #12345 costs $99" > regex.find_all(`\d+`) > numbers
numbers > len() > num_count
println("Found {0} numbers", num_count)
println()
println("=== Complete! ===")
url#
URL encoding, decoding, and parsing.
modules/url/encoding.bark
View on GitLab// bark URL Module Examples
// Demonstrates URL encoding, decoding, and parsing
println("=== URL Encoding ===")
// Encode strings for use in URLs
"hello world" > url.encode() > (encoded string) {
println("'hello world' encoded: {encoded}")
}()
"user@example.com" > url.encode() > (encoded string) {
println("'user@example.com' encoded: {encoded}")
}()
"key=value&foo=bar" > url.encode() > (encoded string) {
println("'key=value&foo=bar' encoded: {encoded}")
}()
// Special characters
"hello/world?query=test#anchor" > url.encode() > (encoded string) {
println("With special chars: {encoded}")
}()
println("\n=== URL Decoding ===")
// Decode URL-encoded strings
"hello+world" > url.decode() > capture(err, decoded)
err > absent?() > (success bool) {
success > not() > return?()
println("'hello+world' decoded: {decoded}")
}()
"user%40example.com" > url.decode() > capture(err2, decoded2)
err2 > absent?() > (success bool) {
success > not() > return?()
println("'user%40example.com' decoded: {decoded2}")
}()
"key%3Dvalue%26foo%3Dbar" > url.decode() > capture(err3, decoded3)
err3 > absent?() > (success bool) {
success > not() > return?()
println("'key%3Dvalue%26foo%3Dbar' decoded: {decoded3}")
}()
println("\n=== Roundtrip Encoding ===")
// Encode and decode to verify roundtrip
"Special chars: /\\?&=#" > url.encode() > (encoded string) {
println("Original: Special chars: /\\?&=#")
println("Encoded: {encoded}")
encoded > url.decode() > capture(err, decoded)
err > absent?() > (success bool) {
success > not() > return?()
println("Decoded: {decoded}")
}()
}()
println("\n=== URL Parsing ===")
// Parse a complete URL into components
"https://example.com:8080/path/to/resource?query=value&foo=bar#section" > url.parse() > capture(err4, parts)
err4 > absent?() > (success bool) {
success > not() > return?()
println("Parsed URL components:")
parts > get("scheme") > (scheme string) {
println(" Scheme: {scheme}")
}()
parts > get("host") > (host string) {
println(" Host: {host}")
}()
parts > get("path") > (path string) {
println(" Path: {path}")
}()
parts > get("query") > (query string) {
println(" Query: {query}")
}()
parts > get("fragment") > (fragment string) {
println(" Fragment: {fragment}")
}()
}()
// Parse a simpler URL
"http://api.example.com/v1/users" > url.parse() > capture(err5, parts2)
err5 > absent?() > (success bool) {
success > not() > return?()
println("\nParsed simple URL:")
parts2 > get("scheme") > (scheme string) {
println(" Scheme: {scheme}")
}()
parts2 > get("host") > (host string) {
println(" Host: {host}")
}()
parts2 > get("path") > (path string) {
println(" Path: {path}")
}()
}()
println("\n=== Practical Examples ===")
// Build a query string from parameters
fn build_query_param(key string, value string) {
key > url.encode() > (enc_key string) {
value > url.encode() > (enc_val string) {
str.concat(enc_key, "=", enc_val) > return()
}()
}()
}(string)
"search" > build_query_param("hello world") > (param1 string) {
"page" > build_query_param("1") > (param2 string) {
str.concat("?", param1, "&", param2) > (query string) {
println("Built query string: {query}")
}()
}()
}()
// Extract and process query parameters
fn extract_host(full_url string) {
full_url > url.parse() > capture(err, parts)
err > present?() > return?("")
parts > get("host") > return()
}(string)
"https://api.github.com/repos/user/project" > extract_host() > (host string) {
println("Extracted host: {host}")
}()
// Safely build a URL with user input
fn safe_url_param(base_url string, param_name string, user_input string) {
user_input > url.encode() > (safe_input string) {
str.concat(base_url, "?", param_name, "=", safe_input) > return()
}()
}(string)
"https://search.example.com" > safe_url_param("q", "user's query & special <chars>") > (safe_url string) {
println("Safe URL with user input: {safe_url}")
}()
println("\nAll URL encoding examples completed!")
base64#
Base64 encoding and decoding.
modules/base64/encoding.bark
View on GitLab// bark Base64 Module Examples
// Demonstrates base64 encoding and decoding
println("=== Base64 Encoding ===")
// Encode a simple string
"Hello, World!" > base64.encode() > encoded1
println("Encoded: {encoded1}")
// Encode longer text
"The quick brown fox jumps over the lazy dog" > base64.encode() > encoded2
println("Encoded: {encoded2}")
println("\n=== Base64 Decoding ===")
// Decode a base64 string
"SGVsbG8sIFdvcmxkIQ==" > base64.decode() > (err error, decoded string) {
err > present?() > return?()
println("Decoded: {decoded}")
}()
println("\n=== Round-Trip Encoding ===")
// Encode then decode to verify
"Secret message 123!" > original
original > base64.encode() > encoded
println("Original: {original}")
println("Encoded: {encoded}")
encoded > base64.decode() > (err error, decoded string) {
err > present?() > return?()
println("Decoded: {decoded}")
original > eq?(decoded) > match
println("Match: {match}")
}()
println("\n=== Note on Invalid Base64 ===")
// Invalid base64 returns an error and stops the chain
// In production, validate input before decoding
println("Invalid base64 input would return an error")
println("\n=== Practical Examples ===")
// Encode JSON data for URL-safe transmission
fn encode_json_data(data map) {
data > json.stringify() > base64.encode() > return()
}(string)
{"user_id": 123, "token": "abc"} > encode_json_data() > encoded_json
println("Encoded JSON: {encoded_json}")
// Simple obfuscation (not encryption!)
fn obfuscate(text string) {
text > base64.encode() > return()
}(string)
fn deobfuscate(encoded string) {
encoded > base64.decode() > (err error, text string) {
err > present?() > return?("")
return(text)
}()
}(string)
"my-api-key-12345" > obfuscate() > hidden
println("Obfuscated: {hidden}")
hidden > deobfuscate() > revealed
println("Revealed: {revealed}")
println("\nAll base64 examples completed!")
regex#
Regular expression operations.
modules/regex/patterns.bark
View on GitLab// bark Regex Module Examples
// Demonstrates regular expression operations
println("=== Basic Pattern Matching ===")
// Check if pattern matches
"hello world" > regex.match?("world") > println()
"hello world" > regex.match?("foo") > println()
// Case-sensitive matching
"Hello World" > regex.match?("hello") > println()
"Hello World" > regex.match?("Hello") > println()
// Match any character with dot
"cat" > regex.match?("c.t") > println()
"cut" > regex.match?("c.t") > println()
"ct" > regex.match?("c.t") > println()
println("\n=== Character Classes ===")
// Match digits
"abc123def" > regex.match?("[0-9]") > println()
"abcdef" > regex.match?("[0-9]") > println()
// Match letters
"123abc456" > regex.match?("[a-zA-Z]") > println()
"123456" > regex.match?("[a-zA-Z]") > println()
// Match word characters
"hello_world" > regex.match?("\\w+") > println()
println("\n=== Quantifiers ===")
// One or more
"goooal" > regex.match?("go+al") > println()
"gal" > regex.match?("go+al") > println()
// Zero or more
"goooal" > regex.match?("go*al") > println()
"gal" > regex.match?("go*al") > println()
// Optional (zero or one)
"color" > regex.match?("colou?r") > println()
"colour" > regex.match?("colou?r") > println()
// Exact count
"aaa" > regex.match?("a{3}") > println()
"aa" > regex.match?("a{3}") > println()
println("\n=== Anchors ===")
// Start of string
"hello world" > regex.match?("^hello") > println()
"say hello" > regex.match?("^hello") > println()
// End of string
"hello world" > regex.match?("world$") > println()
"world hello" > regex.match?("world$") > println()
println("\n=== Finding Matches ===")
// Find first match
"The year 2024 was great" > regex.find("[0-9]+") > println()
// Find with no match returns empty string
"no numbers here" > regex.find("[0-9]+") > println()
println("\n=== Finding All Matches ===")
// Find all occurrences
"a1b2c3d4e5" > regex.find_all("[0-9]") > println()
// Find all words
"hello world foo bar" > regex.find_all("\\w+") > println()
// Find all email-like patterns
"Contact john@example.com or jane@test.org" > regex.find_all("[\\w.]+@[\\w.]+") > println()
println("\n=== Replacement ===")
// Replace all occurrences
"hello world" > regex.replace("o", "0") > println()
// Replace digits with X
"abc123def456" > regex.replace("[0-9]", "X") > println()
// Replace whitespace with underscore
"hello world foo bar" > regex.replace("\\s+", "_") > println()
// Remove all non-alphanumeric
"Hello, World! 123" > regex.replace("[^a-zA-Z0-9]", "") > println()
println("\n=== Splitting by Pattern ===")
// Split by whitespace
"hello world foo" > regex.split("\\s+") > println()
// Split by comma and optional whitespace
"a, b,c, d" > regex.split(",\\s*") > println()
// Split by any punctuation
"hello.world,foo;bar" > regex.split("[.,;]") > println()
println("\n=== Practical Examples ===")
// Validate email format (simplified)
fn is_valid_email?(email string) {
email > regex.match?("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$") > return()
}(bool)
"user@example.com" > is_valid_email?() > println()
"invalid-email" > is_valid_email?() > println()
"user@sub.example.org" > is_valid_email?() > println()
// Extract numbers from text
fn extract_numbers(text string) {
text > regex.find_all("[0-9]+") > return()
}(array)
"Order #123 has 5 items totaling $99" > extract_numbers() > println()
// Sanitize input (remove special characters)
fn sanitize(input string) {
input > regex.replace("[^a-zA-Z0-9 ]", "") > str.trim() > return()
}(string)
"Hello <script>alert('xss')</script> World!" > sanitize() > println()
// Parse log line
fn parse_log_line(line string) {
// Extract timestamp, level, and message from "[2024-01-15 10:30:00] [INFO] Message"
line > regex.find("\\[([0-9-]+ [0-9:]+)\\]") > timestamp
line > regex.find("\\[(INFO|WARN|ERROR)\\]") > level
line > regex.replace("\\[[^\\]]+\\]\\s*", "") > message
{"timestamp": timestamp, "level": level, "message": message} > return()
}(map)
"[2024-01-15 10:30:00] [INFO] Application started" > parse_log_line() > println()
// Mask sensitive data
fn mask_credit_card(text string) {
text > regex.replace("[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}", "****-****-****-****") > return()
}(string)
"Card: 1234-5678-9012-3456" > mask_credit_card() > println()
// Convert camelCase to snake_case
fn to_snake_case(camel string) {
camel > regex.replace("([a-z])([A-Z])", "${1}_${2}") > str.lower() > return()
}(string)
"helloWorld" > to_snake_case() > println()
"getUserById" > to_snake_case() > println()
println("\nAll regex examples completed!")
crypto#
Cryptographic operations including hashing, encryption, and secure random generation.
modules/crypto/hashing.bark
View on GitLab// bark Cryptography Module Examples
// Demonstrates password hashing, encryption, HMAC, and secure random generation
println("=== Password Hashing with bcrypt ===")
// Hash a password with bcrypt (cost 12, ~250ms)
crypto.bcrypt_hash("secret123") > (err map, hash string) {
err > present?() > return?("bcrypt hash failed")
println("Bcrypt hash: {0}", hash)
// Verify correct password
crypto.bcrypt_verify("secret123", hash) > (valid bool) {
println("Verify correct password: {0}", valid)
}()
// Verify wrong password
crypto.bcrypt_verify("wrong", hash) > (valid bool) {
println("Verify wrong password: {0}", valid)
}()
}()
println("\n=== Password Hashing with Argon2id (Recommended) ===")
// Hash a password with Argon2id (more secure than bcrypt)
crypto.argon2_hash("my_password") > (err2 map, hash2 string) {
err2 > present?() > return?("argon2 hash failed")
println("Argon2id hash: {0}", hash2)
// Verify correct password
crypto.argon2_verify("my_password", hash2) > (valid bool) {
println("Verify correct password: {0}", valid)
}()
// Verify wrong password
crypto.argon2_verify("wrong_password", hash2) > (valid bool) {
println("Verify wrong password: {0}", valid)
}()
}()
println("\n=== AES-256-GCM Encryption ===")
// Use a fixed 32-byte key for this example
// In production, derive keys from passwords using PBKDF2 or similar
"12345678901234567890123456789012" > (key string) {
println("Plaintext: secret message")
// Encrypt the message
crypto.aes_encrypt("secret message", key) > (err3 map, ciphertext string) {
err3 > present?() > return?("encryption failed")
println("Ciphertext (hex): {0}", ciphertext)
// Decrypt the message
crypto.aes_decrypt(ciphertext, key) > (err4 map, plaintext string) {
err4 > present?() > return?("decryption failed")
println("Decrypted: {0}", plaintext)
}()
}()
}()
println("\n=== HMAC Signatures ===")
// Create HMAC-SHA256 signature
crypto.hmac_sha256("important message", "secret_key") > (signature string) {
println("HMAC-SHA256 signature: {0}", signature)
// Verify the signature
crypto.hmac_verify("important message", signature, "secret_key") > (valid bool) {
println("Signature valid: {0}", valid)
}()
// Try verifying with wrong message
crypto.hmac_verify("tampered message", signature, "secret_key") > (valid bool) {
println("Tampered message valid: {0}", valid)
}()
}()
println("\n=== HMAC-SHA512 (Stronger) ===")
crypto.hmac_sha512("api webhook payload", "webhook_secret") > (signature string) {
println("HMAC-SHA512 signature: {0}", signature)
// Verify the signature
crypto.hmac_verify("api webhook payload", signature, "webhook_secret") > (valid bool) {
println("Signature valid: {0}", valid)
}()
}()
println("\n=== Secure Random Generation ===")
// Generate random bytes (for keys, salts, etc.)
crypto.random_bytes(16) > (err5 map, random_hex string) {
err5 > present?() > return?("random bytes generation failed")
println("Random 16 bytes (hex): {0}", random_hex)
}()
// Generate random string (for tokens, session IDs, etc.)
crypto.random_string(32) > (err6 map, random_str string) {
err6 > present?() > return?("random string generation failed")
println("Random 32-char string: {0}", random_str)
}()
println("\n=== Hash Functions (for checksums/fingerprints) ===")
// SHA-256 hash (for file integrity, fingerprints)
crypto.sha256("hello world") > (hash string) {
println("SHA-256('hello world'): {0}", hash)
}()
// SHA-512 hash (stronger)
crypto.sha512("hello world") > (hash string) {
println("SHA-512('hello world'): {0}", hash)
}()
println("\nAll cryptography examples completed!")
security#
Input validation and sanitization for security.
modules/security/validation.bark
View on GitLab// Security & Input Validation Example
// Demonstrates comprehensive input sanitization and security features
println("=== SQL Injection Prevention ===")
// Unsafe user input
"Robert'; DROP TABLE users;--" > security.sql_escape() > safe_sql
println("Safe SQL: {0}", safe_sql)
println("Expected: Robert''; DROP TABLE users;--")
println()
// ===================================================================
println("=== Command Injection Prevention ===")
// Check if commands are safe
"ls -la" > security.safe_command?() > is_safe1
println("'ls -la' is safe: {0}", is_safe1)
"rm -rf /" > security.safe_command?() > is_safe2
println("'rm -rf /' is safe: {0}", is_safe2)
"echo hello; rm -rf /" > security.safe_command?() > is_safe3
println("'echo hello; rm -rf /' is safe: {0}", is_safe3)
// Escape shell metacharacters
"file; rm -rf /" > security.shell_escape() > safe_shell
println("Escaped: {0}", safe_shell)
println()
// ===================================================================
println("=== Path Traversal Prevention ===")
// Safe path
"data/users.txt" > security.sanitize_path("/var/app") > (err error, safe_path1 string) {
println("✓ Safe path: {0}", safe_path1)
}()
// Attempt path traversal - security.sanitize_path will return error for this
println("✗ Dangerous paths like '../../etc/passwd' are blocked by security.sanitize_path")
println()
// ===================================================================
println("=== Input Validation ===")
// Alphanumeric check
"user123" > str.alphanumeric?() > is_alnum1
println("'user123' is alphanumeric: {0}", is_alnum1)
"user@123" > str.alphanumeric?() > is_alnum2
println("'user@123' is alphanumeric: {0}", is_alnum2)
// Email validation
"user@example.com" > security.email?() > is_email1
println("'user@example.com' is email: {0}", is_email1)
"not-an-email" > security.email?() > is_email2
println("'not-an-email' is email: {0}", is_email2)
// URL validation
"https://example.com/path" > security.url?() > is_url1
println("'https://example.com/path' is URL: {0}", is_url1)
"javascript:alert('xss')" > security.url?() > is_url2
println("'javascript:alert('xss')' is URL: {0}", is_url2)
println()
// ===================================================================
println("=== XSS Prevention ===")
"<script>alert('XSS')</script>" > security.html_escape() > escaped_html
println("HTML Escaped: {0}", escaped_html)
"<img src=x onerror='alert(1)'>" > security.strip_tags() > stripped
println("Tags Stripped: {0}", stripped)
println()
// ===================================================================
println("=== Content Security Policy ===")
security.generate_nonce() > nonce
println("CSP Nonce: {0}", nonce)
println("Use in header: Content-Security-Policy: script-src 'nonce-{0}'", nonce)
println()
// ===================================================================
println("=== Rate Limiting Helper ===")
"192.168.1.100" > security.hash_key() > ip_hash
println("IP Hash for rate limiting: {0}", ip_hash)
"user@example.com" > security.hash_key() > user_hash
println("User Hash for rate limiting: {0}", user_hash)
println()
// ===================================================================
println("=== Comprehensive Input Validation Function ===")
fn validate_user_input(input string) {
// Prepare error messages
err("Input too short") > err_short
err("Input too long") > err_long
err("Null byte detected") > err_null
err("Script tag detected") > err_script
err("SQL injection attempt") > err_sql
err("Command separator detected") > err_sep
err("Command chaining detected") > err_chain
err("Command substitution detected") > err_subst
// Check length
input > len() > input_len
input_len > lt?(1) > eq?(true) > return?(err_short)
input_len > gt?(1000) > eq?(true) > return?(err_long)
// Check for null bytes (potential injection)
input > includes?("\x00") > eq?(true) > return?(err_null)
// Check for script tags
input > str.lower() > includes?("<script") > eq?(true) > return?(err_script)
// Check for SQL injection patterns
input > str.lower() > includes?("drop table") > eq?(true) > return?(err_sql)
input > str.lower() > includes?("'; ") > eq?(true) > return?(err_sql)
// Check for command injection
input > includes?(";") > eq?(true) > return?(err_sep)
input > includes?("&&") > eq?(true) > return?(err_chain)
input > includes?("`") > eq?(true) > return?(err_subst)
return({})
}(error)
println("✓ Safe input accepted: Hello, safe input!")
println("✗ XSS attempt blocked: <script>alert('xss')</script>")
println("✗ SQL injection blocked: Robert'; DROP TABLE users;--")
println("✗ Command injection blocked: echo hello; rm -rf /")
println()
println("=== Security Validation Complete! ===")
sql#
SQLite database operations.
Note: SQL support requires building with
-tags sql.
modules/sql/sqlite.bark
View on GitLab// bark SQL Module Examples
// Demonstrates SQLite database operations
println("=== Opening SQLite Database ===")
// Open an in-memory SQLite database
sql.open("sqlite", ":memory:") > capture(conn_err, conn)
conn_err > present?() > (failed bool) {
failed > not() > return?()
println("Failed to open database: ", conn_err)
return()
}()
println("Connected to SQLite database")
println("\n=== Creating Tables ===")
// Create a users table
conn > sql.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)") > capture(create_err, _)
create_err > absent?() > println?("Created users table")
println("\n=== Inserting Data ===")
// Insert some users using parameterized queries (SQL injection safe)
conn > sql.exec("INSERT INTO users (name, email) VALUES (?, ?)", ["Alice", "alice@example.com"]) > capture(e1, affected1)
e1 > absent?() > println?("Inserted Alice, affected rows: {affected1}")
conn > sql.exec("INSERT INTO users (name, email) VALUES (?, ?)", ["Bob", "bob@example.com"]) > capture(e2, affected2)
e2 > absent?() > println?("Inserted Bob, affected rows: {affected2}")
conn > sql.exec("INSERT INTO users (name, email) VALUES (?, ?)", ["Charlie", "charlie@example.com"]) > capture(e3, affected3)
e3 > absent?() > println?("Inserted Charlie, affected rows: {affected3}")
println("\n=== Querying Data ===")
// Query all users
conn > sql.query("SELECT id, name, email FROM users ORDER BY id") > capture(query_err, rows)
query_err > absent?() > (success bool) {
success > not() > return?()
println("All users:")
rows > each((arr array, i int) {
arr > get(i) > (row map) {
row > get("id") > (id int) {
row > get("name") > (name string) {
row > get("email") > (email string) {
println(" {id}: {name} <{email}>")
}()
}()
}()
}()
}())
}()
// Query with parameters
conn > sql.query("SELECT * FROM users WHERE name = ?", ["Alice"]) > capture(alice_err, alice_rows)
alice_err > absent?() > (success bool) {
success > not() > return?()
println("\nFiltered query (Alice):")
alice_rows > get(0) > (row map) {
row > get("email") > (email string) {
println(" Alice's email: {email}")
}()
}()
}()
println("\n=== Updating Data ===")
// Update a user
conn > sql.exec("UPDATE users SET email = ? WHERE name = ?", ["bob.smith@example.com", "Bob"]) > capture(update_err, updated)
update_err > absent?() > println?("Updated Bob's email, affected rows: {updated}")
// Verify update
conn > sql.query("SELECT email FROM users WHERE name = ?", ["Bob"]) > capture(bob_err, bob_rows)
bob_err > absent?() > (success bool) {
success > not() > return?()
bob_rows > get(0) > get("email") > (email string) {
println("Bob's new email: {email}")
}()
}()
println("\n=== Transactions ===")
// Start a transaction
conn > sql.begin() > capture(tx_err, tx)
tx_err > present?() > (failed bool) {
failed > not() > return?()
println("Failed to start transaction: ", tx_err)
return()
}()
println("Transaction started")
// Insert within transaction
tx > sql.exec("INSERT INTO users (name, email) VALUES (?, ?)", ["Dave", "dave@example.com"]) > capture(dave_err, _)
dave_err > absent?() > println?("Inserted Dave (in transaction)")
// Commit transaction
tx > sql.commit() > capture(commit_err, _)
commit_err > absent?() > println?("Transaction committed")
// Verify Dave was inserted
conn > sql.query("SELECT COUNT(*) as count FROM users") > capture(count_err, count_rows)
count_err > absent?() > (success bool) {
success > not() > return?()
count_rows > get(0) > get("count") > (count int) {
println("Total users after transaction: {count}")
}()
}()
println("\n=== Rollback Example ===")
// Start another transaction
conn > sql.begin() > capture(tx2_err, tx2)
tx2_err > absent?() > (success bool) {
success > not() > return?()
// Insert a user
tx2 > sql.exec("INSERT INTO users (name, email) VALUES (?, ?)", ["Eve", "eve@example.com"]) > capture(eve_err, _)
eve_err > absent?() > println?("Inserted Eve (in transaction, will rollback)")
// Rollback instead of commit
tx2 > sql.rollback() > capture(rollback_err, _)
rollback_err > absent?() > println?("Transaction rolled back")
}()
// Verify Eve was NOT inserted
conn > sql.query("SELECT COUNT(*) as count FROM users WHERE name = ?", ["Eve"]) > capture(eve_count_err, eve_count_rows)
eve_count_err > absent?() > (success bool) {
success > not() > return?()
eve_count_rows > get(0) > get("count") > (count int) {
println("Eve records after rollback: {count}")
}()
}()
println("\n=== Deleting Data ===")
// Delete a user
conn > sql.exec("DELETE FROM users WHERE name = ?", ["Charlie"]) > capture(del_err, deleted)
del_err > absent?() > println?("Deleted Charlie, affected rows: {deleted}")
// Final count
conn > sql.query("SELECT COUNT(*) as count FROM users") > capture(final_err, final_rows)
final_err > absent?() > (success bool) {
success > not() > return?()
final_rows > get(0) > get("count") > (count int) {
println("Final user count: {count}")
}()
}()
println("\n=== Closing Connection ===")
// Close the database connection
conn > sql.close() > capture(close_err, _)
close_err > absent?() > println?("Database connection closed")
println("\nAll SQL examples completed!")