返回过滤后的范围

发布于 2025-01-11 19:28:04 字数 625 浏览 0 评论 0原文

我正在查看过滤范围,并感到有点困惑。在 D 中,我可以编写以下代码:

import std.stdio;
import std.range;
import std.algorithm;

auto filterNums(int[] vals)
{
    int limit = 3;
    return filter!(n => n >limit)(vals);
}

int main()
{
    int[] nums = [1,2,3,4,5];

    auto flt = filterNums(nums);

    foreach(n;flt)
    {
        writeln(n);
    }

    return 0;
}

给出预期输出:

4
5

但这似乎不是非常安全的代码。如果过滤器是惰性计算的,一旦局部变量超出范围,它如何知道 limit 是 3?我的代码是否只是幸运,内存中没有其他内容超出了 limit ?传递的变量 nums 也是一个引用,还是一个复制的值:如果是一个值,过滤器是否会制作自己的副本?

或者也许我没有以正确的方式使用 filter

I'm looking at filtering ranges, and getting a little confused. In D, I can write this code:

import std.stdio;
import std.range;
import std.algorithm;

auto filterNums(int[] vals)
{
    int limit = 3;
    return filter!(n => n >limit)(vals);
}

int main()
{
    int[] nums = [1,2,3,4,5];

    auto flt = filterNums(nums);

    foreach(n;flt)
    {
        writeln(n);
    }

    return 0;
}

which gives the expected output of:

4
5

But this doesn't seem to be terribly safe code. If the filter is lazy evaluating, how does it know that limit is 3, once the local variable goes out of scope? Is my code just lucky that nothing else has over-ridden limit in memory? Also is the passed variable nums a reference, or a copied value: if a value, is the filter making its own copy?

Or perhaps I am not using filter in the correct way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

苹果你个爱泡泡 2025-01-18 19:28:04

int 是一个值类型,因此过滤器 lambda 接收它的副本。如果存在任何范围问题,编译器会警告您。

int[] nums 是由 D 运行时管理的动态数组。它由两部分组成:一个值部分,其中包含其长度和一个指针,该指针指向堆上的动态部分(存储整数的位置)。长度和指针本身是按值传递的,这意味着附加或删除不会影响原始元素,但编辑元素(例如 vals[1] = 1)会影响。要通过引用传递所有内容,您可以使用

filterNums(ref int[] vals)

无论哪种方式,垃圾收集器都会在需要时保留它,在本例中,它存储在 filter 构造中。

int is a value type, so the filter lambda receives a copy of it. If there were any scoping issues, the compiler would warn you.

int[] nums is a dynamic array managed by D's runtime. It consists of two parts: a value part, which contains its length and a pointer, which points to the dynamic part on the heap (where the ints are stored). The length and pointer itself are passed by value, which means appending or removing will not affect the original, but editing an element e.g. vals[1] = 1 would. To pass all of it by reference, you would use

filterNums(ref int[] vals).

Either way, the garbage collector keeps it around as long as it's needed, in this case it is stored in the filter construct.

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