When implementing algorithms that operate on data structures (particularly arrays, lists, or collections), design them to handle both constant and expression-based inputs efficiently. Consider the constraints each imposes on the algorithm:
When implementing algorithms that operate on data structures (particularly arrays, lists, or collections), design them to handle both constant and expression-based inputs efficiently. Consider the constraints each imposes on the algorithm:
Implement pattern flags (like as_array
) that indicate when constant values are required for type determination. This enables both flexibility and performance optimization.
For example:
def slice(self, offset: int | Expr, length: int | Expr, as_array: bool = True) -> Expr:
"""Slice the array.
Parameters
----------
offset
The offset to start the slice.
length
The length of the slice.
as_array
If True, offset and length must be constants.
If False, returns a list instead of an array.
"""
if as_array and (not isinstance(offset, int) or not isinstance(length, int)):
raise ValueError("When as_array=True, offset and length must be constants")
# Implementation continues...
This pattern enables algorithms to work efficiently with both scenarios while providing clear feedback when constraints cannot be met.
Enter the URL of a public GitHub repository