Data Structures

Data Structures


Arrays store ordered collections of values. They're the most common data structure in Ruchy.

Creating Arrays

Test Coverage: ✅ tests/lang_comp/data_structures/arrays.rs

Try It in the Notebook

Expected Output: [85, 92, 78, 95, 88]

Accessing Elements

Use square brackets with zero-based index:

Expected Output: "apple"

Expected Output: "banana"

Expected Output: "cherry"

Negative Indices

Expected Output: "cherry" (last item)

Expected Output: "banana" (second to last)

Array Methods

len() - Length

Expected Output: 5

push() - Add to End

Expected Output: [1, 2, 3, 4]

pop() - Remove from End

Expected Output: 4, [1, 2, 3]

append() - Combine Arrays

Expected Output: [1, 2, 3, 4]

contains() - Check Membership

Expected Output: true, false

Iteration

For Loop

Expected Output: 15

With Index

Common Patterns

Sum

Filter

Map

Find

Slicing

Multi-Dimensional Arrays

Iterate Matrix

Array Comparison

Best Practices

✅ Use Descriptive Names

✅ Check Length Before Access

Summary

Feature Status: WORKING
Test Coverage: 100%
Mutation Score: 95%

Arrays are ordered collections with zero-based indexing. Use them for lists of similar items.

Key Takeaways:

  • Zero-based indexing
  • Methods: len(), push(), pop(), append(), contains()
  • Iterate with for loops
  • Slicing with [start..end]
  • Can be multi-dimensional

← Previous: Function Definitions | Next: Tuples →


Tuples are fixed-size ordered collections that can hold values of different types. They're perfect for grouping related data.

Creating Tuples

Test Coverage: ✅ tests/lang_comp/data_structures/tuples.rs

Try It in the Notebook

Expected Output: (100, 200, 300)

Accessing Elements

Use zero-based indexing with dot notation:

Expected Output: 10, 20

Multi-Type Tuples

Expected Output: "Error", 404, false

Tuple Destructuring

Unpack tuple values into variables:

Expected Output: 10, 20

Partial Destructuring

Expected Output: 1, 3

Common Patterns

Swap Variables

Expected Output: 20, 10

Return Multiple Values

Expected Output: (3, 2), 3, 2

Coordinate Pairs

Expected Output: (0, 0) -> 0, (10, 20) -> 22.36, (30, 40) -> 50

Tuples vs Arrays

Feature Tuple Array
Size Fixed at creation Can grow/shrink
Types Mixed types allowed Typically same type
Access By position (.0, .1) By index ([0], [1])
Mutation Elements can change Elements can change
Use Case Related but different data Collection of similar items

Nested Tuples

Expected Output: (1, 2), 1, 4

Destructuring Nested Tuples

Expected Output: 10, 40

Tuple Iteration

Expected Output: 15

Note: Tuples don't have built-in iteration. Convert to array if needed.

Common Use Cases

Configuration

Expected Output: Server: localhost:8080 (SSL: true)

State Tracking

Expected Output: Fetched result at 1234567890

Min/Max Pairs

Expected Output: 2, 9

Tuple Methods

Length (Compile-Time)

Note: Tuple size is determined at compile time, not runtime.

Best Practices

✅ Use Descriptive Destructuring

✅ Keep Tuples Small

✅ Use Tuples for Temporary Grouping

✅ Destructure at Function Boundaries

Tuple Comparison

Expected Output: true, false, true, true

Unit Type

The empty tuple () is called the "unit type":

Expected Output: Done, ()

Use Case: Functions that don't return meaningful values return ().

Summary

Feature Status: WORKING
Test Coverage: 100%
Mutation Score: 97%

Tuples are fixed-size collections for grouping related but differently-typed data. Use them for temporary grouping, multiple return values, and coordinate pairs.

Key Takeaways:

  • Fixed size, mixed types
  • Access via .0, .1, .2
  • Destructuring with let (a, b) = tuple
  • Perfect for function return values
  • Keep tuples small (2-4 elements)
  • Use structs for larger, named data

← Previous: Arrays | Next: Objects/Maps →


Objects (also called maps or dictionaries) store key-value pairs. They're perfect for structured data with named fields.

Creating Objects

Test Coverage: ✅ tests/lang_comp/data_structures/objects.rs

Try It in the Notebook

Expected Output: {id: 1, username: "alice", email: "alice@example.com"}

Accessing Fields

Use dot notation or bracket notation:

Expected Output: "Alice", 30

Dynamic Field Access

Expected Output: 10

Modifying Objects

Update Existing Fields

Expected Output: {name: "Alice", age: 31}

Add New Fields

Expected Output: {x: 10, y: 20}

Delete Fields

Expected Output: {a: 1, c: 3}

Object Methods

keys() - Get All Keys

Expected Output: ["name", "age", "active"]

values() - Get All Values

Expected Output: [10, 20, 30]

has_key() - Check Key Existence

Expected Output: true, false

len() - Number of Fields

Expected Output: 3

Iteration

Iterate Over Keys

Expected Output: alice: 90, bob: 85, carol: 95

Iterate Over Values

Expected Output: 4.25

Iterate Over Key-Value Pairs

Expected Output: x = 10, y = 20, z = 30

Common Patterns

Configuration Object

Expected Output: Connecting to localhost:8080, Using SSL

Data Transformation

Expected Output: ["Alice", "Bob", "Carol"]

Counting/Frequency Map

Expected Output: {apple: 3, banana: 2, cherry: 1}

Merge Objects

Expected Output: {host: "localhost", port: 8080, ssl: true}

Nested Objects

Expected Output: "Boston", "Alice"

Nested Field Access

Expected Output: 42

Object Comparison

Expected Output: true, true

Default Values Pattern

Expected Output: 8080, "localhost"

Objects vs Structs

Feature Object Struct
Fields Dynamic, can add/remove Fixed at definition
Types Any value type Declared types
Creation Literal {key: value} Type definition required
Performance Slower (hash lookup) Faster (direct access)
Use Case Dynamic data, JSON Type-safe domain models

JSON-Style Objects

Objects naturally map to JSON:

Expected Output: "Alice"

Best Practices

✅ Use Descriptive Keys

✅ Check Key Existence

✅ Use Objects for Grouped Data

✅ Prefer Structs for Domain Models

Common Algorithms

Group By

Expected Output: {fruit: ["apple", "banana"], vegetable: ["carrot"]}

Object Filter

Expected Output: {b: 2, d: 4}

Object Map

Expected Output: {apple: 2.00, banana: 1.00, cherry: 4.00}

Summary

Feature Status: WORKING
Test Coverage: 100%
Mutation Score: 95%

Objects are key-value collections perfect for structured data, configuration, and JSON-like data structures. Use them when field names matter and structure is dynamic.

Key Takeaways:

  • Create with {key: value} syntax
  • Access via .key or ["key"]
  • Methods: keys(), values(), has_key(), len()
  • Iterate with .keys(), .values(), .entries()
  • Dynamic fields (can add/remove at runtime)
  • Perfect for configuration and JSON data

← Previous: Tuples | Next: Structs →


Structs are user-defined types with named fields and fixed structure. They provide type safety and better performance than objects.

Defining Structs

Test Coverage: ✅ tests/lang_comp/data_structures/structs.rs

Try It in the Notebook

Expected Output: User { id: 1, username: "alice", email: "alice@example.com" }

Creating Instances

Expected Output: Point { x: 0.0, y: 0.0 }, Point { x: 10.5, y: 20.3 }

Field Init Shorthand

Expected Output: Person { name: "Alice", age: 30 }

Accessing Fields

Use dot notation:

Expected Output: 10.0, 20.0

Updating Fields

Expected Output: 10

Note: Instance must be mut to modify fields.

Struct Methods

Define methods with impl block:

Expected Output: 200.0, 60.0, false

Associated Functions (Constructors)

Expected Output: Point { x: 10.0, y: 20.0 }, Point { x: 0.0, y: 0.0 }, Point { x: 5.0, y: 15.0 }

Common Patterns

Builder Pattern

Expected Output: Config { host: "example.com", port: 443, ssl: true, timeout: 30 }

Validation

Expected Output: Some(Email { address: "alice@example.com" }), None

Data Transformation

Expected Output: 32.0

Nested Structs

Expected Output: "Boston"

Struct Update Syntax

Expected Output: 10.0, 2.0, 3.0

Tuple Structs

Structs without named fields:

Expected Output: 0, 0.0

Newtype Pattern

Use Case: Prevent mixing up values of same underlying type.

Unit Structs

Structs with no fields:

Use Case: Type markers, trait implementations, zero-sized types.

Struct Destructuring

Expected Output: 10.0, 20.0, 10.0

Structs vs Objects

Feature Struct Object
Definition Required before use Created on the fly
Fields Fixed at definition Dynamic (add/remove)
Types Statically typed Dynamic typing
Performance Faster (direct access) Slower (hash lookup)
Compile-time checks Yes (field existence, types) No (runtime errors)
Use Case Domain models, APIs Config, JSON, prototypes

Common Algorithms

Distance Calculation

Expected Output: 5.0

Vector Operations

Expected Output: 7.81

Best Practices

✅ Use Structs for Domain Models

✅ Implement Constructor Methods

✅ Group Related Methods in impl Block

✅ Use Newtypes for Type Safety

Summary

Feature Status: WORKING
Test Coverage: 100%
Mutation Score: 98%

Structs provide type-safe, performant data structures with named fields. Use them for domain models, APIs, and any data that benefits from compile-time validation.

Key Takeaways:

  • Define with struct Name { field: Type }
  • Create instances with Name { field: value }
  • Methods with impl Name { fn method(&self) { ... } }
  • Associated functions with fn new() -> Name
  • Better than objects for typed, structured data
  • Use newtypes for type safety

← Previous: Objects/Maps | Next: Enums →


Enums (enumerations) define types with a fixed set of named variants. They're perfect for representing choices, states, and data that can be one of several options.

Defining Enums

Test Coverage: ✅ tests/lang_comp/data_structures/enums.rs

Try It in the Notebook

Expected Output: Color::Red

Using Enum Variants

Access variants with :: notation:

Expected Output: TrafficLight::Red

Pattern Matching with Enums

Expected Output: "Currently working"

Enums with Data

Variants can hold data:

Expected Output: Various message types with data

Pattern Matching with Data

Expected Output: "Moving to (10, 20)"

Option Type

Built-in enum for optional values:

Expected Output: "Found: 2"

Option Methods

Expected Output: true, false, false, true

Unwrapping Option

Expected Output: 42, 42, 42, 0

Result Type

Built-in enum for operations that can fail:

Expected Output: "Result: 5"

Result Methods

Expected Output: true, false, false, true

Common Patterns

State Machine

Expected Output: State::Running

HTTP Status

Expected Output: 404

JSON Value

Expected Output: Object with structured JSON data

Command Pattern

Expected Output: "Creating Item"

Enum Methods

Define methods on enums with impl:

Expected Output: false, "In progress"

Recursive Enums

Enums can be recursive (with Box):

Expected Output: Linked list: 1 -> 2 -> 3 -> Nil

Enum Comparison

Expected Output: true, false

Generic Enums

Expected Output: Containers with different types

Best Practices

✅ Use Enums for Fixed Choices

✅ Prefer Pattern Matching

✅ Use Option Instead of Null

✅ Use Result for Error Handling

Enums vs Structs

Feature Enum Struct
Purpose One of several variants Group related fields
Variants Multiple named options Single structure
Data Each variant can differ All fields present
Matching Pattern match on variant Access fields directly
Use Case States, choices, errors Data models, entities

Summary

Feature Status: WORKING
Test Coverage: 100%
Mutation Score: 98%

Enums define types with fixed sets of variants, enabling type-safe state machines, error handling, and optional values. They're fundamental to Ruchy's type system.

Key Takeaways:

  • Define variants with enum Name { Variant1, Variant2 }
  • Access with Name::Variant
  • Pattern match with match
  • Built-in: Option<T> (Some/None), Result<T, E> (Ok/Err)
  • Variants can hold data
  • Better than magic values or null

← Previous: Structs | Next: Pattern Matching →