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 { ... }
}
The
inExpressionChecking 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
inkeyword for iterable looping, ieloop x in container. We propose a large change toloopsemantics in order to satisfy this.Solution
Firstly,
loopandloop-inmust be changed towhile(boolean conditional looping), andfor-in. This, like Python, allows forinto 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::opsnamespace type defined:The
inexpression will then map directly to this function call.Furthermore, we propose an extension to pattern matching using the
inexpression, an idea borrowed from Kotlin. This introduces 1 new pattern,CasePatternVariantInExpression, allowing for branches to pattern match againstin collection: