if_else#

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])