散列的散列

a hash of hashes of numbers in Raku

如何在 Raku 中声明散列的数字散列?

默认情况下,散列将所有键转换为字符串。当你的键是可能接近的数字时,会导致问题:

> my %h; %h{1/3} = 1; %h{0.333333} = 2; dd %h;
Hash %h = {"0.333333" => 2}

当然,这可以修复如下:

>  my %h{Real}; %h{1/3} = 1; %h{0.333333} = 2; dd %h;
Hash[Any,Real] %h = (my Any %{Real} = 0.333333 => 2, <1/3> => 1)

但现在我需要散列的数字散列时,例如 { 1/3 => { 2/3 => 1, 0.666667 => 2 } }

> my %h{Real}; %h{1/3}{2/3} = 1; %h{1/3}{0.666667} = 2; dd %h;
Hash[Any,Real] %h = (my Any %{Real} = <1/3> => ${"0.666667" => 2})

我怎么修复它?

我能想到的最好的方法是这样:

> my %h{Real}; %h{1/3} //= my %{Real}; %h{1/3}{2/3} = 1; %h{1/3}{0.666667} = 2; dd %h;
Hash[Any,Real] %h = (my Any %{Real} = <1/3> => $(my Any %{Real} = <2/3> => 1, 0.666667 => 2))

但是有点烦人。

解决方法

my Hash[Real,Real] %h{Real};
%h{1/3} .= new;
%h{1/3}{2/3} = 1;

下面的也是有效的:

my Hash[Real,Real] %h{Real};
%h does role {
  method AT-KEY (|) is raw {
    my \result = callsame;
    result .= new unless defined result;
    result
  }
}

%h{1/3}{2/3} = 1;

say %h{1/3}{2/3}; # 1

如果你有多个这样的变量:

role Auto-Instantiate {
  method AT-KEY (|) is raw {
    my \result = callsame;
    result .= new unless defined result;
    result
  }
}

my Hash[Real,Real] %h{Real} does Auto-Instantiate;
Hash 

comments powered by Disqus