Functional Programming 사용에 대한 여러 예시를 작성
def sample_function(index: int):
return index - 1
def sample_main(threshold: int):
res = []
start_index = 1
while True:
res_index = sample_function(start_index)
if res_index % 2 == 0:
res.append(res_index)
if len(res) >= threshold:
break
start_index += 1
return res
def sample_function(index: int):
return index - 1
def sample_main_two(start_index, basket: list = None, threshold=10):
if not basket:
basket = []
if len(basket) >= threshold:
return basket
res_index = sample_function(start_index)
if res_index % 2 == 0:
basket.append(res_index)
return sample_main_two(start_index + 1, basket, threshold)
def sample_function(index: int):
return index - 1
@curry
def update_list(origin_res: list, new_list: list):
return origin_res + new_list
def sample_main_three(start_index, basket: list = []):
if len(basket) >= 10:
return basket
basket = go(
sample_function(start_index + 1),
custom_filter(lambda x: x % 2 == 0),
update_list(basket),
)
return sample_main_three(start_index + 1, basket)
@curry
def custom_filter(func: Callable, iterable: iter):
if not isinstance(iterable, list):
print(
f"[Warning] input_iter is not a list, input: {iterable}, {type(iterable)}"
)
iterable = [iterable]
res = []
for value in iterable:
if func(value):
res.append(value)
return res
# pytest -k test_while_with_count_should_work -s
def test_while_with_count_should_work():
base_counts = 10
target = list(range(0, base_counts + base_counts, 2))
print(f"target: {target}")
assert sample_main(base_counts) == target
assert sample_main_two(0) == target
assert sample_main_three(0) == target
tests/test_fp.py target: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[Warning] input_iter is not a list, input: 0, <class 'int'>
[Warning] input_iter is not a list, input: 1, <class 'int'>
[Warning] input_iter is not a list, input: 2, <class 'int'>
[Warning] input_iter is not a list, input: 3, <class 'int'>
[Warning] input_iter is not a list, input: 4, <class 'int'>
[Warning] input_iter is not a list, input: 5, <class 'int'>
[Warning] input_iter is not a list, input: 6, <class 'int'>
[Warning] input_iter is not a list, input: 7, <class 'int'>
[Warning] input_iter is not a list, input: 8, <class 'int'>
[Warning] input_iter is not a list, input: 9, <class 'int'>
[Warning] input_iter is not a list, input: 10, <class 'int'>
[Warning] input_iter is not a list, input: 11, <class 'int'>
[Warning] input_iter is not a list, input: 12, <class 'int'>
[Warning] input_iter is not a list, input: 13, <class 'int'>
[Warning] input_iter is not a list, input: 14, <class 'int'>
[Warning] input_iter is not a list, input: 15, <class 'int'>
[Warning] input_iter is not a list, input: 16, <class 'int'>
[Warning] input_iter is not a list, input: 17, <class 'int'>
[Warning] input_iter is not a list, input: 18, <class 'int'>