Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Last active December 15, 2017 03:37
Show Gist options
  • Save izmailoff/57154c3dd6bed6e63b3d7d65264f7f36 to your computer and use it in GitHub Desktop.
Save izmailoff/57154c3dd6bed6e63b3d7d65264f7f36 to your computer and use it in GitHub Desktop.
Example of functional sets in Python
set_of_1 = lambda i: i == 1
set_of_1(1)
set_of_1(2)
empty = lambda i: False
empty(1)
union = lambda s1, s2: lambda i: s1(i) or s2(i)
intersect = lambda s1, s2: lambda i: s1(i) and s2(i)
set_of_5_3_2 = union(union(lambda x: x == 5, lambda x: x == 3), lambda x: x == 2)
set_of_5_3_2(5)
set_of_5_3_2(2)
set_of_5_3_2(1)
set_of_5_3_2_1 = union(set_of_1, set_of_5_3_2)
set_of_5_3_2_1(3)
set_of_5_3_2_1(1)
intersect(set_of_5_3_2, set_of_5_3_2_1)(1)
intersect(set_of_5_3_2, set_of_5_3_2_1)(5)
@izmailoff
Copy link
Author

Python REPL output of the code above:

>>> 
>>> set_of_1 = lambda i: i == 1
>>> 
>>> set_of_1(1)
True
>>> 
>>> set_of_1(2)
False
>>> 
>>> empty = lambda i: False
>>> 
>>> empty(1)
False
>>> 
>>> union = lambda s1, s2: lambda i: s1(i) or s2(i)
>>> 
>>> intersect = lambda s1, s2: lambda i: s1(i) and s2(i)
>>> 
>>> set_of_5_3_2 = union(union(lambda x: x == 5, lambda x: x == 3), lambda x: x == 2)
>>> 
>>> set_of_5_3_2(5)
True
>>> 
>>> set_of_5_3_2(2)
True
>>> 
>>> set_of_5_3_2(1)
False
>>> 
>>> set_of_5_3_2_1 = union(set_of_1, set_of_5_3_2)
>>> 
>>> set_of_5_3_2_1(3)
True
>>> 
>>> set_of_5_3_2_1(1)
True
>>> 
>>> intersect(set_of_5_3_2, set_of_5_3_2_1)(1)
False
>>> 
>>> intersect(set_of_5_3_2, set_of_5_3_2_1)(5)
True
>>> 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment