Skip to content

Comprehensive Language Examples

This page provides a collection of examples that demonstrate various features of the Harneet programming language.

Array Operations

Array Operations
package main
import fmt, arrays

var nums = [1, 2, 3, 4, 5]
var names = ["Alice", "Bob", "Charlie"]


var mixedArray = [1, "Amit", "Chandeep"]

// Array operations
var length, _ = arrays.length(nums)
var contains, _ = arrays.contains(names, "Alice")
var newArray, _ = arrays.push(nums, 6)
var sortedNums, _ = arrays.sort([3, 1, 4, 1, 5])

fmt.Println("Length:", length)
fmt.Println("Contains Alice:", contains)
fmt.Println("New array:", newArray)
fmt.Println("Sorted:", sortedNums)
fmt.Println("Mixed Array : ", mixedArray)

Concurrency Patterns

This section provides comprehensive examples using do, await(task), and sleep(ms) for practical concurrency.

Parallel Map (pmap)

Parallel map with do/await
package main
import fmt
import arrays

function square(n int) int {
    sleep(20) // simulate work
    return n * n
}

var values = [1, 2, 3, 4, 5]

// Spawn tasks
var tasks = []
for v in values {
    var newTasks, _ = arrays.push(tasks, do square(v))
    tasks = newTasks
}

// Gather results
var results = []
for t in tasks {
    var newResults, _ = arrays.push(results, await(t))
    results = newResults
}

fmt.Println("pmap squares:", results) // [1, 4, 9, 16, 25]

Concurrency Limit (Batching)

Run tasks in batches to limit concurrency when you don’t need fine-grained completion order.

Batch-limited parallel map
package main
import fmt
import arrays

function pmapLimited(values array, f function(any) any, limit int) array {
    var out = []
    var i = 0
    for i < len(values) {
        // Make a batch up to 'limit'
        var batch = []
        var j = 0
        for j < limit and (i+j) < len(values) {
            var v = values[i+j]
            var batch2, _ = arrays.push(batch, do f(v))
            batch = batch2
            j = j + 1
        }

        // Drain the batch
        for t in batch {
            var out2, _ = arrays.push(out, await(t))
            out = out2
        }

        i = i + j
    }
    return out
}

function slowInc(x any) any { sleep(30); return x + 1 }

var data = [1,2,3,4,5,6,7,8]
var res = pmapLimited(data, slowInc, 3)
fmt.Println("limited concurrency result:", res)

Pipeline (Staged Concurrency)

Process values through multiple stages, synchronizing between stages.

Staged pipeline with barriers
package main
import fmt
import arrays

function stage1(x int) int { sleep(20); return x * 2 }
function stage2(x int) int { sleep(20); return x + 10 }

var input = [1,2,3,4]

// Stage 1
var t1 = []
for v in input { var t1b, _ = arrays.push(t1, do stage1(v)); t1 = t1b }
var r1 = []
for t in t1 { var r1b, _ = arrays.push(r1, await(t)); r1 = r1b }

// Stage 2
var t2 = []
for v in r1 { var t2b, _ = arrays.push(t2, do stage2(v)); t2 = t2b }
var r2 = []
for t in t2 { var r2b, _ = arrays.push(r2, await(t)); r2 = r2b }

fmt.Println("pipeline output:", r2) // For [1,2,3,4]: [(1*2)+10,...] => [12,14,16,18]

Retry with Exponential Backoff

Implement robust retries using sleep(); errors flow through regular return values.

Retry with exponential backoff
package main
import fmt
import errors

// Simulated flaky function that sometimes fails
function maybeFetch(id int) string {
    if id % 2 == 1 {
        fmt.Println("Fetch failed for id:", id)
        return ""
    }
    sleep(20)
    return fmt.Sprintf("item-%d", id)
}

function fetchWithRetry(id, maxRetries int) string {
    var backoff = 50
    var attempt = 0
    for attempt <= maxRetries {
        var task = do maybeFetch(id)
        var result = await(task)
        if result != "" {
            fmt.Println("Success on attempt:", attempt)
            return result
        }
        if attempt == maxRetries {
            fmt.Println("Max retries reached")
            return ""
        }
        fmt.Println("Retrying after", backoff, "ms...")
        sleep(backoff)
        backoff = backoff * 2
        attempt = attempt + 1
    }
    return ""
}

var result = fetchWithRetry(4, 3)
if result != "" {
    fmt.Println("Final result:", result)
} else {
    fmt.Println("Failed to fetch after retries")
}

Staggered Completion and Ordering

Await order controls when you observe task results.

Staggered completion
package main
import fmt

function work(name string, ms int) string { sleep(ms); return name }

var tA = do work("A", 200)
var tB = do work("B", 20)

// Awaiting A first blocks longer
var a = await(tA)
var b = await(tB)
fmt.Printf("ordered await: %s %s\n", a, b)

// Alternatively, await B first to proceed sooner
var tA2 = do work("A", 200)
var tB2 = do work("B", 20)
var b2 = await(tB2)
var a2 = await(tA2)
fmt.Printf("reordered await: %s %s\n", a2, b2)

Exec Examples

This section provides examples of using the exec module to launch applications and run commands on macOS.

Open Terminal.app

Open Terminal.app
package main
import exec
import fmt

var code, err = exec.RunCode("open", "-a", "Terminal")
if err != None {
    fmt.Println("open Terminal failed:", err)
} else {
    fmt.Println("Terminal launched, exit code:", code)
}

Open Terminal at current directory

Open Terminal at current directory
package main
import exec
import fmt

var code, err = exec.RunCode("open", "-a", "Terminal", ".")
if err != None {
    fmt.Println("open Terminal at . failed:", err)
} else {
    fmt.Println("Terminal opened at current directory")
}

Open iTerm (if installed)

Open iTerm
1
2
3
4
5
6
7
8
package main
import exec
import fmt

var code, err = exec.RunCode("open", "-a", "iTerm")
if err != None {
    fmt.Println("open iTerm failed:", err)
}

Run a command in Terminal via AppleScript

Run Terminal command via AppleScript
package main
import exec
import fmt

var script = "osascript -e 'tell application \"Terminal\" to do script \"echo hello from Harneet; ls -la; exit\"'"

var code, err = exec.RunCode("/bin/sh", "-c", script)
if err != None {
    fmt.Println("osascript failed:", err)
} else {
    fmt.Println("Terminal launched to run command")
}

ShellStdout: run commands within current process

ShellStdout example
package main
import exec
import fmt

var out, err = exec.ShellStdout("echo shell-in-process; uname -a")
if err != None {
    fmt.Println("ShellStdout error:", err)
} else {
    fmt.Println("stdout:", out)
}

RunWithOptions: set env and working directory

RunWithOptions with env and cwd
package main
import exec
import fmt

var args = ["-c", "pwd; echo $MYVAR; ls -1 | head -5"]
var envs = ["MYVAR=hello_from_exec"]

var out, err = exec.RunWithOptionsStdout("/bin/sh", args, envs, "/tmp")
if err != None {
    fmt.Println("RunWithOptions error:", err)
} else {
    fmt.Println("stdout:", out)
}

JSON Processing

JSON processing
package main
import json, fmt

var data = ["apple", "banana", "cherry"]
var jsonString, err = json.Marshal(data)
if err != None {
    fmt.Println("Marshal error:", err)
    return
}

fmt.Println("JSON:", jsonString)

var parsed, parseErr = json.Unmarshal(jsonString)
if parseErr != None {
    fmt.Println("Parse error:", parseErr)
    return
}

fmt.Println("Parsed back:", parsed)

File Operations

File Operations
package main
import file, fmt

var content = "Hello, World!\nThis is Harneet!"
var _, writeErr = file.Write("example.txt", content)
if writeErr != None {
    fmt.Println("Write error:", writeErr)
    return
}

var readContent, readErr = file.Read("example.txt")
if readErr != None {
    fmt.Println("Read error:", readErr)
    return
}

fmt.Println("File content:", readContent)

Advanced Function Usage

Functions Usage
package main
import fmt

// Regular function with multiple returns
function processData(data string) (string, string, bool) {
    if data == "" {
        return "", "empty data", false
    }
    return "HELLO WORLD", "", true
}

// Arrow function for simple operations
var multiply = (a, b) => a * b
var greet = name => "Hello, " + name

// Using functions
var result, errorMsg, isSuccess = processData("hello world")
if isSuccess {
    fmt.Println("Result:", result)
} else {
    fmt.Println("Error:", errorMsg)
}

fmt.Println("Product:", multiply(6, 7))
fmt.Println("Greeting:", greet("Alice"))

File I/O Examples

This section provides comprehensive examples of file input/output operations.

Reading, Writing, and Appending Files

File I/O examples
package main
import fmt
import file
import os

// Create a new file and write content to it
var fileName = "test_file.txt"
var initialContent = "Hello from Harneet!"
var _, writeErr = file.Write(fileName, initialContent)
if writeErr != None {
    fmt.Println("Error writing to file:", writeErr)
    return
}
fmt.Println("Successfully wrote to", fileName)

// Read the content of the file
var content, readErr = file.Read(fileName)
if readErr != None {
    fmt.Println("Error reading file:", readErr)
    return
}
fmt.Println("Content of", fileName, ":", content)

// Append content to the file
var appendedContent = "\nThis is a new line."
var _, appendErr = file.Append(fileName, appendedContent)
if appendErr != None {
    fmt.Println("Error appending to file:", appendErr)
    return
}
fmt.Println("Successfully appended to", fileName)

// Read the file again to see the appended content
var newContent, readAgainErr = file.Read(fileName)
if readAgainErr != None {
    fmt.Println("Error reading file again:", readAgainErr)
    return
}
fmt.Println("New content of", fileName, ":", newContent)

