This commit is contained in:
Angelos Chalaris
2020-01-02 20:25:45 +02:00
committed by GitHub
parent 79c1d65ea5
commit e38176767b

19
snippets/when.md Normal file
View File

@ -0,0 +1,19 @@
---
title: when
tags: function,intermediate
---
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`.
```py
def when(predicate, when_true):
return lambda x: when_true(x) if predicate(x) else x
```
```py
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)
double_even_numbers(2) # 4
double_even_numbers(1) # 1
```