这个高阶函数有名字吗?

发布于 2024-10-02 20:38:37 字数 778 浏览 0 评论 0原文

我在代码和库中随处可见这种模式,但似乎在任何地方都找不到它的名称或抽象。

示例(伪代码)

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寻找一个思念的角度 2024-10-09 20:38:37

它实际上是数学和 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文