Typed hashes in Raku

希望你有好运气

Typed hashes in Raku

在 Raku 中, 你可以通过指定变量的类型来限制变量容器的内容, 例如:

my Int $i;

标量变量中只有一个值。你可以将该概念扩展到数组, 并让其元素仅保存整数, 如下例所示:

> my Int @i;
[]

> @i.push(42);
[42]

> @i.push('Hello');
Type check failed in assignment to @i;
expected Int but got Str ("Hello")
  in block <unit> at <unknown file> line 1

哈希中保存的是 pairs, 所以你可以同时指定键和值的类型。语法和上面的例子并无不同。

首先, 让我们声明值的类型:

my Str %s;

现在, 可以将字符串作为哈希的值:

> %s<Hello> = 'World'
World

> %s<42> = 'Fourty-two'
Fourty-two

但这个哈希不能保存整数:

> %s<x> = 100
Type check failed in assignment to %s;
expected Str but got Int (100)
  in block <unit> at <unknown file> line 1

(顺便提一下, 在 %s<42> 的情况下, 键是一个字符串。)

要指定第二个维度的类型, 即散列键的类型, 请在花括号中指定键的类型:

my %r{Rat};

这个变量也被称为对象散列(object hash)。

有了这个, Perl 允许使用 Rat 类型作为键:

> %r<22/7> = pi
3.14159265358979

> %r
{22/7 => 3.14159265358979}

尝试使用整数或字符串作为键则会失败, 例如:

> %r<Hello> = 1
Type check failed in binding to parameter 'key';
expected Rat but got Str ("Hello")
  in block <unit> at <unknown file> line 1

> %r{23} = 32
Type check failed in binding to parameter 'key';
expected Rat but got Int (23)
  in block <unit> at <unknown file> line 1

最后, 你可以同时指定键和值的类型:

my Str %m{Int};

此变量可用于将月份编号转换为月份名称, 但反过来不行:

> %m{3} = 'March'
March

> %m<March> = 3
Type check failed in binding to parameter 'key';
expected Int but got Str ("March")
  in block <unit> at <unknown file> line 1
comments powered by Disqus