-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathhigher-order-functions.py
69 lines (48 loc) · 1.28 KB
/
higher-order-functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def combine(x, y, op):
return op(x, y)
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def polynomial(x, y):
return 2 * x * x + 3 * y
def create_printer():
def printer():
print('Hello functional!')
return printer
# def double(x):
# return x * 2
# def triple(x):
# return x * 3
# def quadruple(x):
# return x * 4
def create_multiplier(y):
def multiplier(x):
return x * y
return multiplier
#############################
def create_arg_checker(arg_check_func, warning_message):
def arg_checker(func):
def safe_version(*args, **kwargs):
if arg_check_func(*args, **kwargs):
print(f'ARGS: {warning_message}')
return
return func(*args, **kwargs)
return safe_version
return arg_checker
def second_arg_zero(*args):
return args[1] == 0;
def first_arg_gt_100(*args):
return args[0] > 100
@create_arg_checker(second_arg_zero, 'Warning: second arg is zero!')
@create_arg_checker(first_arg_gt_100, 'Warning: first arg is greater than 100')
def divide(x, y):
return x / y
def name_is_lt_2_chars(*args, **kwargs):
return len(kwargs['name']) < 2
@create_arg_checker(name_is_lt_2_chars, 'Warning: name arg must be longer than 2 chars')
def create_person(name, age):
return {
'name': name,
'age': age,
}