Skip to content

arrays Module

The arrays module provides a comprehensive set of functions for array manipulation.

Functions

length(array)

Returns the number of elements in an array.

Parameters: - array: An array.

Returns: - (integer, error): The length of the array.

Example:

Array Length
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var len, _ = arrays.length(a)
fmt.Println(len) // Output: 3


contains(array, value)

Checks if a value exists in an array.

Parameters: - array: An array. - value: The value to search for.

Returns: - (boolean, error): true if the value is found, false otherwise.

Example:

Check Contains
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var found, _ = arrays.contains(a, 2)
fmt.Println(found) // Output: true


index(array, value)

Returns the index of the first occurrence of a value in an array.

Parameters: - array: An array. - value: The value to search for.

Returns: - (integer, error): The index of the value, or -1 if not found.

Example:

Find Index
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3, 2]
var i, _ = arrays.index(a, 2)
fmt.Println(i) // Output: 1


push(array, value) or push(array, value, index)

Adds an element to an array and returns the new array. Has two forms: - push(array, value) - Appends value to the end - push(array, value, index) - Inserts value at the specified index

Parameters: - array: An array. - value: The element to add. - index (optional): The index where to insert the element.

Returns: - (array, error): The new array.

Example:

Append Element
package main
import fmt
import arrays

var a = [1, 2, 3]

// Append to end
var b, _ = arrays.push(a, 4)
fmt.Println(b) // Output: [1, 2, 3, 4]

// Insert at index 1
var c, _ = arrays.push(a, 99, 1)
fmt.Println(c) // Output: [1, 99, 2, 3]


pop(array, index)

Removes an element at a specific index from an array and returns the new array and the removed element.

Parameters: - array: An array. - index: The index of the element to remove (integer).

Returns: - On success: (array, any, None): The new array, the removed element, and no error. - On error: (None, error): None and the error message.

Note: This function has inconsistent return values - success returns 3 values, error returns 2 values.

Example:

Pop Element
package main
import fmt
import arrays

var a = [1, 2, 3, 4, 5]
var newArray, removedElement, err = arrays.pop(a, 2)
if err != None {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Original:", a)        // Output: [1, 2, 3, 4, 5] (unchanged)
    fmt.Println("New array:", newArray) // Output: [1, 2, 4, 5]
    fmt.Println("Removed:", removedElement) // Output: 3
}

// To remove the last element:
var length, _ = arrays.length(a)
var newArray2, lastElement, _ = arrays.pop(a, length - 1)
fmt.Println("Last element:", lastElement) // Output: 5


replace(array, index, value)

Replaces an element at a specific index in an array.

Parameters: - array: An array. - index: The index of the element to replace. - value: The new value.

Returns: - (array, error): The modified array.

Example:

Replace Element
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var b, _ = arrays.replace(a, 1, 42)
fmt.Println(b) // Output: [1, 42, 3]


delete(array, index)

Removes an element at a specific index in an array.

Parameters: - array: An array. - index: The index of the element to remove.

Returns: - (array, error): The modified array.

Example:

Remove at Index
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var b, _ = arrays.delete(a, 1)
fmt.Println(b) // Output: [1, 3]


copy(array)

Creates a shallow copy of an array.

Parameters: - array: An array.

Returns: - (array, error): A new array that is a copy of the original.

Example:

Copy Array
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var b, _ = arrays.copy(a)
fmt.Println(b) // Output: [1, 2, 3]


clear(array)

Removes all elements from an array.

Parameters: - array: An array.

Returns: - (array, error): The empty array.

Example:

Clear Array
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var b, _ = arrays.clear(a)
fmt.Println(b) // Output: []


equal(array1, array2)

Compares two arrays for equality.

Parameters: - array1: The first array. - array2: The second array.

Returns: - (boolean, error): true if the arrays are equal, false otherwise.

Example:

Compare Arrays
package main
import fmt
import arrays

var a = [1, 2, 3]
var b = [1, 2, 3]
var c = [4, 5, 6]

var eq1, _ = arrays.equal(a, b)
fmt.Println(eq1) // Output: true

var eq2, _ = arrays.equal(a, c)
fmt.Println(eq2) // Output: false


sort(array, order)

Sorts the elements of an array according to the specified order. Currently supports integers only.

Parameters: - array: An array of integers (mixed arrays will cause an error). - order: A string specifying sort order - "asc", "ascending", "desc", or "descending".

Returns: - (array, error): A new sorted array, or error if array contains mixed types.

Example:

Sort Array
package main
import fmt
import arrays

var a = [3, 1, 4, 1, 5]
var ascending, _ = arrays.sort(a, "asc")
fmt.Println(ascending) // Output: [1, 1, 3, 4, 5]

var descending, _ = arrays.sort(a, "desc")
fmt.Println(descending) // Output: [5, 4, 3, 1, 1]

