Python, Function

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

  • Check if the value of predicate(x) is True and if so return when_true(x), 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

Recommended snippets

  • unfold

    Python, Function

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

  • check_prop

    Python, Function

    Creates a function that will invoke a predicate function for the specified property on a given object.

  • compose

    Python, Function

    Performs right-to-left function composition.