Skip to content

The in Expression #10

@SamG101-Developer

Description

@SamG101-Developer

The in Expression

Checking for a value inside a container is such a common operation, that it warrants its own operator. This also cleans up code that has different container-checking methods or semantics, enforcing consistency across all contains for this common operation.

The difficulty is that there already exists the in keyword for iterable looping, ie loop x in container. We propose a large change to loop semantics in order to satisfy this.

Solution

Firstly, loop and loop-in must be changed to while (boolean conditional looping), and for-in. This, like Python, allows for in to be used for either iterable looping, or container checking. This will require changes to the lexer implementation, the parser implementation, and ast filenames.

The final syntax should look like:

  • for iterator in iterable { ... } for iterating over collections.
  • while condition { ... } for looping based on a condition.
  • while value in collection { ... } for looping while a value exists in a collection.

There must be a new std::ops namespace type defined:

cls Contains[T] {
    !abstract_method
    fun contains(&self, item: &T) -> Bool { }
}

The in expression will then map directly to this function call.

Furthermore, we propose an extension to pattern matching using the in expression, an idea borrowed from Kotlin. This introduces 1 new pattern, CasePatternVariantInExpression, allowing for branches to pattern match against in collection:

case my_expression of {
    in collection_a { ... }
    in collection_b { ... }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions