Control flow ops#
- ivy.for_loop(iterable, body_fn, vars)[source]#
Loops over an iterable, passing the current iteration along with a tuple of variables into the provided body function.
- Parameters:
iterable (
Iterable
[Any
]) – The iterable to loop over.body_fn (
Callable
) – A function to call each iteration, first taking the iterator value and then a tuple of extra parameters.vars (
Iterable
[Union
[Array
,NativeArray
]]) – Extra parameters to be passed to body_fn.
- Returns:
ret – The loop’s return value (if any).
Example
>>> def body_fn(k, args): >>> print(k+1) >>> return args >>> >>> lst = [5,6] >>> >>> ivy.for_loop(lst, body_fn, ()) 5 6
- ivy.if_else(cond, body_fn, orelse_fn, vars)[source]#
Take a condition function and two functions as input. If the condition is True, the first function is executed and its result is returned. Otherwise, the second function is executed and its result is returned.
- Parameters:
cond (
Callable
) – A function returning a boolean.body_fn (
Callable
) – A callable function to be executed if the condition is True.orelse_fn (
Callable
) – A callable function to be executed if the condition is False.vars (
Dict
[str
,Union
[Array
,NativeArray
]]) – Additional variables to be passed to the functions.
- Return type:
Any
- Returns:
ret – The result of executing either body_fn or orelse_fn depending on the value of cond.
Examples
>>> cond = lambda x: True >>> body_fn = lambda x: x + 1 >>> orelse_fn = lambda x: x - 1 >>> vars = (1,) >>> result = ivy.if_else(cond, body_fn, orelse_fn, vars) >>> print(result) 2
>>> cond = lambda x: True >>> body_fn = lambda x: x * 2 >>> orelse_fn = lambda x: x / 2 >>> vars = ivy.array([1, 2, 3]) >>> result = ivy.if_else(cond, body_fn, orelse_fn, vars=(vars,)) >>> print(result) ivy.array([0.5, 1.0, 1.5])
- ivy.while_loop(test_fn, body_fn, vars)[source]#
Take a test function, a body function and a set of variables as input. The body function is executed repeatedly while the test function returns True.
- Parameters:
test_fn (
Callable
) – A callable function that returns a boolean value representing whether the loop should continue.body_fn (
Callable
) – A callable function to be executed repeatedly while the test function returns True.vars (
Dict
[str
,Union
[Array
,NativeArray
]]) – Additional variables to be passed to the functions.
- Return type:
Any
- Returns:
ret – The final result of executing the body function.
Examples
>>> i = 0 >>> test_fn = lambda i: i < 3 >>> body_fn = lambda i: i + 1 >>> result = ivy.while_loop(test_fn, body_fn, vars= (i,)) >>> print(result) (3,)
>>> i = 0 >>> j = 1 >>> test_fn = lambda i, j: i < 3 >>> body_fn = lambda i, j: (i + 1, j * 2) >>> vars = (i, j) >>> result = ivy.while_loop(test_fn, body_fn, vars=vars) >>> print(result) (3, 8)
This should have hopefully given you an overview of the control_flow_ops submodule, if you have any questions, please feel free to reach out on our discord!