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.