Apply function when true

Python, Function · Nov 9, 2020

Tests a value, x, against a testing function, conditionally applying a function.

  • Check if the value of predicate() is True for x and if so call when_true(), otherwise return x.
def when(predicate, when_true):
  return lambda x: when_true(x) if predicate(x) else x
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)
double_even_numbers(2) # 4
double_even_numbers(1) # 1

More like this

  • Unfold list

    Builds a list, using an iterator function and an initial seed value.

    Python, Function · Nov 2, 2020

  • Compose functions

    Performs right-to-left function composition.

    Python, Function · Nov 2, 2020

  • Reverse compose functions

    Performs left-to-right function composition.

    Python, Function · Nov 2, 2020