DEV Community

Functional Javascript
Functional Javascript

Posted on

Python - Pipe-Oriented Programming

How to do #PipeOrientedProgramming in Python.

With an example doing simple arithmetic operations,
as the result of one function is piped into the next.

The "lNum" util function means "log number".

from pyLog import lNum
from pyNum import minus3, mod6, times2, minusNum, mNum, minNum

def pipepy(*funcs):
    def inner(data, funcs=funcs):
        result = data
        for f in funcs:
            #tsk: throwIfNotFunc
            result = f(result)
        return result
    return inner


# testonly
p1 = pipepy(
    mod6, lNum,  # 5
    times2, lNum,  # 10
    minus3, lNum,  # 7
    minusNum(4), lNum,  # -3
    mNum(2), lNum,  # 5
    minNum(25), lNum,  # 20
)
p1(5)

Also, three ways to curry a function in python...

#curry, v1
def minusNum(x):
    def inner(y):
        return x - y
    return inner



#curry, v2
def mNum(x): return lambda y: x-y



#currry, v3
minNum = lambda x: lambda y: x-y

Resource:

Final words

If you have any input, ideas, opinions, questions, let me know.

There more pipe-oriented programming idioms, patterns and ideas coming in the future.

Top comments (0)