Perl 6 有命名元组吗?

Does Perl 6 have named tuples?

我知道 Swift 已命名元组:

let twostraws = (name: "twostraws", password: "fr0st1es")

所以我可以说:

print(twostraws.name)  # twostraws

但在 Perl 6 中我会说:

my $list = (twostraws, fr0st1es);
say $list[0];

哪个不如Swift厉害,所以我想知道Perl 6中是否有命名元组?

看起来您要查找的 Perl 6 中的类型是散列。

查看相关文档:

这是一个 Perl 6 示例,应该等同于您的 Swift 示例:

my %twostraws = name => 'twostraws', password => 'fr0st1es';

print %twostraws<name>; # twostraws

perl6 的等价物是 Pair type and its constructor operator is =>。它们是不可变的 - 一旦创建,键和值就不能更改;

$ perl6
> my $destination = "Name" => "Sydney" ;
Name => Sydney
> say $destination.WHAT ;
(Pair)
> $destination.value = "London";
Cannot modify an immutable Str
  in block <unit> at <unknown file> line 1

>

与 perl5 中的 "fat comma" 一样,如果构造函数是单个标识符,则构造函数不需要将左侧引用。有一种称为 "colon pair" 的表示对的替代语法。您可以将多个 Pairs 收集到一个列表中,但它们只能按位置访问;

> $destination = ( Name => "Sydney" , :Direction("East") , :Miles(420) );
(Name => Sydney Direction => East Miles => 420)
> say $destination.WHAT ;
(List)
> say $destination[1] ;
Direction => East
>

冒号对语法有方便的变体 - 如果值是字符串,您可以用尖括号替换圆括号并去掉引号。如果该值是一个整数,您可以在 值之后立即 列出键,不带引号。如果值为布尔值,则可以在值为 True 时单独列出键,或者在值为 False 时以 ! 为前缀。

最后,您可以将它们中的一些分配到一个散列中,其中的值可以通过键访问并且是可变的;

> my %destination = ( :Name<Sydney> , :Direction<East> , :420miles , :!visited ) ;
Direction => East, Name => Sydney, miles => 420, visited => False
> say %destination<miles> ;
420
> %destination<visited> = True ;
True
>

枚举可以具有非 Int 的值类型。您将它们声明为对列表。

enum Twostraws (name => "twostraws", password => "fr0st1es");
say name; # OUTPUT«twostraws␤»
say password; # OUTPUT«fr0st1es␤»
say name ~~ Twostraws, password ~~ Twostraws; # OUTPUT«TrueTrue␤»
say name.key, ' ', name.value; # OUTPUT«name twostraws␤»

enum 声明的类型可以像任何其他类型一样使用。

sub picky(Twostraws $p){ dd $p };
picky(password); # OUTPUT«Twostraws::password␤»

编辑:见https://github.com/perl6/roast/blob/master/S12-enums/non-int.t

有多种方法可以得到类似的东西。

  • 简单哈希(推荐)

    my \twostraws = %( 'name' => 'twostraws', 'password' => 'fr0st1es' );
    print twostraws<name>; # twostraws{ qw'name' }
    
  • 混合两种方法的列表

    my \twostraws = ( 'twostraws', 'fr0st1es' ) but role {
      method name     () { self[0] }
      method password () { self[1] }
    }
    
    put twostraws.name; # `put` is like `print` except it adds a newline
    
  • 匿名class

    my \twostraws = class :: {
      has ($.name, $.password)
    }.new( :name('twostraws'), :password('fr0st1es') )
    
    say twostraws.name; # `say` is like `put` but calls the `.gist` method
    

可能还有很多我还没有想到。真正的问题是您将如何在其余代码中使用它。