Skip to main content

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fp_functions-0.1.1.tar.gz (3.2 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page