Advanced Function Features
Harneet functions support several advanced features that make them powerful and flexible.
Multiple Return Values
A function can return multiple values. This is particularly useful for returning a result and an error, which is a common pattern in Harneet.
| Function returning multiple return values |
|---|
| package main
import fmt
function divide(a float64, b float64) (float64, string) {
if b == 0 {
return 0.0, "division by zero"
}
return a / b, ""
}
var result, err = divide(10, 2)
if err != "" {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result) // Output: Result: 5
}
var result2, err2 = divide(10, 0)
if err2 != "" {
fmt.Println("Error:", err2) // Output: Error: division by zero
} else {
fmt.Println("Result:", result2)
}
|
Closures and Function Returns
Functions in Harneet are closures, which means they can access variables from their enclosing scope. This enables powerful patterns when returning functions.
Basic Closure
| Closure example in Harneet |
|---|
| package main
import fmt
function outer() function() {
var x = 10
function inner() {
fmt.Println(x)
}
return inner
}
var closure = outer()
closure() // Output: 10
|
Closure with State Capture
| Closure capturing state |
|---|
| package main
import fmt
function createCounter(start int) function() int {
var count = start
function increment() int {
count = count + 1
return count
}
return increment
}
var counter1 = createCounter(0)
var counter2 = createCounter(100)
fmt.Println(counter1()) // Output: 1
fmt.Println(counter1()) // Output: 2
fmt.Println(counter2()) // Output: 101
fmt.Println(counter1()) // Output: 3
|
Factory Functions
| Factory function pattern |
|---|
| package main
import fmt
function createValidator(minLength int) function(string) bool {
function validate(input string) bool {
// Note: In a real implementation, you'd have string length function
// This is a simplified example
return input != "" // Simplified validation
}
return validate
}
var passwordValidator = createValidator(8)
var usernameValidator = createValidator(3)
fmt.Println(passwordValidator("secret")) // Output: true
fmt.Println(usernameValidator("")) // Output: false
|
First-Class Functions
Functions are first-class citizens in Harneet, which means they can be treated like any other value. They can be assigned to variables, passed as arguments to other functions, and returned from functions.
| Functions are first class |
|---|
| package main
import fmt
function apply(f function(int) int, value int) int {
return f(value)
}
function double(x int) int {
return x * 2
}
var result = apply(double, 5)
fmt.Println(result) // Output: 10
|
Assigning functions to variables
Like in most other languages, you can assign functions to a variable. The following code demonstrates that
| Assigning functions to variables |
|---|
| package main
import fmt
function greet() {
fmt.Println("Hello World")
}
var x = greet // here we assign the function to a variable
x() //now we call it
|