Apply a function to each element of the array. Args: fn: The function to apply. Returns: The array after applying the function. Raises: VarTypeError: If the function takes more than one argument.
(self, fn: Any)
| 419 | return array_ge_operation(self, other) |
| 420 | |
| 421 | def foreach(self, fn: Any): |
| 422 | """Apply a function to each element of the array. |
| 423 | |
| 424 | Args: |
| 425 | fn: The function to apply. |
| 426 | |
| 427 | Returns: |
| 428 | The array after applying the function. |
| 429 | |
| 430 | Raises: |
| 431 | VarTypeError: If the function takes more than one argument. |
| 432 | """ |
| 433 | from .function import ArgsFunctionOperation |
| 434 | |
| 435 | if not callable(fn): |
| 436 | raise_unsupported_operand_types("foreach", (type(self), type(fn))) |
| 437 | # get the number of arguments of the function |
| 438 | num_args = len(inspect.signature(fn).parameters) |
| 439 | if num_args > 1: |
| 440 | msg = "The function passed to foreach should take at most one argument." |
| 441 | raise VarTypeError(msg) |
| 442 | |
| 443 | if num_args == 0: |
| 444 | return_value = fn() |
| 445 | function_var = ArgsFunctionOperation.create((), return_value) |
| 446 | else: |
| 447 | # generic number var |
| 448 | number_var = Var("").to(NumberVar, int) |
| 449 | |
| 450 | first_arg_type = self[number_var]._var_type |
| 451 | |
| 452 | arg_name = get_unique_variable_name() |
| 453 | |
| 454 | # get first argument type |
| 455 | first_arg = Var( |
| 456 | _js_expr=arg_name, |
| 457 | _var_type=first_arg_type, |
| 458 | ).guess_type() |
| 459 | |
| 460 | function_var = ArgsFunctionOperation.create( |
| 461 | (arg_name,), |
| 462 | Var.create(fn(first_arg)), |
| 463 | ) |
| 464 | |
| 465 | return map_array_operation(self, function_var) |
| 466 | |
| 467 | |
| 468 | @dataclasses.dataclass( |