Skip to content

[Enhancement] Comprehensive Arithmetic Logic Improvements for String, Array, and Dictionary Operations #104

@victorKariuki

Description

@victorKariuki

Describe the feature

This feature introduces native support for arithmetic and logical operations in the Nuru programming language on Strings, Arrays, and Dictionaries. It aims to expand the expressive power and utility of Nuru's syntax by enabling operations such as concatenation, repetition, slicing, merging, and comparison across these core data types using intuitive, symbolic operators.

By standardising these operators, the feature enhances code readability, promotes data-oriented programming, and lays the foundation for high-level abstractions commonly required in real-world applications such as text processing, list manipulation, and key-value data transformations.

Key Goals:

  • Make Strings, Arrays, and Dictionaries first-class operands in Nuru’s arithmetic and logic system.
  • Align operator behavior with both common programming idioms and Swahili-influenced semantics.
  • Enable cleaner, more declarative syntax for common tasks such as merging dictionaries, appending arrays, or comparing structured data.

Example Usage:

"Habari" + " Dunia"         // "Habari Dunia"
[1, 2, 3] * 2               // [1, 2, 3, 1, 2, 3]
{a: 1} + {b: 2}             // {a: 1, b: 2}
"Hello" == "hello"         // false (case-sensitive by default)

Use Case

As a developer building applications in Nuru, I'm often frustrated when performing basic operations on Strings, Arrays, or Dictionaries, which requires writing verbose helper functions or resorting to workarounds. Trivial tasks in other modern languages—like comparing two arrays, merging dictionaries with conflict resolution, or splitting and formatting strings—become cumbersome and inconsistent in Nuru's current syntax.

For example:

  • Comparing two nested dictionaries requires writing a custom recursive function.
  • Removing an element from an array or a substring from a string has no direct operator support.
  • Performing set operations (like intersection or difference) on arrays or dictionaries is not possible using symbolic notation.
  • Null handling requires manual checks, adding noise to otherwise simple expressions.

This lack of operator support:

  • Breaks the flow of coding and thinking
  • Increases the cognitive load when switching between numeric and non-numeric operations
  • Reduces the expressive power and elegance of the language

Proposed Solution

To implement comprehensive arithmetic logic improvements for Strings, Arrays, and Dictionaries in Nuru, we propose the introduction of consistent, polymorphic operator overloading and null-safe extensions within the language’s existing arithmetic engine.


⚙️ Operator Overloading Framework

Introduce a generalized operator dispatch system in the interpreter/compiler core that allows symbolic operators (like +, -, *, /, <, ??, etc.) to resolve based on operand type pairs (e.g., Array + Array, String - String, Dictionary * Dictionary).

Each operator will delegate to a registered handler for the operand types involved.


🔤 1. String Enhancements

Operator Operation Example
<, >, <=, >= Lexicographical comparison "a" < "z" → true
  • | Remove substring | "hello" - "l" → "heo"
    / | Split by substring | "a,b,c" / "," → ["a", "b", "c"]
    % | Template formatting | "Hello, %s!" % "Don" → "Hello, Don!"
  • | Contains (reused) | "data" * "a" → true
    ** | Regex-like pattern match | "name" ** "[a-z]+" → true

🧪 Prototype:

name ?? "Anonymous"     # returns fallback
user.profile?.email     # null-safe access (future)

🔩 Reference Implementation Strategy

  1. Operator Registry Module
    Define a central registry for overloadable operators:

    register_operator("+", "Array", "Array", array_concat)
    register_operator("==", "Dictionary", "Dictionary", dict_equal)
    
  2. Dynamic Dispatch Engine
    Use pattern matching or method resolution (e.g., multimethods) to delegate to correct operator logic.

  3. AST Transformation (Compiler)
    Extend the abstract syntax tree to include type information and allow operator dispatch nodes for overloaded symbols.

  4. Type Inference & Checking
    During parsing or runtime, validate operand compatibility and provide Swahili-language error suggestions if mismatched.


📘 Inspired By

  • Python's rich operator overloading for strings, lists, dicts

  • Kotlin’s null-safe operator model (?., ?:, ==)

  • JavaScript’s flexible object manipulation (ES6+)

  • Lua’s metatable-based operator extensions


Other Information

🔁 Alternative Solutions Considered

  1. Custom Functions Instead of Operators
    Initially, we considered relying solely on built-in or user-defined functions (e.g., remove_substring(str, part) or dict_intersect(a, b)). While functional, this approach burdens the developer with verbosity and obscures the intention behind simple expressions.

  2. Metaprogramming via Macros (Deferred)
    A future extension could allow user-defined operator overloads via macros or metatables. However, this requires a stable runtime reflection and type system, which may complicate the initial language simplicity goal.

  3. Lisp-style DSL for Data Structures
    We also explored defining a DSL layer for manipulating collections. However, this would impose an unnatural paradigm shift for most users familiar with Python/JavaScript-like syntax.


📉 Pain Points (Context for Need)

  • Current limitations force verbose, manual type-checking or loops for simple tasks like merging dicts or subtracting array elements.
  • Inelegant alternatives break the rhythm of expressive coding — a pain point especially for new developers or educational contexts where Nuru is expected to be intuitive.
  • The language's identity as “simple, expressive, and localizable” is undermined when such common tasks require convoluted logic.

⚠️ Stack Trace / Errors (Simulated Examples)

Example of a confusing error due to lack of polymorphism:

"hello" - "l"
# Error: Operator '-' not supported between String and String

Confuses the developer who expects behavior similar to string subtraction or filtering.


🔗 Related Issues / Inspiration


📈 Forward Compatibility

This proposal opens the door to future features such as:

  • User-defined operators or overrides
  • Domain-specific language constructs for data wrangling
  • In-language natural language representations (Swahili/Amharic syntax sugar)

Acknowledgements

  • I may be able to implement this feature request
  • This feature might incur a breaking change

Version used

victorKariuki@c9fc13e

Environment details (OS name and version, etc.)

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions