Perl 6是否具有内置工具来制作嵌套数据结构的深层副本? [英] Does Perl 6 have a built-in tool to make a deep copy of a nested data structure?

查看:47
本文介绍了Perl 6是否具有内置工具来制作嵌套数据结构的深层副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 6是否具有内置工具来制作嵌套数据结构的深层副本?

Does Perl 6 have a built-in tool to make a deep copy of a nested data structure?

添加的示例:

my %hash_A = (
    a => {
        aa => [ 1, 2, 3, 4, 5 ],
        bb => { aaa => 1, bbb => 2 },
    },
);


my %hash_B = %hash_A;
#my %hash_B = %hash_A.clone; # same result

%hash_B<a><aa>[2] = 735;

say %hash_A<a><aa>[2]; # says "735" but would like get "3"


推荐答案

my %A = (
    a => {
        aa => [ 1, 2, 3, 4, 5 ],
        bb => { aaa => 1, bbb => 2 },
    },
);

my %B = %A.deepmap(-> $c is copy {$c}); # make sure we get a new container instead of cloning the value

dd %A;
dd %B;

%B<a><aa>[2] = 735;

dd %A;
dd %B;

使用 .clone .deepmap 请求数据结构的副本/深层副本。但是不要打赌。任何对象都可以定义自己的 .clone 方法,并使用它进行任何操作。如果必须突变并因此必须克隆,请确保使用大型数据集测试程序。错误的算法会使程序在生产中几乎毫无用处。

Use .clone and .deepmap to request a copy/deep-copy of a data-structure. But don't bet on it. Any object can define its own .clone method and do whatever it wants with it. If you must mutate and therefore must clone, make sure you test your program with large datasets. Bad algorithms can render a program virtually useless in production use.

这篇关于Perl 6是否具有内置工具来制作嵌套数据结构的深层副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