-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompose.py
81 lines (57 loc) · 1.16 KB
/
compose.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
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 15 16:50:47 2023
@author: kirbyurner
"""
def f(x):
return 2 * x
def g(x):
return 2 + x
#%%
print("f(g(10))=", f(g(10)))
print("g(f(10))=", g(f(10)))
#%%
print([f(g(k)) for k in range(10)])
print([g(f(k)) for k in range(10)])
#%%
def compose(m, n):
"""compose callables"""
def newfunc(x):
return m(n(x))
return newfunc
h = compose(f, g)
print("h type:", type(h))
print("f(g(10)): ", h(10))
h = compose(g, f)
print("g(f(10)): ", h(10))
#%%
class Compose:
def __init__(self, func):
"""store callable"""
self.func = func
def __mul__(self, other):
"""compose callables"""
return Compose(lambda x: self(other(x)))
def __call__(self, x):
"""call self with argument"""
return self.func(x)
f = Compose(f)
g = Compose(g)
h = f * g
print("h type:", type(h))
print("f(g(10))= ", h(10))
h = g * f
print("g(f(10))= ", h(10))
#%%
@Compose
def f(x):
return 2 * x
@Compose
def g(x):
return 2 + x
h = f * g
print("h type:", type(h))
print("f(g(10))= ", h(10))
h = g * f
print("g(f(10))= ", h(10))