-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLambdaExpressions.py
More file actions
executable file
·68 lines (50 loc) · 1.22 KB
/
LambdaExpressions.py
File metadata and controls
executable file
·68 lines (50 loc) · 1.22 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 25 00:49:54 2021
@author: maherme
"""
#%%
def sq(x):
return x**2
print(type(sq))
sq # Run in the command line, notice the function name is sq(x)
#%%
# Lambda is a generic function:
lambda x: x**2 # Run in the command line, now the function name is <lambda>
#%%
lambda x, y: x+y # Run in the command line, the functio name is also <lambda>
#%%
f = lambda x, *args, y, **kwargs: (x, args, y, kwargs)
print(f(1, 'a', 'b', y=100, a=10, b=20))
#%%
def apply_func(x, fn):
return fn(x)
a = apply_func(3, sq)
print(a)
#%%
# We can do the same with lambda:
a = apply_func(3, lambda x: x**2)
print(a)
#%%
# Some examples of lambda applications:
def apply_func(fn, *args, **kwargs):
return fn(*args, **kwargs)
a = apply_func(sq, 3)
print(a)
print("----------------------")
a = apply_func(lambda x: x**2, 3)
print(a)
print("----------------------")
a = apply_func(lambda x, y: x+y, 1, 2)
print(a)
print("----------------------")
a = apply_func(lambda x, *, y: x+y, 1, y=20)
print(a)
print("----------------------")
a = apply_func(lambda *args: sum(args), 1, 2, 3, 4, 5)
print(a)
print("----------------------")
a = apply_func(sum, (1, 2, 3, 4, 5))
print(a)
#%%