Does this higher order function have a name?
I see this pattern everywhere in my code, and in libraries, yet there appears to be no name or abstraction of it that I can find anywhere.
Example (pseudocode)
T foo( T x, void f(T&) )
{
T y = x;
f( y );
return y;
}
Basically: Take a value, and a function that transforms that value. Make of a copy of the value, transform it, and return it.
Real-life examples (C++)
T operator+(const T& x, const T& y)
{
T z = x; // Make a copy
operator+=(z, y); // Modify in place
return z;
}
Vector3 Vector3::normalized() const
{
Vector3 x = *this; // Make a copy
x.normalize(); // Modify in place
return x;
}
T sorted(T const& x)
{
T y = x; // Make a copy (yeah, yeah, could have passed by value)
sort( y ); // Modify in place
return y;
}
Basically, you have an in place function (with side-effects) and make an out-of-place function (without side-effects) out o开发者_如何学编程f it.
Is there a name for this pattern? Do you know of any libraries or languages that use it? Obviously functional languages won't use it because they don't have referentially opaque functions to begin with.
It's actually what in mathematics and FP is called a composition, because you could express it as mystery_function(x, fun) = fun(copy(x))
instead.
In Design Patterns linguo, it's a wrapper, that wraps the function call with a copy. So I would rather naturally call it a copy wrapper. But I never saw it classified anywhere.
精彩评论