Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better Function Composition in Python

I work in Python. Recently, I discovered a wonderful little package called fn. I've been using it for function composition.

For example, instead of:

baz(bar(foo(x))))

with fn, you can write:

(F() >> foo >> bar >> baz)(x) .

When I saw this, I immediately thought of Clojure:

(-> x foo bar baz) .

But notice how, in Clojure, the input is on the left. I wonder if this possible in python/fn.

like image 936
Charles R Avatar asked Jun 23 '13 19:06

Charles R


People also ask

What is composition in functions in Python?

Function composition is the way of combining two or more functions in such a way that the output of one function becomes the input of the second function and so on.

How do you merge two functions in Python?

You could just write a function that returns Max(lst), Min(lst) . It will be inefficient since it will recurse twice, but it's the simplest way to combine the two existing functions. Use objects! Your object can have 2 properties min and max.

How do you evaluate the composition of a function?

A composite function can be evaluated by evaluating the inner function using the given input value and then evaluating the outer function taking as its input the output of the inner function.

What is function composition give an example?

It is possible to compose a function with itself. Suppose f is a function, then the composition of function f with itself will be. (f∘f)(x) = f(f(x)) Let us understand this with an example: Example: If f(x) = 3x2, then find (f∘f)(x).


1 Answers

You can't replicate the exact syntax, but you can make something similar:

def f(*args):
    result = args[0]

    for func in args[1:]:
        result = func(result)

    return result

Seems to work:

>>> f('a test', reversed, sorted, ''.join)
' aestt'
like image 164
Blender Avatar answered Oct 15 '22 00:10

Blender