A small Python library that adds some functional programming features
Project description
fp-functions
fp-functions is a small Python library to add some features and syntax from functional programming languages.
It supports combining functions with the left shift (<<) operator and stacking function calls on an iterable with the pipe (|) operator.
This library requires Python 3
Note that all functions created with Pipe, custom and those from the library, can be called as regular functions
Installation
pip3 install fp-functions
Examples
Examples of the pipe operator:
Finding the squares of all numbers less than 100, excluding the multiples of 7:
from fp_functions import select, where, as_list
print(
range(100)
| select(lambda x: x**2)
| where(lambda x: x % 7 != 0)
| as_list()
)
# Returns [1, 4, 9, 16, 25, 36, 64, 81]
Finding all distinct permutations of the list [1, 5, 3, 6, 8], with the even numbers replaced with 7 and 9:
from fp_functions import distinct_permutations, replace, as_set
print(
[5, 6, 8]
| replace(lambda x: x % 2 == 0, [7, 9])
| distinct_permutations(2)
| as_set()
)
# Returns {(7, 7), (9, 9), (5, 7), (7, 9), (9, 5), (5, 9), (7, 5), (9, 7)}
Examples of the function combination:
Create a compound function to return the iterable reversed, with all elements sqrt-ed and as a list
from fp_functions import reversed, select, as_list
reversed_sqrts_list = reversed() >> select(lambda x: x**0.5) >> as_list()
print(reversed_sqrts_list(range(10)))
# Returns [2.0, 1.7320508075688772, 1.4142135623730951, 1.0, 0.0]
This is equivalent to doing the code below, but the function can be used multiple times:
print(
range(5)
| reversed()
| select(lambda x: x**0.5)
| as_list()
)
# Returns [2.0, 1.7320508075688772, 1.4142135623730951, 1.0, 0.0]
Custom pipe/compund functions:
from fp_functions import Pipe
@Pipe
def select_every_third(iterable):
count = 0
for i in iterable:
if count % 3 == 0:
yield i
count += 1
print(
range(20)
| select_every_third()
| as_list()
)
# Returns [0, 3, 6, 9, 12, 15, 18]
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file fp_functions-0.1.1.tar.gz.
File metadata
- Download URL: fp_functions-0.1.1.tar.gz
- Upload date:
- Size: 3.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.5.0 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
488419ba89c30ee8b05db36dfe0235ce7c007d217abecb6842476509d2c9bf74
|
|
| MD5 |
f514d839a676a824f5ccbe321f6393b5
|
|
| BLAKE2b-256 |
9b6904b57be87e3b2054e5b4e85d513336b109b72f11d114112f6c726e655845
|