vendredi 18 septembre 2020

Discovered a pattern using higher order functions. What is this pattern called?

I am working on a python project in which I frequently need to generate a figure containing two axes using matplotlib. The code to generate the figure is identical each time. However I am calling my own functions which accept an axes object as one of their arguments and modify it. I throughout my project, I call different combinations of these functions to populate my figure axes.

It then occured to me that I actually pass these functions themselves and a tuple of their arguments into a higher order function. The higher order function would have the responsibility of calling the functions to populate the two axes objects to generate my figure. I made a toy example to illustrate this below.

import matplotlib.pyplot as plt
import numpy as np

def A(ax, x, a, b, c):

    y = a*x**2+b*x+c
    ax.plot(x, y)

    return ax

def B(ax, x, a):

    y = a*x**2
    ax.scatter(x, y)

    return ax

def C(ax, n):

    ax.axhline(n)

    return x

def plot(ax1, f1, args1, ax2, f2, args2):

    ax1 = f1(ax1, *args1)
    ax2 = f2(ax2, *args2)

    return ax1, ax2
if __name__=="__main__":
    x = np.linspace(0,10,10)

    fig, (ax1, ax2) = plt.subplots(2, 1)
    ax1, ax2 = plot(ax1, A, (x, 1, 2, 3), ax2, C, (5,))

    plt.show()

    x = np.linspace(0, 10, 10)

    fig, (ax1, ax2) = plt.subplots(2, 1)
    ax1, ax2 = plot(ax1, B, (x, 1), ax2, C, (5,))

    plt.show()

The function plot here is an example of such a higher order function. It can take in any combination of functions f1 and f2. It then calls these functions on the given axes objects to generate a figure. The function plot does not care how many arguments f1 and f2 has, which makes it generic enough to reduce the amount of duplicate code I have.

What pattern is this? Is this an example of a decorator? If not does python have any built-in syntactic sugar to support this on a more fundamental level?

Aucun commentaire:

Enregistrer un commentaire