首页 > 解决方案 > Any.match 是做什么的?

问题描述

它具有看似简单的代码:

 method match(Any:U: |) { self.Str; nqp::getlexcaller('$/') = Nil }

但是,这是它的行为:

(^3).match(1) # OUTPUT: «「1」␤»

到现在为止还挺好。

say (1,3 ... * ).match(77); # OUTPUT: «Nil␤»

哎呀。现在发生了什么?

say (1,3 ... * ).match(1);    # OUTPUT: «Nil␤»
say (1,3 ... * ).match(/\d/); # OUTPUT: «Nil␤»

不喜欢序列。

say (^10).match(/\d/); # OUTPUT: «「0」␤»

好吧,又说得通了。

say <a b c>.match(/\w/); # OUTPUT: «「a」␤»

恢复正常。那么它不喜欢Seqs吗?我假设,因为我查看了其他类的代码并且match没有重新实现,所以它们都在调用该代码。但是我看不到从 NPQ 返回字符串和设置变量是如何做到的,或者为什么它在序列上不起作用。

标签: matchrakuseqstringification

解决方案


.match是在单个干草堆字符串中搜索针。一个无限序列串化为'...'

say (1,3 ... 9).Str;        # 1 3 5 7 9
say (1,3 ... 9).match: '1'; # 「1」

say (1,3 ... *).Str;        # ...
say (1,3 ... *).match: '.'; # 「.」

我是如何解决这个问题的

首先,您正在查看错误的方法定义:

method match(Any:U: |) { ... }

Any:U is kinda like Any $ where not .defined except if it matched you would get the error message "Parameter '<anon>' of routine 'match' must be a type object of type 'Any', not an object instance ...".

But you're passing a defined Seq. So your .match calls don't dispatch to the method definition you're looking at.

To find out what a method dispatches to, use:

say (1,3 ... *).^lookup('match').package ; # (Cool)

A defined Seq will thus dispatch to the Cool code:

method match(Cool:D: |c) {
    ...
    self.Stringy.match(|c)
}

So, next:

say (1,3 ... *).^lookup('Stringy').package ; # (Mu)

And the code:

multi method Stringy(Mu:D $:) { self.Str }

So check:

say (1,3 ... *).Str; # ...

Bingo.

And confirm:

say (1,3 ... *).match: '.'; # 「.」

推荐阅读