1 point

Python when function - to apply a function when predicate(x) is True


Sat Jan 11 2020 20:54:48 GMT+0000 (UTC)

Posted by @dry_toasts #python #function

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
content_copy Copy

Tests a value, x, against a predicate function, conditionally applying a function. Check if the value of predicate(x) is True and if so return when_true(x), otherwise return x.