// Clean up the created file
os.Remove(fileName)

Datetime Examples

This section provides comprehensive examples of date and time operations.

Timezone Conversions and Formatting

DateTime examples
package main
import fmt
import datetime

// Get the current time in UTC
var nowUTC, _ = datetime.Now()
fmt.Println("Current UTC time (Unix):", nowUTC)

// Format the UTC time
var formattedUTC, _ = datetime.Format(nowUTC, "RFC3339")
fmt.Println("Formatted UTC time:", formattedUTC)

// Convert to a different timezone
var newYorkTime, _ = datetime.ConvertTZ(nowUTC, "UTC", "America/New_York")
var formattedNY, _ = datetime.Format(newYorkTime, "Kitchen")
fmt.Println("New York time:", formattedNY)

// Get the system's timezone
var systemTZ, _ = datetime.GetSystemTZ()
fmt.Println("System timezone:", systemTZ)

Cron Job Scheduling and Management

Cron Job Scheduling
package main
import fmt
import datetime

// Schedule cron jobs
var job1, err1 = datetime.ScheduleCron("daily_backup", "0 2 * * *")  // Daily at 2 AM
if err1 != None {
    fmt.Println("ScheduleCron failed:", err1)
} else {
    fmt.Println("Scheduled daily backup:", job1)
}

var job2, err2 = datetime.ScheduleCron("weekly_report", "0 9 * * 1")  // Monday at 9 AM
if err2 != None {
    fmt.Println("ScheduleCron failed:", err2)
} else {
    fmt.Println("Scheduled weekly report:", job2)
}

// List active cron jobs
var jobs, listErr = datetime.ListCronJobs()
if listErr != None {
    fmt.Println("ListCronJobs failed:", listErr)
} else {
    fmt.Println("Active cron jobs:", jobs)
}

// Validate cron expressions
var validCron, _ = datetime.IsValidCron("0 9 * * 1")
fmt.Println("'0 9 * * 1' is valid:", validCron)

// Calculate next execution times
var now, _ = datetime.Now()
var nextMonday, _ = datetime.NextCronExecution("0 9 * * 1", now)
fmt.Println("Next Monday 9AM timestamp:", nextMonday)

// Use pre-defined cron expressions
var hourly, _ = datetime.Hourly()
fmt.Println("Hourly cron expression:", hourly)

var daily, _ = datetime.Daily()
fmt.Println("Daily cron expression:", daily)

// Stop a cron job
var _, stopErr = datetime.StopCron("daily_backup")
if stopErr != None {
    fmt.Println("StopCron failed:", stopErr)
} else {
    fmt.Println("Stopped daily backup job")
}

// List jobs after stopping one
var jobsAfter, _ = datetime.ListCronJobs()
fmt.Println("Active cron jobs after stopping:", jobsAfter)

// Sleep for a few seconds to demonstrate timing
fmt.Println("Sleeping for 3 seconds...")
var _, _ = datetime.Sleep(3)
fmt.Println("Done sleeping!")

Logging Examples

This section provides comprehensive examples of logging.

Logging at Different Levels

Logging in Harneet
1
2
3
4
5
6
7
package main
import log

log.Debug("This is a debug message.")
log.Info("This is an info message.")
log.Warn("This is a warning message.")
log.Error("This is an error message.")

Setting Log Level

Setting up log levels
package main
import log

// Set the log level to WARN
log.SetLevel("WARN")

log.Debug("This message will not be printed.")
log.Info("This message will also not be printed.")
log.Warn("This is a warning message that will be printed.")
log.Error("This is an error message that will also be printed.")

// Reset log level to default (DEBUG)
log.SetLevel("DEBUG")

Redirecting Log Output to a File

Redirecting log outputs
package main
import log
import file
import os

var logFile = "app.log"

// Redirect log output to a file
log.SetOutput(logFile)

log.Info("This message will be written to the log file.")

// Reset log output to standard output
log.SetOutput("")

// Read the log file to verify the content
var logContent, _ = file.Read(logFile)
fmt.Println("Log file content:", logContent)

// Clean up the log file
os.Remove(logFile)

OS Module Examples

This section provides comprehensive examples of interacting with the operating system.

Device Information and Drive Information

Getting Device Information
package main
import fmt
import os

// List all connected devices
var devices, err = os.ListDevices()
if err != None {
    fmt.Println("Error listing devices:", err)
} else {
    fmt.Println("Connected Devices:", devices)
}

// Get detailed information about a specific device (example: first device in the list)
if devices != None and len(devices) > 0 {
    var firstDevice = devices[0]
    var deviceInfo, err2 = os.GetDeviceInfo(firstDevice)
    if err2 != None {
        fmt.Println("Error getting device info for", firstDevice, ":", err2)
    } else {
        fmt.Println("Device Info for", firstDevice, ":", deviceInfo)
    }
} else {
    fmt.Println("No devices found to get detailed information.")
}