// Mixed arrays will cause an error
var mixed = [1, "hello", 3]
var _, err = arrays.sort(mixed, "asc")
// Error: "arrays.sort cannot sort mixed arrays: element at index 1 is STRING, expected INTEGER"


memory(array)

Returns the memory usage of an array.

Parameters: - array: An array.

Returns: - (integer, error): The memory usage in bytes.

Example:

Memory Usage
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var mem, _ = arrays.memory(a)
fmt.Println(mem) 


tojson(array)

Converts an array to a JSON string.

Parameters: - array: An array.

Returns: - (string, error): The JSON string representation of the array.

Example:

Convert to JSON
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var json, _ = arrays.tojson(a)
fmt.Println(json) // Output: [1,2,3]


tostring(array)

Converts an array to a string representation.

Parameters: - array: An array.

Returns: - (string, error): The string representation of the array.

Example:

Convert to String
1
2
3
4
5
6
7
package main
import fmt
import arrays

var a = [1, 2, 3]
var s, _ = arrays.tostring(a)
fmt.Println(s) // Output: [1, 2, 3]


Sorting

Harneet supports non-mutating array sorting with natural order and custom comparators. You can access these via the arrays module aliases shown below. These aliases delegate to the global built-ins under the hood.

arrays.SortFn(array)

Returns a new array sorted in natural order.

Behavior: - Numbers are sorted in ascending order. - Strings are sorted lexicographically. - Errors on mixed element types or unsupported element types. - Non-mutating: the original array is not changed. - Returns a tuple: (array, error).

Example:

Slice Array
package main
import fmt, arrays

// Sort integers
var nums = [5, 2, 9, 1, 5, 6]
var sortedNums, err1 = arrays.SortFn(nums)
if err1 != None {
    fmt.Println("SortFn error:", err1)
} else {
    fmt.Println("sorted ints:", sortedNums) // [1, 2, 5, 5, 6, 9]
}

// Sort strings
var words = ["pear", "apple", "banana"]
var sortedWords, err2 = arrays.SortFn(words)
fmt.Println(sortedWords) // [apple, banana, pear]

arrays.SortBy(array, less function(T, T) bool)

Returns a new array sorted using a user-supplied comparator function. The sort is stable.

Behavior: - Comparator signature must match the array element type: function(T, T) bool. - Returns a tuple: (array, error). - Non-mutating: the original array is not changed. - Stable sorting preserves the relative order of equal elements.

Examples:

Stable Sort
package main
import fmt, arrays

// Sort integers by absolute value
var signed = [-3, 1, -2, 4]
var byAbs, err3 = arrays.SortBy(signed, function(a int, b int) bool {
    var absA = a
    if a < 0 {
        absA = -a
    }
    var absB = b
    if b < 0 {
        absB = -b
    }
    return absA < absB
})
fmt.Println(byAbs) // [1, -2, -3, 4]

// Sort strings by length (stable)
var fruits = ["fig", "apple", "pear", "plum", "banana"]
var byLen, err4 = arrays.SortBy(fruits, function(a string, b string) bool { 
    return len(a) < len(b) 
})

Slicing

Harneet supports Go-like slicing on arrays, typed arrays, and strings using the s[a:b] syntax. Four forms are available:

  • s[a:b]
  • s[:b]
  • s[a:]
  • s[:]

Rules and semantics

  • Sliceable types: arrays, typed arrays, and strings.
  • Indices: a and b must be integers. The type checker validates this at compile time.
  • Bounds: indices are clamped to the valid range [0, len(s)].
  • Order: if a > b, the result is an empty slice [].
  • Half-open: a is inclusive, b is exclusive.
  • Typed arrays: slicing preserves the array's element type (e.g., int[]).
  • Strings: result is a string. Slicing is currently byte-based.

Examples

Array Examples
package main
import fmt

// Arrays
var arr = [10, 20, 30, 40, 50]
fmt.Println(arr[:])    // [10, 20, 30, 40, 50]
fmt.Println(arr[:3])   // [10, 20, 30]
fmt.Println(arr[2:])   // [30, 40, 50]
fmt.Println(arr[1:4])  // [20, 30, 40]

// Bounds handling
fmt.Println(arr[-5:2]) // [10, 20]  (clamped)
fmt.Println(arr[3:99]) // [40, 50]  (clamped)
fmt.Println(arr[4:2])  // []        (start > end)

// Typed arrays
var tarr = int[5]{1, 2, 3, 4, 5}
var tmid = tarr[1:4]
fmt.Println(tmid)      // int[3]{2, 3, 4}

// Strings (byte-based slicing)
var s = "abcdef"
fmt.Println(s[0:3])    // "abc"
fmt.Println(s[2:])     // "cdef"
fmt.Println(s[:])      // "abcdef"

Notes on strings:

  • Current implementation slices by byte index. If your strings contain multi-byte UTF-8 characters, ensure indices align with character boundaries to avoid splitting a character. Rune-aware slicing may be introduced in the future.