Question

update

Since one effect of these functions is to provide a way to use method chaining on methods that would not normally support it *, I'm considering calling them chain and copychain, respectively. This seems less than ideal though, since the would-be copychain is arguably a more fundamental concept, at least in terms of functional programming.


original

I'm calling it a boxer for now. The code is in Python, though the question is general:

def boxer(f):
    """Return a function g(o, *args, **keyargs) -> o

    `g` calls `f` on `o` with the remaining arguments
        and returns `o`.

    >>> l = [2]
    >>> def increment_list_element(l, i):
    ...     l[0] += i
    >>> adder = boxer(increment_list_element)
    >>> adder(l, 2)
    [4]
    >>> def multiply_list_element(l, i):
    ...     l[0] *= i
    >>> multiplier = boxer(multiply_list_element)
    >>> sum(multiplier(l, 6))
    24
    """
    def box(o, *args, **keyargs):
        f(o, *args, **keyargs)
        return o
    return box

A similar concept copies the would-be assignee, and assigns to and returns the copy. This one is a "shadow_boxer":

from copy import deepcopy

def shadow_boxer(f):
    """Return a function g(o, *args, **keyargs) -> p

    `g` deepcopies `o` as `p`,
        executes `f` on `p` with the remaining arguments,
        and returns `p`.

    >>> l = [2]
    >>> def increment_list_element(l, i):
    ...     l[0] += i
    >>> adder = shadow_boxer(increment_list_element)
    >>> adder(l, 2)
    [4]
    >>> def multiply_list_element(l, i):
    ...     l[0] *= i
    >>> multiplier = shadow_boxer(multiply_list_element)
    >>> sum(multiplier(l, 6))
    12
    """
    def shadow_box(o, *args, **keyargs):
        p = deepcopy(o)
        f(p, *args, **keyargs)
        return p
    return shadow_box

In addition, I'd like to find out about resources for learning more about these sorts of things — though I'm similarly unsure of a name for "these sorts of things". It does seem related to functional programming, although as I understand it, these technique would be unnecessary in a true functional language.

Was it helpful?

Solution

This is pretty much the same thing as Ruby's Object#tap. Don't know how you feel about the name, but that's what they call it.

OTHER TIPS

What the boxer function returns is probably defined closure in some programming languages. If there is not already a function with this name, I would call the function closure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top