I tried function synthesis and curry with python

python has partial

However, there is no currying. I'm sad. So I wrote a curry function that counts the positional arguments by myself.

Function composition

First, I wrote a function composition. It's simple and shabby.

def compose(*funcs: Callable) -> Callable:
    '''
    >>> compose(multest, multest)(4)
    16
    '''
    def composed(*args: Any) -> Any:
        return reduce(lambda x, y: y(x), (funcs[0](*args),)+funcs[1:])
    return composed

Currying functions

The mechanism is as simple as checking the number of positional arguments and partially partialing that much. So sometimes it doesn't work.

def _curry_one(func: Callable) -> Callable:
    def wrap(*args: Any, **kwargs: Any) -> Any:
        return partial(func, *args, **kwargs)
    return wrap


def curry(num_of_args: Optional[int] = None) -> Callable:
    '''
    >>> fnc = curry(2)(multest2)
    >>> fnc(2)(3)
    6
    >>> fnc = curry()(multest3)
    >>> fnc(2)(3)(4)
    24
    '''
    def curry_wrap(func: Callable) -> Callable:
        length_of = compose(filter, list, len)
        if num_of_args:
            num = num_of_args
        else:
            def is_empty(x): return x.default is inspect._empty
            num = length_of(is_empty,
                            inspect.signature(func).parameters.values())
        for n in range(num - 1):
            func = _curry_one(func)
        return func
    return curry_wrap

This counts the number of arguments when currying, and curries as many as the number of positional arguments. You can also specify the number of times to curry. However, in practice, it is fixed at 2 and it feels good.

Why is it currying? Is it useless in partial?

It can be partial, but this curry can be used as a decorator.

@curry()
def test(x, y, z):
    return x * y + z

Also, sometimes useful when using it as a higher-order function. Mainly when it is necessary to separate cases When I have to bring out a starmap. For example, I can't read the last part below. (Write)

def plus(x, y):
    return x * y

result = list(map(partial(plus, 3), range(4)))

This guy's partial can be separated.

def plus(x, y):
    return x * y

plus3 = partial(plus)
result = list(map(plus3, range(4)))

The namespace is a little bit ... I feel uncomfortable with more plus hoge. I can write this guy like this

@curry()
def plus(x, y):
    return x * y

result = compose(map, list)(plus(3), range(4))

Is it okay to do this?

It's decided to be useless, python should be the same no matter who writes it. Therefore, the above should not be used.

Dissolution

If it doesn't work, why did you do this?

Use numpy in your personal project. I'm self-employed, but I was disappointed because I couldn't read the code because I wrote the code like this.

np.save(fname, baseline(np.square(fft(data.mean(axis=1)))))

This is a scientific calculation package, so there is room for consideration in the situation (is there?). There were so many math variables and the namespace was crazy ... If there was currying and function composition here, this would be the case, right?

mean = curry(np.mean)
save = curry(np.save)
compose(mean(axis=1), fft, np.square, np.std, save(fname))(data)

... isn't it? Personal project acquittal.

Recommended Posts

I tried function synthesis and curry with python
I tried Jacobian and partial differential with python
I tried fp-growth with python
I tried scraping with Python
I tried gRPC with Python
I tried scraping with python
I tried web scraping with python.
I played with PyQt5 and Python3
Function synthesis and application in Python
I tried running prolog with python 3.8.2.
I tried SMTP communication with Python
I tried follow management with Twitter API and Python (easy)
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried scraping Yahoo News with Python
I tried non-photorealistic rendering with Python + opencv
I tried a functional language with Python
I tried recursion with Python ② (Fibonacci sequence)
I installed and used Numba with Python3.5
#I tried something like Vlookup with Python # 2
I tried to make a periodical process with Selenium and Python
I tried to easily detect facial landmarks with python and dlib
I tried to make an image similarity function with Python + OpenCV
I also tried to imitate the function monad and State monad with a generator in Python
I tried "smoothing" the image with Python + OpenCV
I tried hundreds of millions of SQLite with python
[Python] I tried substituting the function name for the function name
I tried web scraping using python and selenium
I tried object detection using Python and OpenCV
I tried Python> autopep8
I tried L-Chika with Raspberry Pi 4 (Python edition)
I tried playing with PartiQL and MongoDB connected
I compared "python dictionary type" and "excel function"
I tried to get CloudWatch data with Python
I tried using mecab with python2.7, ruby2.3, php7
I tried to output LLVM IR with Python
I tried "binarizing" the image with Python + OpenCV
I tried running faiss with python, Go, Rust
I tried to automate sushi making with python
I tried playing mahjong with Python (single mahjong edition)
I tried running Deep Floor Plan with Python 3.6.10.
I tried sending an email with SendGrid + Python
I tried Python> decorator
I tried updating Google Calendar with CSV appointments using Python and Google APIs
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to automate internal operations with Docker, Python and Twitter API + bonus
I tried speeding up Python code including if statements with Numba and Cython
I tried to learn the sin function with chainer
I tried pipenv and asdf for Python version control
I tried to implement and learn DCGAN with PyTorch
Introduce pipe operators and function synthesis to Python (provisional)
I tried to implement Minesweeper on terminal with python
I tried to get started with blender python script_Part 01
2017-04-11 Python> I tried generator> I was taught generator expression / generator function / next ()
I tried to touch the CSV file with Python
I tried to draw a route map with Python
[OpenCV / Python] I tried image analysis of cells with OpenCV
I tried to solve the soma cube with python
I tried to automatically read and save with VOICEROID2
I tried to get started with blender python script_Part 02
I tried to implement an artificial perceptron with python
Crawling with Python and Twitter API 1-Simple search function