这个高阶函数有名字吗?
我在代码和库中随处可见这种模式,但似乎在任何地方都找不到它的名称或抽象。
示例(伪代码)
T foo( T x, void f(T&) )
{
T y = x;
f( y );
return y;
}
基本上:获取一个值,以及转换该值的函数。制作该值的副本,对其进行转换,然后返回它。
现实生活中的例子(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;
}
基本上,你有一个就地函数(有副作用),并用它创建一个不合适的函数(没有副作用)。
这种模式有名字吗?您知道有哪些库或语言使用它吗?显然函数式语言不会使用它,因为它们一开始就没有引用不透明的函数。
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 of 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它实际上是数学和 FP 中所谓的组合,因为您可以将其表示为
mystery_function(x, fun) = fun(copy(x))
。用设计模式的术语来说,它是一个包装器,用副本包装函数调用。所以我更愿意自然地将其称为复制包装器。但我从未在任何地方看到过它被分类。
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.